use crate::process::contracts::ProcessActionIntent;
#[cfg(windows)]
use super::windows_shell;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ShellKind {
Bash,
#[cfg(windows)]
PowerShell,
#[cfg(windows)]
Cmd,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ShellProcessInput<'a> {
pub(super) kind: ShellKind,
pub(super) shell: &'a str,
pub(super) flag: &'a str,
pub(super) script: &'a str,
}
impl<'a> ShellProcessInput<'a> {
pub(crate) const fn kind(self) -> ShellKind {
self.kind
}
pub(crate) const fn shell(self) -> &'a str {
self.shell
}
pub(crate) const fn flag(self) -> &'a str {
self.flag
}
pub(crate) const fn script(self) -> &'a str {
self.script
}
pub(crate) const fn script_bytes(self) -> usize {
self.script.len()
}
pub(crate) fn script_fingerprint(self) -> String {
stable_process_input_fingerprint(self.script.as_bytes())
}
}
pub(crate) fn shell_process_input(intent: &ProcessActionIntent) -> Option<ShellProcessInput<'_>> {
shell_process_input_from_argv(intent.argv())
}
pub(crate) fn shell_command_argv(command: &str) -> Vec<String> {
#[cfg(windows)]
{
windows_shell::detect_windows_shell().command_argv(command)
}
#[cfg(not(windows))]
{
vec!["bash".to_owned(), "-lc".to_owned(), command.to_owned()]
}
}
pub(crate) fn shell_command_from_argv(argv: &[String]) -> Option<&str> {
#[cfg(windows)]
{
match argv {
[shell, no_profile, non_interactive, flag, command]
if matches!(executable_name(shell).as_str(), "powershell" | "pwsh")
&& no_profile.eq_ignore_ascii_case("-NoProfile")
&& non_interactive.eq_ignore_ascii_case("-NonInteractive")
&& flag.eq_ignore_ascii_case("-Command") =>
{
Some(command)
}
[shell, no_profile, flag, command]
if matches!(executable_name(shell).as_str(), "powershell" | "pwsh")
&& no_profile.eq_ignore_ascii_case("-NoProfile")
&& flag.eq_ignore_ascii_case("-Command") =>
{
Some(command)
}
[shell, flag, command]
if executable_name(shell) == "bash" && matches!(flag.as_str(), "-c" | "-lc") =>
{
Some(command)
}
[shell, flag, command]
if executable_name(shell) == "cmd" && flag.eq_ignore_ascii_case("/C") =>
{
Some(command)
}
_ => None,
}
}
#[cfg(not(windows))]
{
match argv {
[shell, flag, command] if shell == "bash" && matches!(flag.as_str(), "-c" | "-lc") => {
Some(command)
}
_ => None,
}
}
}
#[must_use]
pub fn shell_command_for_argv(argv: &[String]) -> String {
if let Some(command) = shell_command_from_argv(argv) {
return command.to_owned();
}
argv.iter()
.map(|argument| shell_quote_argument(argument))
.collect::<Vec<_>>()
.join(" ")
}
#[cfg(not(windows))]
pub(super) fn shell_quote_argument(argument: &str) -> String {
if !argument.is_empty() && argument.bytes().all(is_safe_shell_word_byte) {
return argument.to_owned();
}
format!("'{}'", argument.replace('\'', "'\\''"))
}
#[cfg(windows)]
pub(super) fn shell_quote_argument(argument: &str) -> String {
if !argument.is_empty() && argument.bytes().all(is_safe_shell_word_byte) {
return argument.to_owned();
}
format!("'{}'", argument.replace('\'', "''"))
}
pub(super) fn is_safe_shell_word_byte(byte: u8) -> bool {
byte.is_ascii_alphanumeric()
|| matches!(
byte,
b'_' | b'-' | b'.' | b'/' | b':' | b'=' | b'@' | b'%' | b'+'
)
}
pub(super) fn shell_process_input_from_argv(argv: &[String]) -> Option<ShellProcessInput<'_>> {
#[cfg(windows)]
{
match argv {
[shell, no_profile, non_interactive, flag, script]
if is_supported_plain_shell_token(shell)
&& no_profile.eq_ignore_ascii_case("-NoProfile")
&& non_interactive.eq_ignore_ascii_case("-NonInteractive")
&& flag.eq_ignore_ascii_case("-Command") =>
{
Some(ShellProcessInput {
kind: ShellKind::PowerShell,
shell,
flag,
script,
})
}
[shell, no_profile, flag, script]
if is_supported_plain_shell_token(shell)
&& no_profile.eq_ignore_ascii_case("-NoProfile")
&& flag.eq_ignore_ascii_case("-Command") =>
{
Some(ShellProcessInput {
kind: ShellKind::PowerShell,
shell,
flag,
script,
})
}
[shell, flag, script]
if is_supported_plain_bash_token(shell)
&& matches!(flag.as_str(), "-c" | "-lc") =>
{
Some(ShellProcessInput {
kind: ShellKind::Bash,
shell,
flag,
script,
})
}
_ => None,
}
}
#[cfg(not(windows))]
{
let [shell, flag, script] = argv else {
return None;
};
if !is_supported_plain_shell_token(shell) || !matches!(flag.as_str(), "-c" | "-lc") {
return None;
}
Some(ShellProcessInput {
kind: ShellKind::Bash,
shell,
flag,
script,
})
}
}
pub(super) fn is_supported_plain_shell_token(shell: &str) -> bool {
#[cfg(windows)]
{
!shell.contains(['/', '\\'])
&& matches!(executable_name(shell).as_str(), "powershell" | "pwsh")
}
#[cfg(not(windows))]
matches!(shell, "bash" | "sh" | "zsh")
}
#[cfg(windows)]
fn is_supported_plain_bash_token(shell: &str) -> bool {
if !shell.contains(['/', '\\']) {
return matches!(executable_name(shell).as_str(), "bash" | "sh" | "zsh");
}
matches!(
windows_shell::detect_windows_shell(),
windows_shell::WindowsShell::GitBash(path)
if path.to_string_lossy().eq_ignore_ascii_case(shell)
)
}
pub(crate) fn stable_process_input_fingerprint(bytes: &[u8]) -> String {
const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
let hash = bytes.iter().fold(FNV_OFFSET_BASIS, |hash, byte| {
(hash ^ u64::from(*byte)).wrapping_mul(FNV_PRIME)
});
format!("fnv1a64:{hash:016x}")
}
pub(super) fn shell_like_process_input_from_argv(argv: &[String]) -> Option<ShellProcessInput<'_>> {
#[cfg(windows)]
{
match argv {
[shell, no_profile, non_interactive, flag, script]
if matches!(executable_name(shell).as_str(), "powershell" | "pwsh")
&& no_profile.eq_ignore_ascii_case("-NoProfile")
&& non_interactive.eq_ignore_ascii_case("-NonInteractive")
&& flag.eq_ignore_ascii_case("-Command") =>
{
Some(ShellProcessInput {
kind: ShellKind::PowerShell,
shell,
flag,
script,
})
}
[shell, no_profile, flag, script]
if matches!(executable_name(shell).as_str(), "powershell" | "pwsh")
&& no_profile.eq_ignore_ascii_case("-NoProfile")
&& flag.eq_ignore_ascii_case("-Command") =>
{
Some(ShellProcessInput {
kind: ShellKind::PowerShell,
shell,
flag,
script,
})
}
[shell, flag, script]
if matches!(executable_name(shell).as_str(), "bash" | "sh" | "zsh")
&& matches!(flag.as_str(), "-c" | "-lc") =>
{
Some(ShellProcessInput {
kind: ShellKind::Bash,
shell,
flag,
script,
})
}
[shell, flag, script]
if executable_name(shell) == "cmd" && flag.eq_ignore_ascii_case("/C") =>
{
Some(ShellProcessInput {
kind: ShellKind::Cmd,
shell,
flag,
script,
})
}
_ => None,
}
}
#[cfg(not(windows))]
{
let [shell, flag, script] = argv else {
return None;
};
if !is_supported_shell_executable_name(shell) || !matches!(flag.as_str(), "-c" | "-lc") {
return None;
}
Some(ShellProcessInput {
kind: ShellKind::Bash,
shell,
flag,
script,
})
}
}
#[cfg(not(windows))]
pub(super) fn is_supported_shell_executable_name(shell: &str) -> bool {
matches!(executable_name(shell).as_str(), "bash" | "sh" | "zsh")
}
pub(super) struct BashSecurityAnalysis {
pub(super) commands: Vec<Vec<String>>,
pub(super) env_injection: bool,
pub(super) has_command_substitution: bool,
pub(super) path_check_tokens: Vec<String>,
}
const INJECTION_ENV_KEYS: &[&str] = &[
"LD_PRELOAD",
"LD_AUDIT",
"BASH_ENV",
"ENV",
"IFS",
"PATH",
"GIT_EXTERNAL_DIFF",
"GIT_PROXY_COMMAND",
"PROMPT_COMMAND",
];
const INJECTION_ENV_KEY_PREFIXES: &[&str] = &["DYLD_", "GIT_CONFIG"];
pub(super) fn is_injection_env_key(key: &str) -> bool {
INJECTION_ENV_KEYS.contains(&key)
|| INJECTION_ENV_KEY_PREFIXES
.iter()
.any(|prefix| key.starts_with(prefix))
}
pub(super) fn parse_plain_shell_command_sequence(script: &str) -> Option<Vec<Vec<String>>> {
#[cfg(feature = "bash-ast")]
{
super::bash_ast::parse_plain_shell_command_sequence(script)
}
#[cfg(not(feature = "bash-ast"))]
{
let _ = script;
None
}
}
pub(super) fn parse_bash_security_analysis(script: &str) -> Option<BashSecurityAnalysis> {
#[cfg(feature = "bash-ast")]
{
super::bash_ast::parse_bash_security_analysis(script)
}
#[cfg(not(feature = "bash-ast"))]
{
let _ = script;
None
}
}
pub(super) fn command_words_have_env_injection(words: &[String]) -> bool {
let mut index = 0;
while let Some(head) = words.get(index) {
let name = executable_name(head);
if name == "env" {
let mut options_done = false;
for arg in &words[index + 1..] {
if !options_done && arg == "--" {
options_done = true;
continue;
}
if !options_done && arg.starts_with('-') {
if arg == "-S"
|| arg.starts_with("-S")
|| arg == "--split-string"
|| arg.starts_with("--split-string=")
|| (!arg.starts_with("--") && arg.contains('S'))
{
return true;
}
continue;
}
if let Some((key, _)) = arg.split_once('=') {
if is_injection_env_key(key) {
return true;
}
continue;
}
break;
}
return false;
}
if matches!(
head.as_str(),
"!" | "time" | "exec" | "command" | "builtin" | "nohup"
) {
index += 1;
continue;
}
if name == "timeout" {
index += 1;
while let Some(arg) = words.get(index) {
if matches!(arg.as_str(), "-k" | "--kill-after" | "-s" | "--signal") {
index += 2;
continue;
}
if arg.starts_with('-') {
index += 1;
continue;
}
index += 1;
break;
}
continue;
}
break;
}
false
}
pub(super) fn executable_name(argument: &str) -> String {
let base = argument
.rsplit(['/', '\\'])
.next()
.unwrap_or(argument)
.to_ascii_lowercase();
for suffix in [".exe", ".cmd", ".bat", ".com"] {
if let Some(stripped) = base.strip_suffix(suffix)
&& !stripped.is_empty()
{
return stripped.to_owned();
}
}
base
}
pub(super) fn executable_token_is(argument: &str, expected: &str) -> bool {
#[cfg(windows)]
{
argument.eq_ignore_ascii_case(expected)
|| argument
.strip_suffix(".exe")
.or_else(|| argument.strip_suffix(".EXE"))
.is_some_and(|stripped| stripped.eq_ignore_ascii_case(expected))
}
#[cfg(not(windows))]
{
argument == expected
}
}