#[cfg(windows)]
use crate::process::classification::windows_shell::{
analyze_powershell_script, parse_plain_powershell_command_sequence,
};
use crate::process::{
classification::shell::{
ShellKind, command_words_have_env_injection, executable_name, executable_token_is,
parse_bash_security_analysis, parse_plain_shell_command_sequence,
shell_like_process_input_from_argv, shell_process_input_from_argv,
},
contracts::{
AcceptedLocalWorkspaceProcessAdmission, ProcessActionIntent, ProcessEnvPolicy,
ProcessPermissionProfileId,
},
};
pub use shell::shell_command_for_argv;
pub(crate) use shell::{shell_command_argv, shell_process_input, stable_process_input_fingerprint};
use std::path::Path;
pub use windows_shell::{
host_shell_chain_separator, host_shell_has_unix_utilities, host_shell_name,
};
#[cfg(feature = "bash-ast")]
mod bash_ast;
mod git;
mod shell;
mod triggers;
mod windows_shell;
pub use triggers::{
ActionReviewTrigger, classify_process_action_review_triggers, summarize_action_review_triggers,
};
use git::{git_invocation_is_forbidden, is_read_only_git_command};
impl AcceptedLocalWorkspaceProcessAdmission {
pub(crate) fn matches_intent(self, intent: &ProcessActionIntent) -> bool {
let required = required_process_permission_profile_id(intent);
(self.sandbox_profile() == super::contracts::LocalWorkspaceProcessSandboxProfile::Host
&& required.is_some())
|| required == Some(self.permission_profile_id())
|| (self.permission_profile_id() == ProcessPermissionProfileId::LOCAL_WORKSPACE_HOST
&& required == Some(ProcessPermissionProfileId::LOCAL_WORKSPACE))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProcessIntentClass {
Informational,
LocalWorkspaceEffect,
Unknown,
Forbidden,
}
#[must_use]
pub fn classify_process_intent(intent: &ProcessActionIntent) -> ProcessIntentClass {
classify_process_argv(intent.argv())
}
fn classify_process_argv(argv: &[String]) -> ProcessIntentClass {
if is_forbidden_process_argv(argv) {
return ProcessIntentClass::Forbidden;
}
if is_informational_process_argv(argv) {
return ProcessIntentClass::Informational;
}
if is_local_workspace_effect_process_argv(argv) {
return ProcessIntentClass::LocalWorkspaceEffect;
}
ProcessIntentClass::Unknown
}
fn is_informational_process_argv(argv: &[String]) -> bool {
if is_read_only_direct_process_argv(argv) {
return true;
}
is_read_only_plain_shell_process_argv(argv)
}
pub(super) fn is_read_only_direct_process_argv(argv: &[String]) -> bool {
match argv {
[executable, version]
if executable_token_is(executable, "rustc") && version.as_str() == "--version" =>
{
true
}
[executable, rg_arg] if executable_token_is(executable, "rg") => {
is_read_only_rg_single_argument(rg_arg)
}
[executable, print_flag, range, file]
if executable_token_is(executable, "sed")
&& print_flag.as_str() == "-n"
&& is_read_only_sed_print_range(range)
&& is_workspace_relative_file_argument(file) =>
{
true
}
[executable, subcommand, args @ ..] if executable_token_is(executable, "git") => {
is_read_only_git_command(subcommand, args)
}
[executable, version]
if executable_token_is(executable, "git") && version.as_str() == "--version" =>
{
true
}
[executable] if executable_token_is(executable, "pwd") => true,
[executable] if executable_token_is(executable, "true") => true,
[executable] if executable_token_is(executable, "false") => true,
[executable, args @ ..] if executable_token_is(executable, "echo") => {
is_read_only_echo_args(args)
}
[executable, args @ ..] if executable_token_is(executable, "wc") => {
is_read_only_wc_args(args)
}
[executable, args @ ..] if executable_token_is(executable, "head") => {
is_read_only_head_or_tail_args(args)
}
[executable, args @ ..] if executable_token_is(executable, "tail") => {
is_read_only_head_or_tail_args(args)
}
[executable, args @ ..] if executable_token_is(executable, "cargo") => {
is_read_only_cargo_fmt_check_args(args)
}
[executable] if executable_token_is(executable, "ls") => true,
[executable, file] if executable_token_is(executable, "ls") => {
is_workspace_relative_file_argument(file)
}
[executable, file] if executable_token_is(executable, "cat") => {
is_workspace_relative_file_argument(file)
}
[executable] if executable.eq_ignore_ascii_case("get-location") => true,
[executable] if executable.eq_ignore_ascii_case("get-childitem") => true,
[executable, file] if executable.eq_ignore_ascii_case("get-childitem") => {
is_workspace_relative_file_argument(file)
}
[executable, file] if executable.eq_ignore_ascii_case("get-content") => {
is_workspace_relative_file_argument(file)
}
_ => false,
}
}
fn is_read_only_cargo_fmt_check_args(args: &[String]) -> bool {
let mut saw_fmt = false;
let mut saw_check = false;
for argument in args {
match argument.as_str() {
"fmt" if !saw_fmt => saw_fmt = true,
"--all" | "--check" if !saw_check || argument == "--all" => {
if argument == "--check" {
saw_check = true;
}
}
_ => return false,
}
}
saw_fmt && saw_check
}
fn is_read_only_plain_shell_process_argv(argv: &[String]) -> bool {
let Some(shell_input) = shell_process_input_from_argv(argv) else {
return false;
};
let commands = match shell_input.kind() {
ShellKind::Bash => parse_plain_shell_command_sequence(shell_input.script()),
#[cfg(windows)]
ShellKind::PowerShell => parse_plain_powershell_command_sequence(shell_input.script()),
#[cfg(windows)]
ShellKind::Cmd => None,
};
commands.is_some_and(|commands| {
!commands.is_empty()
&& commands
.iter()
.all(|command| is_read_only_direct_process_argv(command))
})
}
fn is_read_only_echo_args(args: &[String]) -> bool {
!args.iter().any(|arg| arg.starts_with('-'))
}
fn is_read_only_wc_args(args: &[String]) -> bool {
match args {
[] => true,
[flag_or_file] => {
is_read_only_wc_flag(flag_or_file) || is_workspace_relative_file_argument(flag_or_file)
}
[flag, file] => is_read_only_wc_flag(flag) && is_workspace_relative_file_argument(file),
_ => false,
}
}
fn is_read_only_wc_flag(flag: &str) -> bool {
matches!(flag, "-l" | "-w" | "-c" | "-m")
}
fn is_read_only_head_or_tail_args(args: &[String]) -> bool {
match args {
[] => true,
[file] => is_workspace_relative_file_argument(file),
[count_flag, count] if count_flag.as_str() == "-n" => is_positive_decimal(count),
[count_flag, count, file] if count_flag.as_str() == "-n" => {
is_positive_decimal(count) && is_workspace_relative_file_argument(file)
}
_ => false,
}
}
fn is_read_only_rg_single_argument(argument: &str) -> bool {
argument == "--version" || argument == "--files" || is_simple_rg_literal_pattern(argument)
}
fn is_simple_rg_literal_pattern(pattern: &str) -> bool {
!pattern.starts_with('-') && !pattern.chars().any(is_rg_regex_metacharacter)
}
fn is_rg_regex_metacharacter(character: char) -> bool {
matches!(
character,
'\\' | '.' | '^' | '$' | '*' | '+' | '?' | '(' | ')' | '[' | ']' | '{' | '}' | '|'
)
}
fn is_read_only_sed_print_range(range: &str) -> bool {
let Some(line_range) = range.strip_suffix('p') else {
return false;
};
if line_range.is_empty() {
return false;
}
let mut parts = line_range.split(',');
let Some(start) = parts.next() else {
return false;
};
if !is_positive_decimal(start) {
return false;
}
match (parts.next(), parts.next()) {
(None, None) => true,
(Some(end), None) => is_positive_decimal(end),
_ => false,
}
}
pub(super) fn is_positive_decimal(value: &str) -> bool {
!value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()) && value != "0"
}
pub(super) fn is_workspace_relative_file_argument(argument: &str) -> bool {
if argument.starts_with('-')
|| Path::new(argument).is_absolute()
|| has_windows_drive_prefix(argument)
{
return false;
}
#[cfg(windows)]
{
!argument.starts_with(['/', '\\'])
&& !argument
.split(['/', '\\'])
.any(|segment| segment.is_empty() || segment == "." || segment == "..")
}
#[cfg(not(windows))]
{
!argument.split('/').any(|segment| {
segment.is_empty() || segment == "." || segment == ".." || segment.contains('\\')
})
}
}
fn is_local_workspace_effect_process_argv(argv: &[String]) -> bool {
matches!(
argv,
[cargo, command, package_flag, package]
if executable_token_is(cargo, "cargo")
&& matches!(command.as_str(), "test" | "check")
&& (package_flag.as_str() == "-p" || package_flag.as_str() == "--package")
&& is_safe_cargo_package_token(package)
)
}
pub(crate) fn is_safe_cargo_package_token(package: &str) -> bool {
!package.is_empty()
&& !package.starts_with('-')
&& package
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
}
fn is_forbidden_process_argv(argv: &[String]) -> bool {
if let Some(shell_input) = shell_like_process_input_from_argv(argv) {
return shell_script_contains_forbidden_process(shell_input.kind(), shell_input.script());
}
is_forbidden_direct_process_argv(argv)
}
fn is_forbidden_direct_process_argv(argv: &[String]) -> bool {
if command_words_have_env_injection(argv) {
return true;
}
let argv = strip_shell_command_prefixes(argv);
let Some(executable) = argv.first().map(|argument| executable_name(argument)) else {
return false;
};
if executable == "rm" {
return rm_invocation_requires_review(argv);
}
if FORBIDDEN_PROCESS_EXECUTABLES.contains(&executable.as_str()) {
return true;
}
if executable == "git" {
return git_invocation_is_forbidden(argv);
}
false
}
pub(super) fn strip_shell_command_prefixes(mut argv: &[String]) -> &[String] {
for _ in 0..8 {
let Some(first) = argv.first() else {
return argv;
};
if matches!(
first.as_str(),
"!" | "time" | "exec" | "command" | "builtin" | "nohup"
) {
argv = &argv[1..];
continue;
}
let head = executable_name(first);
if head == "env" {
let mut idx = 1;
let mut options_done = false;
while let Some(arg) = argv.get(idx) {
if !options_done && arg == "--" {
options_done = true;
idx += 1;
continue;
}
if !options_done && arg.starts_with('-') {
idx += 1;
continue;
}
if arg.contains('=') && !arg.starts_with('=') {
idx += 1;
continue;
}
break;
}
argv = &argv[idx..];
continue;
}
if head == "timeout" {
let mut idx = 1;
while let Some(arg) = argv.get(idx) {
if matches!(arg.as_str(), "-k" | "--kill-after" | "-s" | "--signal") {
idx += 2;
continue;
}
if arg.starts_with('-') {
idx += 1;
continue;
}
idx += 1;
break;
}
argv = argv.get(idx..).unwrap_or(&[]);
continue;
}
break;
}
argv
}
fn shell_script_contains_forbidden_process(kind: ShellKind, script: &str) -> bool {
match kind {
ShellKind::Bash => {
let Some(analysis) = parse_bash_security_analysis(script) else {
return true;
};
analysis.env_injection
|| analysis
.commands
.iter()
.any(|command| is_forbidden_direct_process_argv(command))
}
#[cfg(windows)]
ShellKind::PowerShell => {
let Some(analysis) = analyze_powershell_script(script) else {
return true;
};
analysis.env_or_eval_injection
|| analysis.has_destructive_delete
|| analysis
.commands
.iter()
.any(|command| is_forbidden_direct_process_argv(command))
}
#[cfg(windows)]
ShellKind::Cmd => true,
}
}
const FORBIDDEN_PROCESS_EXECUTABLES: &[&str] = &[
"bash",
"cmd",
"powershell",
"pwsh",
"sh",
"su",
"sudo",
"zsh",
];
fn rm_invocation_requires_review(argv: &[String]) -> bool {
rm_review_target(argv).is_some()
}
pub(super) fn rm_review_target(argv: &[String]) -> Option<Option<String>> {
let mut operands = Vec::new();
let mut end_of_flags = false;
let mut recursive = false;
for argument in argv.iter().skip(1) {
if !end_of_flags && argument == "--" {
end_of_flags = true;
continue;
}
if !end_of_flags && argument.starts_with('-') {
if rm_flag_requires_review(argument) {
recursive = true;
}
continue;
}
operands.push(argument.as_str());
}
if recursive
|| operands.is_empty()
|| operands
.iter()
.any(|operand| rm_operand_requires_review(operand))
{
return Some(operands.first().map(|target| (*target).to_owned()));
}
None
}
fn rm_flag_requires_review(flag: &str) -> bool {
if flag == "--recursive" || flag == "--dir" {
return true;
}
let Some(cluster) = flag.strip_prefix('-') else {
return false;
};
if cluster.starts_with('-') {
return false;
}
cluster
.chars()
.any(|character| matches!(character, 'r' | 'R'))
}
fn rm_operand_requires_review(operand: &str) -> bool {
operand.is_empty()
|| operand == "."
|| operand == ".."
|| operand == "/"
|| operand == "*"
|| operand == "~"
|| operand.ends_with("/*")
|| operand
.chars()
.any(|character| matches!(character, '*' | '?' | '[' | '{' | '$' | '`'))
}
#[must_use]
pub fn is_low_risk_process_action_intent(intent: &ProcessActionIntent) -> bool {
required_process_permission_profile_id(intent) == Some(ProcessPermissionProfileId::READ_ONLY)
}
#[must_use]
pub fn is_read_only_shell_process_action_intent(intent: &ProcessActionIntent) -> bool {
required_process_permission_profile_id(intent)
== Some(ProcessPermissionProfileId::SHELL_READ_ONLY)
}
pub(crate) fn required_process_permission_profile_id(
intent: &ProcessActionIntent,
) -> Option<ProcessPermissionProfileId> {
if intent.env_policy() != ProcessEnvPolicy::Empty || intent.stdin_text().is_some() {
return Some(ProcessPermissionProfileId::LOCAL_WORKSPACE);
}
if is_read_only_plain_shell_process_argv(intent.argv()) {
return Some(ProcessPermissionProfileId::SHELL_READ_ONLY);
}
match classify_process_intent(intent) {
ProcessIntentClass::Informational => Some(ProcessPermissionProfileId::READ_ONLY),
ProcessIntentClass::LocalWorkspaceEffect => {
Some(ProcessPermissionProfileId::LOCAL_WORKSPACE)
}
ProcessIntentClass::Unknown => Some(ProcessPermissionProfileId::LOCAL_WORKSPACE),
ProcessIntentClass::Forbidden => Some(ProcessPermissionProfileId::LOCAL_WORKSPACE),
}
}
#[cfg(test)]
#[must_use]
pub(crate) fn requires_process_action_review(intent: &ProcessActionIntent) -> bool {
matches!(
classify_process_intent(intent),
ProcessIntentClass::Forbidden
)
}
fn has_windows_drive_prefix(value: &str) -> bool {
let bytes = value.as_bytes();
bytes.len() >= 2
&& bytes[0].is_ascii_alphabetic()
&& bytes[1] == b':'
&& (bytes.len() == 2 || matches!(bytes[2], b'\\' | b'/'))
}