aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
[
|
||||
{"name":"echo","script":"echo hi","expected":[["echo","hi"]]},
|
||||
{"name":"single_quote","script":"Get-Content 'foo bar'","expected":[["Get-Content","foo bar"]]},
|
||||
{"name":"quoted_comma","script":"Get-Content 'foo,bar'","expected":[["Get-Content","foo,bar"]]},
|
||||
{"name":"double_quote","script":"Get-Content \"foo bar\"","expected":[["Get-Content","foo bar"]]},
|
||||
{"name":"doubled_single_quote","script":"Write-Output 'a''b'","expected":[["Write-Output","a'b"]]},
|
||||
{"name":"escaped_double_quote","script":"Write-Output \"a`\"b\"","expected":[["Write-Output","a\"b"]]},
|
||||
{"name":"powershell_7_escape_in_double_quote","script":"rg \"--pr`e=helper.exe\" pattern","expected":null},
|
||||
{"name":"unicode_escape_in_double_quote","script":"rg \"--pre=`u{68}elper.exe\" pattern","expected":null},
|
||||
{"name":"escaped_space","script":"Get-Content foo` bar","expected":[["Get-Content","foo bar"]]},
|
||||
{"name":"powershell_7_escape_in_bare_word","script":"rg --pr`e helper.exe pattern","expected":null},
|
||||
{"name":"command_parameter","script":"Get-ChildItem -Path .","expected":[["Get-ChildItem","-Path","."]]},
|
||||
{"name":"attached_parameter_argument","script":"Get-Content -Path:1","expected":null},
|
||||
{"name":"attached_quoted_parameter_argument","script":"Get-Content -Path:'foo bar'","expected":null},
|
||||
{"name":"pipeline","script":"Write-Output foo | Measure-Object","expected":[["Write-Output","foo"],["Measure-Object"]]},
|
||||
{"name":"semicolon","script":"Get-Content Cargo.toml; Test-Path Cargo.toml","expected":[["Get-Content","Cargo.toml"],["Test-Path","Cargo.toml"]]},
|
||||
{"name":"and_chain","script":"pwd && ls","expected":[["pwd"],["ls"]]},
|
||||
{"name":"or_chain","script":"pwd || ls","expected":[["pwd"],["ls"]]},
|
||||
{"name":"parenthesized_command","script":"(Get-Content foo.rs -Raw)","expected":null},
|
||||
{"name":"parenthesized_pipeline","script":"(Get-Content foo | Measure-Object)","expected":null},
|
||||
{"name":"parenthesized_chain","script":"(pwd && ls)","expected":null},
|
||||
{"name":"canonical_numeric_argument","script":"Get-Content -TotalCount 100","expected":[["Get-Content","-TotalCount","100"]]},
|
||||
{"name":"negative_numeric_argument","script":"git log -1 Cargo.toml","expected":[["git","log","-1","Cargo.toml"]]},
|
||||
{"name":"hexadecimal_numeric_argument","script":"Write-Output 0x10","expected":null},
|
||||
{"name":"signed_hexadecimal_numeric_argument","script":"Write-Output 0xFFFFFFFF","expected":null},
|
||||
{"name":"binary_numeric_argument","script":"Write-Output 0b101","expected":null},
|
||||
{"name":"type_suffixed_numeric_argument","script":"Write-Output 1d","expected":null},
|
||||
{"name":"powershell_7_type_suffixed_numeric_argument","script":"Write-Output 1u","expected":null},
|
||||
{"name":"size_suffixed_numeric_argument","script":"Write-Output 1kb","expected":null},
|
||||
{"name":"leading_zero_numeric_argument","script":"Write-Output 01","expected":null},
|
||||
{"name":"real_numeric_argument","script":"Write-Output 1.0","expected":null},
|
||||
{"name":"exponent_numeric_argument","script":"Write-Output 1e3","expected":null},
|
||||
{"name":"numeric_leading_filename","script":"Get-Content 1.0.0","expected":null},
|
||||
{"name":"inline_double_dash_parameter","script":"Get-Content --flag=value","expected":[["Get-Content","--flag=value"]]},
|
||||
{"name":"inline_double_dash_parameter_pipeline","script":"Get-Content --flag=value | Measure-Object","expected":[["Get-Content","--flag=value"],["Measure-Object"]]},
|
||||
{"name":"git_dir_inline","script":"git --git-dir=.git status","expected":[["git","--git-dir=.git","status"]]},
|
||||
{"name":"windows_path","script":"Get-Content C:\\tmp\\x","expected":[["Get-Content","C:\\tmp\\x"]]},
|
||||
{"name":"verbatim_here_string","script":"Write-Output @'\nhello\n'@","expected":null},
|
||||
{"name":"expandable_here_string_without_expansion","script":"Write-Output @\"\nhello\n\"@","expected":null},
|
||||
{"name":"expandable_here_string_with_escaped_dollar","script":"Write-Output @\"\n`$foo\n\"@","expected":null},
|
||||
{"name":"dangerous_literal_url","script":"Start-Process 'https://example.com'","expected":[["Start-Process","https://example.com"]]},
|
||||
{"name":"dangerous_literal_force","script":"Remove-Item test -Force","expected":[["Remove-Item","test","-Force"]]},
|
||||
{"name":"unicode_dash_parameter","script":"Remove-Item test –Force","expected":null},
|
||||
{"name":"trailing_comment","script":"Get-Content Cargo.toml # comment","expected":[["Get-Content","Cargo.toml"]]},
|
||||
{"name":"hash_inside_token","script":"Get-Content foo#bar","expected":[["Get-Content","foo#bar"]]},
|
||||
{"name":"embedded_hash_before_separator","script":"git status --short#; Remove-Item victim","expected":null},
|
||||
{"name":"smart_quote_delimiter","script":"rg “--pre=helper.exe” pattern","expected":null},
|
||||
{"name":"hash_inside_recovered_command_token","script":"pwd#evil --flag=value","expected":[["pwd#evil","--flag=value"]]},
|
||||
{"name":"block_comment_before_command","script":"<# note #>\nGet-Content foo","expected":[["Get-Content","foo"]]},
|
||||
{"name":"stop_parsing","script":"git log --% HEAD --output=codex_poc.txt","expected":null},
|
||||
{"name":"param_block","script":"param([string]$path = (Get-Location)) Write-Output test","expected":null},
|
||||
{"name":"named_blocks","script":"begin { Set-Content codex_poc.txt pwned } end { Get-Content Cargo.toml }","expected":null},
|
||||
{"name":"using_statement","script":"using module ./codex_poc.psm1\nGet-Content Cargo.toml","expected":null},
|
||||
{"name":"mixed_case_using_statement","script":"Using module ./codex_poc.psm1\nGet-Content Cargo.toml","expected":null},
|
||||
{"name":"trap_block","script":"trap { Set-Content codex_poc.txt pwned; continue } Get-Content missing -ErrorAction Stop","expected":null},
|
||||
{"name":"redirection","script":"echo hi > out.txt","expected":null},
|
||||
{"name":"invocation_operator","script":"& Remove-Item foo","expected":null},
|
||||
{"name":"nested_command","script":"Write-Output (Set-Content foo6.txt 'abc')","expected":null},
|
||||
{"name":"subexpression","script":"Write-Output $(Get-Content foo)","expected":null},
|
||||
{"name":"array_expression","script":"ls @(calc.exe)","expected":null},
|
||||
{"name":"splat","script":"Get-Content @args","expected":null},
|
||||
{"name":"empty_word","script":"''","expected":null},
|
||||
{"name":"dynamic_argument","script":"Get-Content $foo","expected":null},
|
||||
{"name":"expandable_dynamic","script":"Write-Output \"foo $bar\"","expected":null},
|
||||
{"name":"comma_form","script":"Get-Content foo,bar","expected":null},
|
||||
{"name":"single_dash_equals_is_not_recovery","script":"Get-Content -foo=bar","expected":null},
|
||||
{"name":"uncovered_closing_paren","script":"Get-Content --flag=value )","expected":null},
|
||||
{"name":"uncovered_invalid_tail","script":"Get-Content --flag=value | if (","expected":null},
|
||||
{"name":"dangling_escape_after_recovery","script":"Get-Content --flag=value `","expected":null}
|
||||
]
|
||||
@@ -0,0 +1,332 @@
|
||||
use crate::bash::parse_shell_lc_literal_commands;
|
||||
#[path = "windows_dangerous_commands.rs"]
|
||||
mod windows_dangerous_commands;
|
||||
pub use windows_dangerous_commands::powershell_commands_are_independent;
|
||||
|
||||
/// The platform whose command semantics should be used for safety checks.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum DangerousCommandPlatform {
|
||||
/// POSIX command and path semantics.
|
||||
Posix,
|
||||
/// Windows command and path semantics.
|
||||
Windows,
|
||||
}
|
||||
|
||||
impl DangerousCommandPlatform {
|
||||
/// Returns the platform where the classifier is running.
|
||||
pub fn host() -> Self {
|
||||
if cfg!(windows) {
|
||||
Self::Windows
|
||||
} else {
|
||||
Self::Posix
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Identifies the dangerous-command rule matched by a command invocation.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum DangerousCommandMatch {
|
||||
/// An `rm` invocation includes the force option.
|
||||
ForcedRm,
|
||||
/// Another dangerous-command rule matched.
|
||||
Other,
|
||||
}
|
||||
|
||||
const MAX_DANGEROUS_COMMAND_WRAPPER_DEPTH: usize = 8;
|
||||
|
||||
/// Returns the dangerous-command rule matched by an already-tokenized command.
|
||||
pub fn dangerous_command_match(command: &[String]) -> Option<DangerousCommandMatch> {
|
||||
dangerous_command_match_for_platform(command, DangerousCommandPlatform::host())
|
||||
}
|
||||
|
||||
/// Returns the dangerous-command rule matched using the target platform's semantics.
|
||||
pub fn dangerous_command_match_for_platform(
|
||||
command: &[String],
|
||||
platform: DangerousCommandPlatform,
|
||||
) -> Option<DangerousCommandMatch> {
|
||||
dangerous_command_match_with_depth(command, /*wrapper_depth*/ 0, platform)
|
||||
}
|
||||
|
||||
fn dangerous_command_match_with_depth(
|
||||
command: &[String],
|
||||
wrapper_depth: usize,
|
||||
platform: DangerousCommandPlatform,
|
||||
) -> Option<DangerousCommandMatch> {
|
||||
if wrapper_depth > MAX_DANGEROUS_COMMAND_WRAPPER_DEPTH {
|
||||
return Some(DangerousCommandMatch::Other);
|
||||
}
|
||||
|
||||
if let Some(dangerous_match) =
|
||||
dangerous_command_match_for_exec(command, wrapper_depth, platform)
|
||||
{
|
||||
return Some(dangerous_match);
|
||||
}
|
||||
|
||||
// Support shell scripts where any literal command might be dangerous,
|
||||
// including commands nested in control flow or substitutions.
|
||||
if let Some(dangerous_match) = parse_shell_lc_literal_commands(command).and_then(|commands| {
|
||||
commands.iter().find_map(|command| {
|
||||
dangerous_command_match_with_depth(command, wrapper_depth + 1, platform)
|
||||
})
|
||||
}) {
|
||||
return Some(dangerous_match);
|
||||
}
|
||||
|
||||
if platform == DangerousCommandPlatform::Windows
|
||||
&& windows_dangerous_commands::is_dangerous_command_windows(command)
|
||||
{
|
||||
return Some(DangerousCommandMatch::Other);
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// Returns the PowerShell-specific rule matched using the target platform's semantics.
|
||||
pub fn dangerous_powershell_words_match(
|
||||
command: &[String],
|
||||
platform: DangerousCommandPlatform,
|
||||
) -> Option<DangerousCommandMatch> {
|
||||
if platform == DangerousCommandPlatform::Windows {
|
||||
windows_dangerous_commands::is_dangerous_powershell_words(command)
|
||||
.then_some(DangerousCommandMatch::Other)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Classifies a strictly lowered command from an independent literal PowerShell script.
|
||||
pub fn dangerous_powershell_literal_words_match(
|
||||
command: &[String],
|
||||
) -> Option<DangerousCommandMatch> {
|
||||
windows_dangerous_commands::is_dangerous_powershell_literal_words(command)
|
||||
.then_some(DangerousCommandMatch::Other)
|
||||
}
|
||||
|
||||
fn executable_name_lookup_key(raw: &str, platform: DangerousCommandPlatform) -> Option<String> {
|
||||
match platform {
|
||||
DangerousCommandPlatform::Posix => raw
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.filter(|name| !name.is_empty())
|
||||
.map(str::to_owned),
|
||||
DangerousCommandPlatform::Windows => {
|
||||
let name = raw
|
||||
.rsplit(['/', '\\'])
|
||||
.next()
|
||||
.filter(|name| !name.is_empty())?;
|
||||
let name = match name.as_bytes() {
|
||||
[drive, b':', ..] if drive.is_ascii_alphabetic() => &name[2..],
|
||||
_ => name,
|
||||
};
|
||||
let name = name.to_ascii_lowercase();
|
||||
for suffix in [".exe", ".cmd", ".bat", ".com"] {
|
||||
if let Some(stripped) = name.strip_suffix(suffix) {
|
||||
return Some(stripped.to_string());
|
||||
}
|
||||
}
|
||||
(!name.is_empty()).then_some(name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn dangerous_command_match_for_exec(
|
||||
command: &[String],
|
||||
wrapper_depth: usize,
|
||||
platform: DangerousCommandPlatform,
|
||||
) -> Option<DangerousCommandMatch> {
|
||||
let cmd0 = command
|
||||
.first()
|
||||
.and_then(|command| executable_name_lookup_key(command, platform));
|
||||
|
||||
match cmd0.as_deref() {
|
||||
Some("rm") if rm_args_include_force_option(&command[1..]) => {
|
||||
Some(DangerousCommandMatch::ForcedRm)
|
||||
}
|
||||
|
||||
// For sudo <cmd>, simply check <cmd>.
|
||||
Some("sudo") => {
|
||||
dangerous_command_match_with_depth(&command[1..], wrapper_depth + 1, platform)
|
||||
}
|
||||
|
||||
// Skip environment assignments before checking the command run by env.
|
||||
Some("env") => dangerous_command_match_for_env(command, wrapper_depth, platform),
|
||||
|
||||
// A trap action is shell source stored in the first operand.
|
||||
Some("trap") => dangerous_command_match_for_trap(command, wrapper_depth, platform),
|
||||
|
||||
// ── anything else ─────────────────────────────────────────────────
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn dangerous_command_match_for_env(
|
||||
command: &[String],
|
||||
wrapper_depth: usize,
|
||||
platform: DangerousCommandPlatform,
|
||||
) -> Option<DangerousCommandMatch> {
|
||||
let mut command_index = 1;
|
||||
while let Some(argument) = command.get(command_index) {
|
||||
if argument == "--" {
|
||||
command_index += 1;
|
||||
break;
|
||||
}
|
||||
if matches!(argument.as_str(), "-i" | "--ignore-environment")
|
||||
|| argument
|
||||
.split_once('=')
|
||||
.is_some_and(|(name, _)| !name.is_empty() && !name.starts_with('-'))
|
||||
{
|
||||
command_index += 1;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
dangerous_command_match_with_depth(&command[command_index..], wrapper_depth + 1, platform)
|
||||
}
|
||||
|
||||
fn dangerous_command_match_for_trap(
|
||||
command: &[String],
|
||||
wrapper_depth: usize,
|
||||
platform: DangerousCommandPlatform,
|
||||
) -> Option<DangerousCommandMatch> {
|
||||
let mut action_index = 1;
|
||||
if command
|
||||
.get(action_index)
|
||||
.is_some_and(|argument| argument == "--")
|
||||
{
|
||||
action_index += 1;
|
||||
}
|
||||
let action = command
|
||||
.get(action_index)
|
||||
.filter(|action| !action.starts_with('-'))?;
|
||||
let shell_command = vec!["sh".to_string(), "-c".to_string(), action.clone()];
|
||||
dangerous_command_match_with_depth(&shell_command, wrapper_depth + 1, platform)
|
||||
}
|
||||
|
||||
fn rm_args_include_force_option(args: &[String]) -> bool {
|
||||
args.iter()
|
||||
.take_while(|arg| arg.as_str() != "--")
|
||||
.any(|arg| {
|
||||
arg == "--force"
|
||||
|| arg
|
||||
.strip_prefix('-')
|
||||
.is_some_and(|flags| !flags.starts_with('-') && flags.contains('f'))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn vec_str(items: &[&str]) -> Vec<String> {
|
||||
items.iter().map(std::string::ToString::to_string).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rm_rf_is_dangerous() {
|
||||
assert_eq!(
|
||||
dangerous_command_match(&vec_str(&["rm", "-rf", "/"])),
|
||||
Some(DangerousCommandMatch::ForcedRm)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rm_f_is_dangerous() {
|
||||
assert_eq!(
|
||||
dangerous_command_match(&vec_str(&["rm", "-f", "/"])),
|
||||
Some(DangerousCommandMatch::ForcedRm)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forced_rm_variants_are_dangerous() {
|
||||
for command in [
|
||||
vec_str(&["/bin/rm", "-fr", "/tmp/example"]),
|
||||
vec_str(&["rm", "-r", "-f", "/tmp/example"]),
|
||||
vec_str(&["rm", "--force", "/tmp/example"]),
|
||||
vec_str(&["rm", "/tmp/example", "-f"]),
|
||||
vec_str(&["sudo", "rm", "-rf", "/tmp/example"]),
|
||||
vec_str(&["env", "TARGET=/tmp/example", "rm", "-rf", "/tmp/example"]),
|
||||
] {
|
||||
assert_eq!(
|
||||
dangerous_command_match(&command),
|
||||
Some(DangerousCommandMatch::ForcedRm),
|
||||
"{command:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deeply_nested_command_wrappers_fail_closed() {
|
||||
for (depth, expected) in [
|
||||
(
|
||||
MAX_DANGEROUS_COMMAND_WRAPPER_DEPTH,
|
||||
DangerousCommandMatch::ForcedRm,
|
||||
),
|
||||
(
|
||||
MAX_DANGEROUS_COMMAND_WRAPPER_DEPTH + 1,
|
||||
DangerousCommandMatch::Other,
|
||||
),
|
||||
] {
|
||||
let command = std::iter::repeat_n("env", depth)
|
||||
.chain(["rm", "-rf", "/tmp/example"])
|
||||
.map(str::to_owned)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(dangerous_command_match(&command), Some(expected));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forced_rm_in_complex_shell_syntax_is_dangerous() {
|
||||
for script in [
|
||||
"printf x | rm -rf /tmp/example",
|
||||
"if test -d /tmp/example; then rm --force /tmp/example; fi",
|
||||
"rm -rf \"$TARGET\" >/dev/null",
|
||||
"for target in /tmp/a /tmp/b; do rm -r -f \"$target\"; done",
|
||||
"echo \"$(rm -rf /tmp/example)\"",
|
||||
"bash -c 'rm -rf /tmp/example'",
|
||||
"trap 'rm -rf /tmp/example' EXIT",
|
||||
"for a in '-C5a25KeRr' '--' '--json' '--bogus'; do HOME=$(mktemp -d) MDE_URL=http://127.0.0.1:1 MDE_TOKEN=x node cli/mde.cjs ls \"$a\" >/tmp/mde-review-out 2>/tmp/mde-review-err; code=$?; printf '%s\\t%s\\t%s\\n' \"$a\" \"$code\" \"$(tr '\\n' ' ' </tmp/mde-review-err)\"; rm -rf \"$HOME\"; done",
|
||||
] {
|
||||
let command = vec_str(&["bash", "-lc", script]);
|
||||
assert_eq!(
|
||||
dangerous_command_match(&command),
|
||||
Some(DangerousCommandMatch::ForcedRm),
|
||||
"{script}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_forced_or_non_literal_rm_is_not_dangerous() {
|
||||
for command in [
|
||||
vec_str(&["rm", "-r", "/tmp/example"]),
|
||||
vec_str(&["rm", "--", "-f"]),
|
||||
vec_str(&["bash", "-lc", "echo 'rm -rf /tmp/example'"]),
|
||||
vec_str(&["bash", "-lc", "cmd=rm; $cmd -rf /tmp/example"]),
|
||||
vec_str(&["bash", "-lc", "if then rm -rf /tmp/example"]),
|
||||
vec_str(&["env", "TARGET=/tmp/example", "rm", "-r", "/tmp/example"]),
|
||||
vec_str(&["bash", "-lc", "trap 'echo rm -rf /tmp/example' EXIT"]),
|
||||
] {
|
||||
assert_eq!(dangerous_command_match(&command), None, "{command:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_powershell_words_return_other_match_on_windows() {
|
||||
let command = vec_str(&["Remove-Item", "test", "-Force"]);
|
||||
|
||||
if cfg!(windows) {
|
||||
assert_eq!(
|
||||
dangerous_powershell_words_match(&command, DangerousCommandPlatform::host()),
|
||||
Some(DangerousCommandMatch::Other)
|
||||
);
|
||||
} else {
|
||||
assert_eq!(
|
||||
dangerous_powershell_words_match(&command, DangerousCommandPlatform::host()),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
9
akode-rs/shell-command/src/command_safety/mod.rs
Normal file
9
akode-rs/shell-command/src/command_safety/mod.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
// Keep the PowerShell subprocess parser available as a test oracle, but do not
|
||||
// compile it into production command classification.
|
||||
#[cfg(test)]
|
||||
#[allow(dead_code)]
|
||||
mod powershell_parser;
|
||||
mod powershell_tree_sitter;
|
||||
|
||||
pub mod is_dangerous_command;
|
||||
pub(crate) use powershell_tree_sitter::try_parse_powershell_commands;
|
||||
281
akode-rs/shell-command/src/command_safety/powershell_parser.ps1
Normal file
281
akode-rs/shell-command/src/command_safety/powershell_parser.ps1
Normal file
@@ -0,0 +1,281 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$ProgressPreference = 'SilentlyContinue'
|
||||
|
||||
# Long-lived PowerShell AST parser used by the Rust command-safety layer on Windows.
|
||||
# The caller starts one child process per PowerShell executable variant and then sends
|
||||
# newline-delimited JSON requests over stdin:
|
||||
# { "id": <u64>, "payload": "<base64-encoded UTF-16LE script>" }
|
||||
# We answer with one compact JSON line per request:
|
||||
# { "id": <same>, "status": "ok", "commands": [["Get-Content", "foo.txt"]] }
|
||||
# or:
|
||||
# { "id": <same>, "status": "parse_failed" | "parse_errors" | "unsupported" }
|
||||
#
|
||||
# "unsupported" is intentional: it means the script parsed successfully, but the AST
|
||||
# included constructs that we conservatively refuse to lower into argv-like command words.
|
||||
# The Rust side treats that the same way as an unsafe command.
|
||||
|
||||
# Use BOM-free UTF-8 on the protocol stream so Rust sees clean JSON lines with no
|
||||
# leading BOM bytes on the first response.
|
||||
$utf8 = [System.Text.UTF8Encoding]::new($false)
|
||||
$stdin = [System.IO.StreamReader]::new([Console]::OpenStandardInput(), $utf8, $false)
|
||||
$stdout = [System.IO.StreamWriter]::new([Console]::OpenStandardOutput(), $utf8)
|
||||
$stdout.AutoFlush = $true
|
||||
|
||||
function Invoke-ParseRequest {
|
||||
param($RequestId, $Source)
|
||||
|
||||
$tokens = $null
|
||||
$errors = $null
|
||||
|
||||
$ast = $null
|
||||
try {
|
||||
$ast = [System.Management.Automation.Language.Parser]::ParseInput(
|
||||
$Source,
|
||||
[ref]$tokens,
|
||||
[ref]$errors
|
||||
)
|
||||
} catch {
|
||||
return @{ id = $RequestId; status = 'parse_failed' }
|
||||
}
|
||||
|
||||
if ($errors.Count -gt 0) {
|
||||
return @{ id = $RequestId; status = 'parse_errors' }
|
||||
}
|
||||
|
||||
# Top-level AST regions and collections outside the end-block statement list
|
||||
# can execute code that the command lowering below does not inspect.
|
||||
$cleanBlock = $ast.PSObject.Properties['CleanBlock']
|
||||
if (
|
||||
$ast.ParamBlock -ne $null -or
|
||||
$ast.DynamicParamBlock -ne $null -or
|
||||
$ast.BeginBlock -ne $null -or
|
||||
$ast.ProcessBlock -ne $null -or
|
||||
($cleanBlock -ne $null -and $cleanBlock.Value -ne $null) -or
|
||||
$ast.UsingStatements.Count -gt 0 -or
|
||||
$ast.EndBlock.Traps.Count -gt 0
|
||||
) {
|
||||
return @{ id = $RequestId; status = 'unsupported' }
|
||||
}
|
||||
|
||||
# PowerShell's stop-parsing marker hands the remaining source text to native
|
||||
# commands with runtime argument handling that does not match the AST shape we
|
||||
# flatten below. Keep that form out of the argv-like lowering path entirely.
|
||||
foreach ($token in $tokens) {
|
||||
if ($token.Text -eq '--%') {
|
||||
return @{ id = $RequestId; status = 'unsupported' }
|
||||
}
|
||||
}
|
||||
|
||||
# Only accept AST shapes we can flatten into a list of argv-like command words.
|
||||
# Anything more dynamic than that becomes "unsupported" instead of being guessed at.
|
||||
$commands = [System.Collections.ArrayList]::new()
|
||||
|
||||
foreach ($statement in $ast.EndBlock.Statements) {
|
||||
if (-not (Add-CommandsFromPipelineBase $statement $commands)) {
|
||||
$commands = $null
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if ($commands -ne $null) {
|
||||
$normalized = [System.Collections.ArrayList]::new()
|
||||
foreach ($cmd in $commands) {
|
||||
# Convert every successful parse result to an array-of-arrays shape so the Rust
|
||||
# side can deserialize one uniform representation.
|
||||
if ($cmd -is [string]) {
|
||||
$null = $normalized.Add(@($cmd))
|
||||
continue
|
||||
}
|
||||
|
||||
if ($cmd -is [System.Array] -or $cmd -is [System.Collections.IEnumerable]) {
|
||||
$null = $normalized.Add(@($cmd))
|
||||
continue
|
||||
}
|
||||
|
||||
$normalized = $null
|
||||
break
|
||||
}
|
||||
|
||||
$commands = $normalized
|
||||
}
|
||||
|
||||
if ($commands -eq $null) {
|
||||
return @{ id = $RequestId; status = 'unsupported' }
|
||||
}
|
||||
|
||||
return @{ id = $RequestId; status = 'ok'; commands = $commands }
|
||||
}
|
||||
|
||||
function Write-Response {
|
||||
param($Response)
|
||||
|
||||
$stdout.WriteLine(($Response | ConvertTo-Json -Compress -Depth 3))
|
||||
}
|
||||
|
||||
function Convert-CommandElement {
|
||||
param($element)
|
||||
|
||||
# Accept only literal-ish command elements. Variable expansion, subexpressions, splats,
|
||||
# and other dynamic forms return $null so the whole request becomes unsupported.
|
||||
if ($element -is [System.Management.Automation.Language.StringConstantExpressionAst]) {
|
||||
return @($element.Value)
|
||||
}
|
||||
|
||||
if ($element -is [System.Management.Automation.Language.ExpandableStringExpressionAst]) {
|
||||
if ($element.NestedExpressions.Count -gt 0) {
|
||||
return $null
|
||||
}
|
||||
return @($element.Value)
|
||||
}
|
||||
|
||||
if ($element -is [System.Management.Automation.Language.ConstantExpressionAst]) {
|
||||
return @($element.Value.ToString())
|
||||
}
|
||||
|
||||
if ($element -is [System.Management.Automation.Language.CommandParameterAst]) {
|
||||
if ($element.Argument -eq $null) {
|
||||
return @('-' + $element.ParameterName)
|
||||
}
|
||||
|
||||
if ($element.Argument -is [System.Management.Automation.Language.StringConstantExpressionAst]) {
|
||||
return @('-' + $element.ParameterName, $element.Argument.Value)
|
||||
}
|
||||
|
||||
if ($element.Argument -is [System.Management.Automation.Language.ConstantExpressionAst]) {
|
||||
return @('-' + $element.ParameterName, $element.Argument.Value.ToString())
|
||||
}
|
||||
|
||||
return $null
|
||||
}
|
||||
|
||||
return $null
|
||||
}
|
||||
|
||||
function Convert-PipelineElement {
|
||||
param($element)
|
||||
|
||||
if ($element -is [System.Management.Automation.Language.CommandAst]) {
|
||||
# Redirections and invocation operators make the command harder to classify safely,
|
||||
# so reject them rather than trying to normalize them.
|
||||
if ($element.Redirections.Count -gt 0) {
|
||||
return $null
|
||||
}
|
||||
|
||||
if (
|
||||
$element.InvocationOperator -ne $null -and
|
||||
$element.InvocationOperator -ne [System.Management.Automation.Language.TokenKind]::Unknown
|
||||
) {
|
||||
return $null
|
||||
}
|
||||
|
||||
$parts = @()
|
||||
foreach ($commandElement in $element.CommandElements) {
|
||||
$converted = Convert-CommandElement $commandElement
|
||||
if ($converted -eq $null) {
|
||||
return $null
|
||||
}
|
||||
$parts += $converted
|
||||
}
|
||||
return $parts
|
||||
}
|
||||
|
||||
if ($element -is [System.Management.Automation.Language.CommandExpressionAst]) {
|
||||
if ($element.Redirections.Count -gt 0) {
|
||||
return $null
|
||||
}
|
||||
|
||||
# Allow a parenthesized single pipeline element like "(Get-Content foo.rs -Raw)" so
|
||||
# the caller still sees the inner command words. More complex expressions stay unsupported.
|
||||
if ($element.Expression -is [System.Management.Automation.Language.ParenExpressionAst]) {
|
||||
$innerPipeline = $element.Expression.Pipeline
|
||||
if ($innerPipeline -and $innerPipeline.PipelineElements.Count -eq 1) {
|
||||
return Convert-PipelineElement $innerPipeline.PipelineElements[0]
|
||||
}
|
||||
}
|
||||
|
||||
return $null
|
||||
}
|
||||
|
||||
return $null
|
||||
}
|
||||
|
||||
function Add-CommandsFromPipelineAst {
|
||||
param($pipeline, $commands)
|
||||
|
||||
if ($pipeline.PipelineElements.Count -eq 0) {
|
||||
return $false
|
||||
}
|
||||
|
||||
foreach ($element in $pipeline.PipelineElements) {
|
||||
$words = Convert-PipelineElement $element
|
||||
if ($words -eq $null -or $words.Count -eq 0) {
|
||||
return $false
|
||||
}
|
||||
$null = $commands.Add($words)
|
||||
}
|
||||
|
||||
return $true
|
||||
}
|
||||
|
||||
function Add-CommandsFromPipelineChain {
|
||||
param($chain, $commands)
|
||||
|
||||
if (-not (Add-CommandsFromPipelineBase $chain.LhsPipelineChain $commands)) {
|
||||
return $false
|
||||
}
|
||||
|
||||
if (-not (Add-CommandsFromPipelineAst $chain.RhsPipeline $commands)) {
|
||||
return $false
|
||||
}
|
||||
|
||||
return $true
|
||||
}
|
||||
|
||||
function Add-CommandsFromPipelineBase {
|
||||
param($pipeline, $commands)
|
||||
|
||||
if ($pipeline -is [System.Management.Automation.Language.PipelineAst]) {
|
||||
return Add-CommandsFromPipelineAst $pipeline $commands
|
||||
}
|
||||
|
||||
# Windows PowerShell 5.1 does not define PipelineChainAst, so avoid a direct type
|
||||
# reference here and instead check the runtime type name.
|
||||
if ($pipeline.GetType().FullName -eq 'System.Management.Automation.Language.PipelineChainAst') {
|
||||
return Add-CommandsFromPipelineChain $pipeline $commands
|
||||
}
|
||||
|
||||
return $false
|
||||
}
|
||||
|
||||
# This script stays alive so the Rust caller can amortize PowerShell startup across
|
||||
# many parse requests. Each request and response is one compact JSON line.
|
||||
while (($requestLine = $stdin.ReadLine()) -ne $null) {
|
||||
$request = $null
|
||||
try {
|
||||
$request = $requestLine | ConvertFrom-Json
|
||||
} catch {
|
||||
Write-Response @{ id = $null; status = 'parse_failed' }
|
||||
continue
|
||||
}
|
||||
|
||||
# We process requests serially, but still echo the id back so the Rust side can
|
||||
# detect protocol desyncs instead of silently trusting mixed stdout.
|
||||
$requestId = $request.id
|
||||
$payload = $request.payload
|
||||
if ([string]::IsNullOrEmpty($payload)) {
|
||||
Write-Response @{ id = $requestId; status = 'parse_failed' }
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
$source =
|
||||
[System.Text.Encoding]::Unicode.GetString(
|
||||
[System.Convert]::FromBase64String($payload)
|
||||
)
|
||||
} catch {
|
||||
Write-Response @{ id = $requestId; status = 'parse_failed' }
|
||||
continue
|
||||
}
|
||||
|
||||
Write-Response (Invoke-ParseRequest -RequestId $requestId -Source $source)
|
||||
}
|
||||
373
akode-rs/shell-command/src/command_safety/powershell_parser.rs
Normal file
373
akode-rs/shell-command/src/command_safety/powershell_parser.rs
Normal file
@@ -0,0 +1,373 @@
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::collections::HashMap;
|
||||
use std::io::BufRead;
|
||||
use std::io::BufReader;
|
||||
use std::io::ErrorKind;
|
||||
use std::io::Write;
|
||||
use std::process::Child;
|
||||
use std::process::ChildStdin;
|
||||
use std::process::ChildStdout;
|
||||
use std::process::Command;
|
||||
use std::process::Stdio;
|
||||
use std::sync::LazyLock;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::PoisonError;
|
||||
|
||||
const POWERSHELL_PARSER_SCRIPT: &str = include_str!("powershell_parser.ps1");
|
||||
|
||||
/// Cache one long-lived parser process per executable path so repeated safety checks reuse
|
||||
/// PowerShell startup work while still consulting the real parser every time.
|
||||
///
|
||||
/// We keep the cache behind one mutex because each child process speaks a simple
|
||||
/// request/response protocol over a single stdin/stdout pair, so callers targeting the same
|
||||
/// executable must serialize access anyway.
|
||||
pub(super) fn parse_with_powershell_ast(executable: &str, script: &str) -> PowershellParseOutcome {
|
||||
static PARSER_PROCESSES: LazyLock<Mutex<HashMap<String, PowershellParserProcess>>> =
|
||||
LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
let mut parser_processes = PARSER_PROCESSES
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
parse_with_cached_process(&mut parser_processes, executable, script)
|
||||
}
|
||||
|
||||
pub(crate) fn try_parse_powershell_ast_commands(
|
||||
executable: &str,
|
||||
script: &str,
|
||||
) -> Option<Vec<Vec<String>>> {
|
||||
match parse_with_powershell_ast(executable, script) {
|
||||
PowershellParseOutcome::Commands(commands) => Some(commands),
|
||||
PowershellParseOutcome::Unsupported | PowershellParseOutcome::Failed => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(super) enum PowershellParseOutcome {
|
||||
Commands(Vec<Vec<String>>),
|
||||
Unsupported,
|
||||
Failed,
|
||||
}
|
||||
|
||||
fn parse_with_cached_process(
|
||||
parser_processes: &mut HashMap<String, PowershellParserProcess>,
|
||||
executable: &str,
|
||||
script: &str,
|
||||
) -> PowershellParseOutcome {
|
||||
// `powershell.exe` and `pwsh.exe` do not accept the same language surface, so each
|
||||
// executable keeps its own parser process and request stream.
|
||||
let parser_key = executable.to_string();
|
||||
for attempt in 0..=1 {
|
||||
if !parser_processes.contains_key(&parser_key) {
|
||||
match PowershellParserProcess::spawn(executable) {
|
||||
Ok(process) => {
|
||||
parser_processes.insert(parser_key.clone(), process);
|
||||
}
|
||||
Err(_) => return PowershellParseOutcome::Failed,
|
||||
}
|
||||
}
|
||||
|
||||
let Some(parser_process) = parser_processes.get_mut(&parser_key) else {
|
||||
return PowershellParseOutcome::Failed;
|
||||
};
|
||||
let parse_result = parser_process.parse(script);
|
||||
match parse_result {
|
||||
Ok(outcome) => return outcome,
|
||||
Err(_) if attempt == 0 => {
|
||||
// The common failure mode here is that a previously cached child exited or its
|
||||
// stdio stream became unusable between requests. Drop that process and retry once
|
||||
// with a fresh child before giving up.
|
||||
parser_processes.remove(&parser_key);
|
||||
}
|
||||
Err(_) => return PowershellParseOutcome::Failed,
|
||||
}
|
||||
}
|
||||
|
||||
PowershellParseOutcome::Failed
|
||||
}
|
||||
|
||||
fn encode_powershell_base64(script: &str) -> String {
|
||||
let mut utf16 = Vec::with_capacity(script.len() * 2);
|
||||
for unit in script.encode_utf16() {
|
||||
utf16.extend_from_slice(&unit.to_le_bytes());
|
||||
}
|
||||
BASE64_STANDARD.encode(utf16)
|
||||
}
|
||||
|
||||
fn encoded_parser_script() -> &'static str {
|
||||
static ENCODED: LazyLock<String> =
|
||||
LazyLock::new(|| encode_powershell_base64(POWERSHELL_PARSER_SCRIPT));
|
||||
&ENCODED
|
||||
}
|
||||
|
||||
struct PowershellParserProcess {
|
||||
child: Child,
|
||||
stdin: ChildStdin,
|
||||
stdout: BufReader<ChildStdout>,
|
||||
// Request ids are monotonic within one child process so the caller can detect protocol
|
||||
// desynchronization if stdout is contaminated or the child is unexpectedly replaced.
|
||||
next_request_id: u64,
|
||||
}
|
||||
|
||||
impl PowershellParserProcess {
|
||||
fn spawn(executable: &str) -> std::io::Result<Self> {
|
||||
let mut command = Command::new(executable);
|
||||
command
|
||||
.args([
|
||||
"-NoLogo",
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-EncodedCommand",
|
||||
encoded_parser_script(),
|
||||
])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null());
|
||||
akode_protocol::shell_environment::scrub_non_inheritable_env_vars(&mut command);
|
||||
let mut child = command.spawn()?;
|
||||
let stdin = match take_child_stdin(&mut child) {
|
||||
Ok(stdin) => stdin,
|
||||
Err(error) => {
|
||||
kill_child(&mut child);
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
let stdout = match take_child_stdout(&mut child) {
|
||||
Ok(stdout) => stdout,
|
||||
Err(error) => {
|
||||
kill_child(&mut child);
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
child,
|
||||
stdin,
|
||||
stdout,
|
||||
next_request_id: 0,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse(&mut self, script: &str) -> std::io::Result<PowershellParseOutcome> {
|
||||
let request = PowershellParserRequest {
|
||||
id: self.next_request_id,
|
||||
payload: encode_powershell_base64(script),
|
||||
};
|
||||
self.next_request_id = self.next_request_id.wrapping_add(1);
|
||||
let mut request_json = serialize_request(&request)?;
|
||||
request_json.push('\n');
|
||||
self.stdin.write_all(request_json.as_bytes())?;
|
||||
self.stdin.flush()?;
|
||||
|
||||
let mut response_line = String::new();
|
||||
if self.stdout.read_line(&mut response_line)? == 0 {
|
||||
return Err(std::io::Error::new(
|
||||
ErrorKind::UnexpectedEof,
|
||||
"PowerShell parser closed stdout",
|
||||
));
|
||||
}
|
||||
|
||||
let response = deserialize_response(&response_line)?;
|
||||
// Requests are serialized today; the id still catches protocol desyncs if stdout is
|
||||
// contaminated or the child process is unexpectedly replaced mid-request. That turns an
|
||||
// ambiguous parser result into a hard failure so the caller can discard the cached child.
|
||||
if response.id != request.id {
|
||||
return Err(std::io::Error::new(
|
||||
ErrorKind::InvalidData,
|
||||
format!(
|
||||
"PowerShell parser returned response id {} for request {}",
|
||||
response.id, request.id
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
Ok(response.into_outcome())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PowershellParserProcess {
|
||||
fn drop(&mut self) {
|
||||
kill_child(&mut self.child);
|
||||
}
|
||||
}
|
||||
|
||||
fn take_child_stdin(child: &mut Child) -> std::io::Result<ChildStdin> {
|
||||
child.stdin.take().ok_or_else(|| {
|
||||
std::io::Error::new(
|
||||
ErrorKind::BrokenPipe,
|
||||
"PowerShell parser child did not expose stdin",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn take_child_stdout(child: &mut Child) -> std::io::Result<BufReader<ChildStdout>> {
|
||||
child.stdout.take().map(BufReader::new).ok_or_else(|| {
|
||||
std::io::Error::new(
|
||||
ErrorKind::BrokenPipe,
|
||||
"PowerShell parser child did not expose stdout",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn serialize_request(request: &PowershellParserRequest) -> std::io::Result<String> {
|
||||
serde_json::to_string(request).map_err(|error| {
|
||||
std::io::Error::new(
|
||||
ErrorKind::InvalidData,
|
||||
format!("failed to serialize PowerShell parser request: {error}"),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn deserialize_response(response_line: &str) -> std::io::Result<PowershellParserResponse> {
|
||||
serde_json::from_str(response_line).map_err(|error| {
|
||||
std::io::Error::new(
|
||||
ErrorKind::InvalidData,
|
||||
format!("failed to parse PowerShell parser response: {error}"),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct PowershellParserRequest {
|
||||
id: u64,
|
||||
payload: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct PowershellParserResponse {
|
||||
id: u64,
|
||||
status: String,
|
||||
commands: Option<Vec<Vec<String>>>,
|
||||
}
|
||||
|
||||
impl PowershellParserResponse {
|
||||
fn into_outcome(self) -> PowershellParseOutcome {
|
||||
match self.status.as_str() {
|
||||
"ok" => self
|
||||
.commands
|
||||
.filter(|commands| {
|
||||
!commands.is_empty()
|
||||
&& commands
|
||||
.iter()
|
||||
.all(|cmd| !cmd.is_empty() && cmd.iter().all(|word| !word.is_empty()))
|
||||
})
|
||||
.map(PowershellParseOutcome::Commands)
|
||||
.unwrap_or(PowershellParseOutcome::Unsupported),
|
||||
"unsupported" => PowershellParseOutcome::Unsupported,
|
||||
_ => PowershellParseOutcome::Failed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn kill_child(child: &mut Child) {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
|
||||
#[cfg(all(test, windows))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::powershell::try_find_powershell_executable_blocking;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn parser_process_handles_multiple_requests() {
|
||||
let Some(powershell) = try_find_powershell_executable_blocking() else {
|
||||
return;
|
||||
};
|
||||
let powershell = powershell.as_path().to_str().unwrap();
|
||||
let mut parser = PowershellParserProcess::spawn(powershell).unwrap();
|
||||
|
||||
let first = parser.parse("Get-Content 'foo bar'").unwrap();
|
||||
assert_eq!(
|
||||
first,
|
||||
PowershellParseOutcome::Commands(vec![vec![
|
||||
"Get-Content".to_string(),
|
||||
"foo bar".to_string(),
|
||||
]]),
|
||||
);
|
||||
|
||||
let second = parser.parse("Write-Output foo | Measure-Object").unwrap();
|
||||
assert_eq!(
|
||||
second,
|
||||
PowershellParseOutcome::Commands(vec![
|
||||
vec!["Write-Output".to_string(), "foo".to_string()],
|
||||
vec!["Measure-Object".to_string()],
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parser_process_rejects_stop_parsing_forms() {
|
||||
let Some(powershell) = try_find_powershell_executable_blocking() else {
|
||||
return;
|
||||
};
|
||||
let powershell = powershell.as_path().to_str().unwrap();
|
||||
let mut parser = PowershellParserProcess::spawn(powershell).unwrap();
|
||||
|
||||
let parsed = parser
|
||||
.parse("git log --% HEAD --output=codex_poc.txt")
|
||||
.unwrap();
|
||||
assert_eq!(parsed, PowershellParseOutcome::Unsupported);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parser_process_rejects_param_blocks() {
|
||||
let Some(powershell) = try_find_powershell_executable_blocking() else {
|
||||
return;
|
||||
};
|
||||
let powershell = powershell.as_path().to_str().unwrap();
|
||||
let mut parser = PowershellParserProcess::spawn(powershell).unwrap();
|
||||
|
||||
let parsed = parser
|
||||
.parse("param([string]$path = (Get-Location)) Write-Output test")
|
||||
.unwrap();
|
||||
assert_eq!(parsed, PowershellParseOutcome::Unsupported);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parser_process_rejects_named_blocks() {
|
||||
let Some(powershell) = try_find_powershell_executable_blocking() else {
|
||||
return;
|
||||
};
|
||||
let powershell = powershell.as_path().to_str().unwrap();
|
||||
let mut parser = PowershellParserProcess::spawn(powershell).unwrap();
|
||||
|
||||
let parsed = parser
|
||||
.parse("begin { Set-Content codex_poc.txt pwned } end { Get-Content Cargo.toml }")
|
||||
.unwrap();
|
||||
assert_eq!(parsed, PowershellParseOutcome::Unsupported);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parser_process_rejects_using_statements() {
|
||||
let Some(powershell) = try_find_powershell_executable_blocking() else {
|
||||
return;
|
||||
};
|
||||
let powershell = powershell.as_path().to_str().unwrap();
|
||||
let mut parser = PowershellParserProcess::spawn(powershell).unwrap();
|
||||
|
||||
let parsed = parser
|
||||
.parse("using module ./codex_poc.psm1\nGet-Content Cargo.toml")
|
||||
.unwrap();
|
||||
assert_eq!(parsed, PowershellParseOutcome::Unsupported);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parser_process_rejects_trap_blocks() {
|
||||
let Some(powershell) = try_find_powershell_executable_blocking() else {
|
||||
return;
|
||||
};
|
||||
let powershell = powershell.as_path().to_str().unwrap();
|
||||
let mut parser = PowershellParserProcess::spawn(powershell).unwrap();
|
||||
|
||||
let parsed = parser
|
||||
.parse(
|
||||
"trap { Set-Content codex_poc.txt pwned; continue } Get-Content missing -ErrorAction Stop",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(parsed, PowershellParseOutcome::Unsupported);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
use tree_sitter::Node;
|
||||
use tree_sitter::Parser;
|
||||
|
||||
/// Lowers a literal PowerShell script into argv-like command vectors.
|
||||
///
|
||||
/// This module does not decide whether a command is safe or dangerous; callers apply those
|
||||
/// policies to the lowered words. Its job is only to recognize a deliberately small literal
|
||||
/// PowerShell subset and fail closed for everything else.
|
||||
///
|
||||
/// Unknown syntax, parse recovery, and dynamic expressions fail closed instead of being guessed
|
||||
/// at. The accepted CST shapes intentionally cover only common literal command forms; rare
|
||||
/// PowerShell syntax and value-conversion cases stay opaque.
|
||||
pub(crate) fn try_parse_powershell_commands(script: &str) -> Option<Vec<Vec<String>>> {
|
||||
lower_with_tree_sitter(script).ok()
|
||||
}
|
||||
|
||||
fn lower_with_tree_sitter(script: &str) -> Result<Vec<Vec<String>>, String> {
|
||||
// PowerShell treats these Unicode characters as syntax aliases even when tree-sitter leaves
|
||||
// them inside generic tokens. Keep that whole spelling family opaque rather than guessing at
|
||||
// whether a quote or dash is structural in a particular position.
|
||||
if script
|
||||
.chars()
|
||||
.any(|ch| matches!(ch, '‘' | '’' | '“' | '”' | '–' | '—' | '―'))
|
||||
{
|
||||
return Err("PowerShell Unicode syntax alias".to_string());
|
||||
}
|
||||
|
||||
let mut parser = Parser::new();
|
||||
parser
|
||||
.set_language(&tree_sitter_powershell::LANGUAGE.into())
|
||||
.map_err(|error| format!("load grammar: {error}"))?;
|
||||
// The grammar rejects native `--flag=value`. Mask only the `=` in conservatively
|
||||
// recognized bare tokens; the one-byte replacement keeps CST ranges valid for `script`.
|
||||
let mut parse_source = script.as_bytes().to_vec();
|
||||
for equals in inline_double_dash_parameter_equals(script) {
|
||||
parse_source[equals] = b' ';
|
||||
}
|
||||
let parse_source = String::from_utf8(parse_source)
|
||||
.map_err(|_| "masked command source is not UTF-8".to_string())?;
|
||||
let tree = parser
|
||||
.parse(&parse_source, None)
|
||||
.ok_or_else(|| "tree-sitter returned no tree".to_string())?;
|
||||
let root = tree.root_node();
|
||||
if root.has_error() {
|
||||
return Err("tree contains ERROR or missing nodes".to_string());
|
||||
}
|
||||
if has_requires_directive(root, script) {
|
||||
return Err("requires directives can execute before command lowering".to_string());
|
||||
}
|
||||
if let Some(kind) = first_unrecognized_named_kind(root) {
|
||||
return Err(format!("unrecognized named node: {kind}"));
|
||||
}
|
||||
let mut command_nodes = Vec::new();
|
||||
collect_command_nodes(root, &mut command_nodes);
|
||||
if command_nodes.is_empty() {
|
||||
return Err("no literal command nodes".to_string());
|
||||
}
|
||||
|
||||
let mut commands = Vec::with_capacity(command_nodes.len());
|
||||
let mut command_ranges = Vec::with_capacity(command_nodes.len());
|
||||
for node in command_nodes {
|
||||
let text = node
|
||||
.utf8_text(script.as_bytes())
|
||||
.map_err(|_| "command source is not UTF-8".to_string())?;
|
||||
command_ranges.push(node.start_byte()..node.end_byte());
|
||||
commands.push(lower_command_text(text)?);
|
||||
}
|
||||
if !source_is_covered_by_commands(script, &command_ranges) {
|
||||
return Err("source outside literal command nodes".to_string());
|
||||
}
|
||||
if commands.iter().any(|command| {
|
||||
command
|
||||
.first()
|
||||
.is_some_and(|word| word.eq_ignore_ascii_case("using"))
|
||||
}) {
|
||||
return Err("using declarations require the PowerShell AST oracle".to_string());
|
||||
}
|
||||
if commands
|
||||
.iter()
|
||||
.any(|command| command.is_empty() || command.iter().any(String::is_empty))
|
||||
{
|
||||
return Err("empty lowered command or word".to_string());
|
||||
}
|
||||
Ok(commands)
|
||||
}
|
||||
|
||||
fn collect_command_nodes<'tree>(root: Node<'tree>, commands: &mut Vec<Node<'tree>>) {
|
||||
// Script nesting is model-controlled, so keep CST traversal off the call stack.
|
||||
let mut stack = vec![root];
|
||||
while let Some(node) = stack.pop() {
|
||||
if node.kind() == "command" {
|
||||
commands.push(node);
|
||||
continue;
|
||||
}
|
||||
for child_index in (0..node.named_child_count()).rev() {
|
||||
if let Some(child) = node.named_child(child_index) {
|
||||
stack.push(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn has_requires_directive(root: Node<'_>, script: &str) -> bool {
|
||||
// Tree-sitter exposes #requires as a comment, but PowerShell evaluates it before the
|
||||
// script body and can load modules or assemblies.
|
||||
let mut stack = vec![root];
|
||||
while let Some(node) = stack.pop() {
|
||||
if node.kind() == "comment"
|
||||
&& node
|
||||
.utf8_text(script.as_bytes())
|
||||
.ok()
|
||||
.is_some_and(|comment| {
|
||||
comment
|
||||
.trim_start()
|
||||
.to_ascii_lowercase()
|
||||
.starts_with("#requires")
|
||||
})
|
||||
{
|
||||
return true;
|
||||
}
|
||||
let mut cursor = node.walk();
|
||||
stack.extend(node.named_children(&mut cursor));
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
// These helpers are the allowlist for PowerShell CST forms we intentionally understand. A new
|
||||
// named tree-sitter node is rejected until its lowering semantics are reviewed.
|
||||
fn first_unrecognized_named_kind(root: Node<'_>) -> Option<String> {
|
||||
let mut stack = vec![root];
|
||||
while let Some(node) = stack.pop() {
|
||||
if node.is_named() && !is_allowed_named_kind(node.kind()) {
|
||||
return Some(node.kind().to_string());
|
||||
}
|
||||
let mut cursor = node.walk();
|
||||
for child in node.named_children(&mut cursor) {
|
||||
stack.push(child);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn is_allowed_named_kind(kind: &str) -> bool {
|
||||
matches!(
|
||||
kind,
|
||||
"program"
|
||||
| "statement_list"
|
||||
| "pipeline"
|
||||
| "pipeline_chain"
|
||||
| "pipeline_chain_tail"
|
||||
| "command"
|
||||
| "command_name"
|
||||
| "command_elements"
|
||||
| "command_argument_sep"
|
||||
| "command_parameter"
|
||||
| "generic_token"
|
||||
| "array_literal_expression"
|
||||
| "unary_expression"
|
||||
| "string_literal"
|
||||
| "verbatim_string_characters"
|
||||
| "expandable_string_literal"
|
||||
| "integer_literal"
|
||||
| "decimal_integer_literal"
|
||||
| "comment"
|
||||
| "empty_statement"
|
||||
// Negative numeric flags such as git log -1 use this wrapper.
|
||||
| "expression_with_unary_operator"
|
||||
)
|
||||
}
|
||||
|
||||
// Find only bare literal `--flag=value` forms whose `=` can be masked before parsing.
|
||||
fn inline_double_dash_parameter_equals(script: &str) -> Vec<usize> {
|
||||
let mut equals = Vec::new();
|
||||
let mut start = 0;
|
||||
for (index, ch) in script.char_indices() {
|
||||
if is_inline_parameter_token_separator(ch) {
|
||||
push_inline_parameter_equals(&mut equals, script, start, index);
|
||||
start = index + ch.len_utf8();
|
||||
}
|
||||
}
|
||||
push_inline_parameter_equals(&mut equals, script, start, script.len());
|
||||
equals
|
||||
}
|
||||
|
||||
fn push_inline_parameter_equals(equals: &mut Vec<usize>, script: &str, start: usize, end: usize) {
|
||||
let token = &script[start..end];
|
||||
if token.starts_with("--")
|
||||
&& token
|
||||
.chars()
|
||||
.all(|ch| !is_rejected_inline_parameter_character(ch))
|
||||
&& let Some(relative_equals) = token.find('=')
|
||||
&& relative_equals > 2
|
||||
&& relative_equals + 1 < token.len()
|
||||
{
|
||||
equals.push(start + relative_equals);
|
||||
}
|
||||
}
|
||||
|
||||
fn is_inline_parameter_token_separator(ch: char) -> bool {
|
||||
ch.is_whitespace() || "|&;#><(){}".contains(ch)
|
||||
}
|
||||
|
||||
fn is_rejected_inline_parameter_character(ch: char) -> bool {
|
||||
ch.is_whitespace() || is_rejected_bare_character(ch) || matches!(ch, '\u{60}' | '#')
|
||||
}
|
||||
|
||||
fn source_is_covered_by_commands(script: &str, command_ranges: &[std::ops::Range<usize>]) -> bool {
|
||||
// Command nodes alone are not enough: reject any source outside the literal commands and
|
||||
// separators/comments we explicitly understand.
|
||||
let mut index = 0;
|
||||
let mut range_index = 0;
|
||||
let mut can_chain = false;
|
||||
let mut needs_command = false;
|
||||
let mut paren_depth = 0;
|
||||
while index < script.len() {
|
||||
if let Some(range) = command_ranges.get(range_index)
|
||||
&& index == range.start
|
||||
{
|
||||
index = range.end;
|
||||
range_index += 1;
|
||||
can_chain = true;
|
||||
needs_command = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
let Some(ch) = script[index..].chars().next() else {
|
||||
return false;
|
||||
};
|
||||
let next = index + ch.len_utf8();
|
||||
if ch == '\r' || ch == '\n' {
|
||||
can_chain = false;
|
||||
index = next;
|
||||
continue;
|
||||
}
|
||||
if ch.is_whitespace() {
|
||||
index = next;
|
||||
continue;
|
||||
}
|
||||
if ch == ';' {
|
||||
if needs_command {
|
||||
return false;
|
||||
}
|
||||
can_chain = false;
|
||||
index = next;
|
||||
continue;
|
||||
}
|
||||
if ch == '(' && !can_chain {
|
||||
paren_depth += 1;
|
||||
index = next;
|
||||
continue;
|
||||
}
|
||||
if ch == ')' && paren_depth > 0 && !needs_command {
|
||||
paren_depth -= 1;
|
||||
index = next;
|
||||
continue;
|
||||
}
|
||||
if ch == '|' && can_chain {
|
||||
can_chain = false;
|
||||
needs_command = true;
|
||||
index = if script[next..].starts_with('|') {
|
||||
next + '|'.len_utf8()
|
||||
} else {
|
||||
next
|
||||
};
|
||||
continue;
|
||||
}
|
||||
if ch == '&' && can_chain && script[next..].starts_with('&') {
|
||||
can_chain = false;
|
||||
needs_command = true;
|
||||
index = next + '&'.len_utf8();
|
||||
continue;
|
||||
}
|
||||
if ch == '#' && !needs_command {
|
||||
// `#` starts a comment only at a token boundary. Tree-sitter can split an
|
||||
// embedded `#` out of a bare token, so reject that recovery instead of dropping
|
||||
// the rest of the line.
|
||||
if index > 0
|
||||
&& !script[..index]
|
||||
.chars()
|
||||
.next_back()
|
||||
.is_some_and(|previous| previous.is_whitespace() || previous == ';')
|
||||
{
|
||||
return false;
|
||||
}
|
||||
index = script[next..]
|
||||
.find(['\r', '\n'])
|
||||
.map_or(script.len(), |offset| next + offset);
|
||||
continue;
|
||||
}
|
||||
if script[index..].starts_with("<#")
|
||||
&& !needs_command
|
||||
&& (index == 0
|
||||
|| script[..index]
|
||||
.chars()
|
||||
.next_back()
|
||||
.is_some_and(|previous| previous.is_whitespace() || previous == ';'))
|
||||
{
|
||||
let Some(end) = script[next..].find("#>") else {
|
||||
return false;
|
||||
};
|
||||
index = next + end + "#>".len();
|
||||
continue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
range_index == command_ranges.len() && !needs_command && paren_depth == 0
|
||||
}
|
||||
|
||||
fn lower_command_text(command_text: &str) -> Result<Vec<String>, String> {
|
||||
// This is literal argv lowering, not safe/dangerous classification. Quoting and escapes are
|
||||
// decoded only for forms whose runtime value is statically known.
|
||||
let mut words = Vec::new();
|
||||
let chars: Vec<char> = command_text.trim().chars().collect();
|
||||
let mut index = 0;
|
||||
while index < chars.len() {
|
||||
while index < chars.len() && chars[index].is_whitespace() {
|
||||
index += 1;
|
||||
}
|
||||
if index == chars.len() || chars[index] == '#' {
|
||||
break;
|
||||
}
|
||||
let (word, next, is_bare) = if chars[index] == '\'' {
|
||||
let (word, next) = parse_single_quoted(&chars, index)?;
|
||||
(word, next, false)
|
||||
} else if chars[index] == '"' {
|
||||
let (word, next) = parse_double_quoted(&chars, index)?;
|
||||
(word, next, false)
|
||||
} else {
|
||||
let (word, next) = parse_bare_word(&chars, index)?;
|
||||
(word, next, true)
|
||||
};
|
||||
index = next;
|
||||
if index < chars.len() && !chars[index].is_whitespace() && chars[index] != '#' {
|
||||
return Err("adjacent/concatenated command elements".to_string());
|
||||
}
|
||||
if word.is_empty() {
|
||||
return Err("empty word".to_string());
|
||||
}
|
||||
if is_bare {
|
||||
reject_unsupported_bare_word(&word)?;
|
||||
}
|
||||
words.push(word);
|
||||
}
|
||||
|
||||
if words.is_empty() {
|
||||
return Err("command lowered to no words".to_string());
|
||||
}
|
||||
Ok(words)
|
||||
}
|
||||
|
||||
fn parse_single_quoted(chars: &[char], start: usize) -> Result<(String, usize), String> {
|
||||
let mut value = String::new();
|
||||
let mut index = start + 1;
|
||||
while index < chars.len() {
|
||||
if chars[index] == '\'' {
|
||||
if chars.get(index + 1) == Some(&'\'') {
|
||||
value.push('\'');
|
||||
index += 2;
|
||||
continue;
|
||||
}
|
||||
return Ok((value, index + 1));
|
||||
}
|
||||
value.push(chars[index]);
|
||||
index += 1;
|
||||
}
|
||||
Err("unterminated single-quoted string".to_string())
|
||||
}
|
||||
|
||||
fn parse_double_quoted(chars: &[char], start: usize) -> Result<(String, usize), String> {
|
||||
let mut value = String::new();
|
||||
let mut index = start + 1;
|
||||
while index < chars.len() {
|
||||
match chars[index] {
|
||||
'"' => return Ok((value, index + 1)),
|
||||
'$' => return Err("expandable string contains variable syntax".to_string()),
|
||||
'`' => {
|
||||
let escaped = *chars
|
||||
.get(index + 1)
|
||||
.ok_or_else(|| "trailing PowerShell escape".to_string())?;
|
||||
// `e is ESC only in PowerShell 6+, so it has no version-neutral value.
|
||||
if escaped == 'e' {
|
||||
return Err("PowerShell-version-dependent escape".to_string());
|
||||
}
|
||||
if escaped == 'u' && chars.get(index + 2) == Some(&'{') {
|
||||
return Err("PowerShell Unicode escape".to_string());
|
||||
}
|
||||
value.push(decode_backtick_escape(escaped));
|
||||
index += 2;
|
||||
}
|
||||
ch => {
|
||||
value.push(ch);
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err("unterminated double-quoted string".to_string())
|
||||
}
|
||||
|
||||
fn decode_backtick_escape(ch: char) -> char {
|
||||
match ch {
|
||||
'0' => '\0',
|
||||
'a' => '\u{7}',
|
||||
'b' => '\u{8}',
|
||||
'f' => '\u{c}',
|
||||
'n' => '\n',
|
||||
'r' => '\r',
|
||||
't' => '\t',
|
||||
'v' => '\u{b}',
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_bare_word(chars: &[char], start: usize) -> Result<(String, usize), String> {
|
||||
let mut value = String::new();
|
||||
let mut index = start;
|
||||
while index < chars.len() && !chars[index].is_whitespace() {
|
||||
let ch = chars[index];
|
||||
if ch == '`' {
|
||||
let escaped = *chars
|
||||
.get(index + 1)
|
||||
.ok_or_else(|| "trailing PowerShell escape".to_string())?;
|
||||
if escaped == 'e' {
|
||||
return Err("PowerShell-version-dependent escape".to_string());
|
||||
}
|
||||
value.push(decode_backtick_escape(escaped));
|
||||
index += 2;
|
||||
continue;
|
||||
}
|
||||
if is_rejected_bare_character(ch) {
|
||||
return Err(format!("dynamic or structural bare character: {ch:?}"));
|
||||
}
|
||||
value.push(ch);
|
||||
index += 1;
|
||||
}
|
||||
if value.is_empty() {
|
||||
return Err("empty bare word".to_string());
|
||||
}
|
||||
Ok((value, index))
|
||||
}
|
||||
|
||||
fn is_rejected_bare_character(ch: char) -> bool {
|
||||
matches!(
|
||||
ch,
|
||||
'$' | '@'
|
||||
| '\''
|
||||
| '"'
|
||||
| '('
|
||||
| ')'
|
||||
| '{'
|
||||
| '}'
|
||||
| '['
|
||||
| ']'
|
||||
| ';'
|
||||
| '|'
|
||||
| '&'
|
||||
| '>'
|
||||
| '<'
|
||||
| ','
|
||||
)
|
||||
}
|
||||
|
||||
fn reject_unsupported_bare_word(word: &str) -> Result<(), String> {
|
||||
// These forms require PowerShell-specific value conversion. Keeping them opaque is safer
|
||||
// than reproducing that conversion in the policy parser.
|
||||
if word.starts_with('-') && !word.starts_with("--") && word.contains(':') {
|
||||
return Err("attached PowerShell parameter value".to_string());
|
||||
}
|
||||
|
||||
// Tree-sitter leaves some PowerShell numerics as generic tokens. Keep only canonical decimal
|
||||
// spellings whose runtime string is obviously identical to the source spelling.
|
||||
if word.chars().next().is_some_and(|ch| ch.is_ascii_digit())
|
||||
&& !(word == "0" || (!word.starts_with('0') && word.chars().all(|ch| ch.is_ascii_digit())))
|
||||
{
|
||||
return Err("non-canonical numeric-leading bare word".to_string());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "powershell_tree_sitter_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,37 @@
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::try_parse_powershell_commands;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct FixtureCase {
|
||||
name: String,
|
||||
script: String,
|
||||
expected: Option<Vec<Vec<String>>>,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lowers_compact_literal_fixture() {
|
||||
// Supported outputs were captured from the PowerShell 7 AST subprocess parser. Rare forms
|
||||
// that need additional PowerShell-specific lowering are intentionally recorded as unsupported.
|
||||
let cases: Vec<FixtureCase> =
|
||||
serde_json::from_str(include_str!("fixtures/powershell_lowering.json"))
|
||||
.expect("valid PowerShell lowering fixture");
|
||||
|
||||
for case in cases {
|
||||
assert_eq!(
|
||||
try_parse_powershell_commands(&case.script),
|
||||
case.expected,
|
||||
"fixture case: {}",
|
||||
case.name
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_requires_directives() {
|
||||
assert_eq!(
|
||||
try_parse_powershell_commands("#requires -Modules Evil\nGet-Location"),
|
||||
None
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,849 @@
|
||||
use crate::command_safety::powershell_tree_sitter::try_parse_powershell_commands;
|
||||
use once_cell::sync::Lazy;
|
||||
use regex::Regex;
|
||||
use shlex::split as shlex_split;
|
||||
use url::Url;
|
||||
|
||||
pub fn is_dangerous_command_windows(command: &[String]) -> bool {
|
||||
// Prefer structured parsing for PowerShell/CMD so we can spot URL-bearing
|
||||
// invocations of ShellExecute-style entry points before falling back to
|
||||
// simple argv heuristics.
|
||||
if is_dangerous_powershell(command) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if is_dangerous_cmd(command) {
|
||||
return true;
|
||||
}
|
||||
|
||||
is_direct_gui_launch(command)
|
||||
}
|
||||
|
||||
fn is_dangerous_powershell(command: &[String]) -> bool {
|
||||
let Some((exe, rest)) = command.split_first() else {
|
||||
return false;
|
||||
};
|
||||
if !is_powershell_executable(exe) {
|
||||
return false;
|
||||
}
|
||||
let Some(parsed) = parse_powershell_invocation(rest) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
if let Some(script) = parsed.script
|
||||
&& let Some(commands) = try_parse_powershell_commands(script)
|
||||
&& powershell_commands_are_independent(script, &commands)
|
||||
{
|
||||
return commands
|
||||
.iter()
|
||||
.any(|words| is_dangerous_powershell_literal_words(words));
|
||||
}
|
||||
is_dangerous_powershell_words(&parsed.tokens)
|
||||
}
|
||||
|
||||
/// Whether strictly lowered commands can be classified independently of the rest of the script.
|
||||
pub fn powershell_commands_are_independent(script: &str, commands: &[Vec<String>]) -> bool {
|
||||
// Deliberately keep even quoted pipes and `||` chains on the existing path. Do not
|
||||
// model pipeline data, command rebinding, or strings that may execute using script state.
|
||||
!script.contains('|')
|
||||
&& commands.iter().all(|words| {
|
||||
!matches!(
|
||||
words
|
||||
.first()
|
||||
.and_then(|word| executable_basename(word))
|
||||
.as_deref(),
|
||||
Some(
|
||||
"set-alias"
|
||||
| "sal"
|
||||
| "new-alias"
|
||||
| "nal"
|
||||
| "set-item"
|
||||
| "si"
|
||||
| "new-item"
|
||||
| "ni"
|
||||
)
|
||||
) && !words.iter().skip(1).any(|word| {
|
||||
let word = word.to_ascii_lowercase();
|
||||
[
|
||||
"start-process",
|
||||
"invoke-item",
|
||||
"shellexecute",
|
||||
"shell.application",
|
||||
]
|
||||
.iter()
|
||||
.any(|marker| word.contains(marker))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
enum PowerShellCommandKind {
|
||||
Opaque,
|
||||
IndependentLiteral,
|
||||
}
|
||||
|
||||
pub(crate) fn is_dangerous_powershell_words(words: &[String]) -> bool {
|
||||
classify_powershell_words(words, PowerShellCommandKind::Opaque)
|
||||
}
|
||||
|
||||
pub(crate) fn is_dangerous_powershell_literal_words(words: &[String]) -> bool {
|
||||
// Shell and terminal wrappers can interpret later words as commands, including `start`.
|
||||
let kind = if words.first().is_some_and(|word| {
|
||||
is_powershell_executable(word)
|
||||
|| matches!(
|
||||
executable_basename(word).as_deref(),
|
||||
Some("cmd" | "cmd.exe" | "wt" | "wt.exe")
|
||||
)
|
||||
}) {
|
||||
PowerShellCommandKind::Opaque
|
||||
} else {
|
||||
PowerShellCommandKind::IndependentLiteral
|
||||
};
|
||||
classify_powershell_words(words, kind)
|
||||
}
|
||||
|
||||
fn classify_powershell_words(words: &[String], kind: PowerShellCommandKind) -> bool {
|
||||
let tokens_lc: Vec<String> = words
|
||||
.iter()
|
||||
.map(|t| t.trim_matches('\'').trim_matches('"').to_ascii_lowercase())
|
||||
.collect();
|
||||
let has_url = args_have_url(words);
|
||||
|
||||
if has_url
|
||||
&& tokens_lc.iter().enumerate().any(|(index, t)| {
|
||||
((index == 0 || matches!(kind, PowerShellCommandKind::Opaque))
|
||||
&& matches!(
|
||||
t.as_str(),
|
||||
"start-process" | "start" | "saps" | "invoke-item" | "ii"
|
||||
))
|
||||
|| t.contains("start-process")
|
||||
|| t.contains("invoke-item")
|
||||
})
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if has_url
|
||||
&& tokens_lc
|
||||
.iter()
|
||||
.any(|t| t.contains("shellexecute") || t.contains("shell.application"))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if let Some(first) = tokens_lc.first() {
|
||||
// Legacy ShellExecute path via url.dll
|
||||
if first == "rundll32"
|
||||
&& tokens_lc
|
||||
.iter()
|
||||
.any(|t| t.contains("url.dll,fileprotocolhandler"))
|
||||
&& has_url
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if first == "mshta" && has_url {
|
||||
return true;
|
||||
}
|
||||
if is_browser_executable(first) && has_url {
|
||||
return true;
|
||||
}
|
||||
if matches!(first.as_str(), "explorer" | "explorer.exe") && has_url {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Check for force delete operations (e.g., Remove-Item -Force)
|
||||
has_force_delete_cmdlet(&tokens_lc)
|
||||
}
|
||||
|
||||
fn is_dangerous_cmd(command: &[String]) -> bool {
|
||||
let Some((exe, rest)) = command.split_first() else {
|
||||
return false;
|
||||
};
|
||||
let Some(base) = executable_basename(exe) else {
|
||||
return false;
|
||||
};
|
||||
if base != "cmd" && base != "cmd.exe" {
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut iter = rest.iter();
|
||||
for arg in iter.by_ref() {
|
||||
let lower = arg.to_ascii_lowercase();
|
||||
match lower.as_str() {
|
||||
"/c" | "/r" | "-c" => break,
|
||||
_ if lower.starts_with('/') => continue,
|
||||
// Unknown tokens before the command body => bail.
|
||||
_ => return false,
|
||||
}
|
||||
}
|
||||
|
||||
let remaining: Vec<String> = iter.cloned().collect();
|
||||
if remaining.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let cmd_tokens: Vec<String> = match remaining.as_slice() {
|
||||
[only] => shlex_split(only).unwrap_or_else(|| vec![only.clone()]),
|
||||
_ => remaining,
|
||||
};
|
||||
|
||||
// Refine tokens by splitting concatenated CMD operators (e.g. "echo hi&del")
|
||||
let tokens: Vec<String> = cmd_tokens
|
||||
.into_iter()
|
||||
.flat_map(|t| split_embedded_cmd_operators(&t))
|
||||
.collect();
|
||||
|
||||
const CMD_SEPARATORS: &[&str] = &["&", "&&", "|", "||"];
|
||||
tokens
|
||||
.split(|t| CMD_SEPARATORS.contains(&t.as_str()))
|
||||
.any(|segment| {
|
||||
let Some(cmd) = segment.first() else {
|
||||
return false;
|
||||
};
|
||||
|
||||
// Classic `cmd /c ... start https://...` ShellExecute path.
|
||||
if cmd.eq_ignore_ascii_case("start") && args_have_url(segment) {
|
||||
return true;
|
||||
}
|
||||
// Force delete: del /f, erase /f
|
||||
if (cmd.eq_ignore_ascii_case("del") || cmd.eq_ignore_ascii_case("erase"))
|
||||
&& has_force_flag_cmd(segment)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
// Recursive directory removal: rd /s /q, rmdir /s /q
|
||||
if (cmd.eq_ignore_ascii_case("rd") || cmd.eq_ignore_ascii_case("rmdir"))
|
||||
&& has_recursive_flag_cmd(segment)
|
||||
&& has_quiet_flag_cmd(segment)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
false
|
||||
})
|
||||
}
|
||||
|
||||
fn is_direct_gui_launch(command: &[String]) -> bool {
|
||||
let Some((exe, rest)) = command.split_first() else {
|
||||
return false;
|
||||
};
|
||||
let Some(base) = executable_basename(exe) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
// Explorer/rundll32/mshta or direct browser exe with a URL anywhere in args.
|
||||
if matches!(base.as_str(), "explorer" | "explorer.exe") && args_have_url(rest) {
|
||||
return true;
|
||||
}
|
||||
if matches!(base.as_str(), "mshta" | "mshta.exe") && args_have_url(rest) {
|
||||
return true;
|
||||
}
|
||||
if (base == "rundll32" || base == "rundll32.exe")
|
||||
&& rest.iter().any(|t| {
|
||||
t.to_ascii_lowercase()
|
||||
.contains("url.dll,fileprotocolhandler")
|
||||
})
|
||||
&& args_have_url(rest)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if is_browser_executable(&base) && args_have_url(rest) {
|
||||
return true;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
fn split_embedded_cmd_operators(token: &str) -> Vec<String> {
|
||||
// Split concatenated CMD operators so `echo hi&del` becomes `["echo hi", "&", "del"]`.
|
||||
// Handles `&`, `&&`, `|`, `||`. Best-effort (CMD escaping is weird by nature).
|
||||
let mut parts = Vec::new();
|
||||
let mut start = 0;
|
||||
let mut it = token.char_indices().peekable();
|
||||
|
||||
while let Some((i, ch)) = it.next() {
|
||||
if ch == '&' || ch == '|' {
|
||||
if i > start {
|
||||
parts.push(token[start..i].to_string());
|
||||
}
|
||||
|
||||
// Detect doubled operator: && or ||
|
||||
let op_len = match it.peek() {
|
||||
Some(&(j, next)) if next == ch => {
|
||||
it.next(); // consume second char
|
||||
(j + next.len_utf8()) - i
|
||||
}
|
||||
_ => ch.len_utf8(),
|
||||
};
|
||||
|
||||
parts.push(token[i..i + op_len].to_string());
|
||||
start = i + op_len;
|
||||
}
|
||||
}
|
||||
|
||||
if start < token.len() {
|
||||
parts.push(token[start..].to_string());
|
||||
}
|
||||
|
||||
parts.retain(|s| !s.trim().is_empty());
|
||||
parts
|
||||
}
|
||||
|
||||
fn has_force_delete_cmdlet(tokens: &[String]) -> bool {
|
||||
const DELETE_CMDLETS: &[&str] = &["remove-item", "ri", "rm", "del", "erase", "rd", "rmdir"];
|
||||
|
||||
// Hard separators that end a command segment (so -Force must be in same segment)
|
||||
const SEG_SEPS: &[char] = &[';', '|', '&', '\n', '\r', '\t'];
|
||||
|
||||
// Soft separators: punctuation that can stick to tokens (blocks, parens, brackets, commas, etc.)
|
||||
const SOFT_SEPS: &[char] = &['{', '}', '(', ')', '[', ']', ',', ';'];
|
||||
|
||||
// Build rough command segments first
|
||||
let mut segments: Vec<Vec<String>> = vec![Vec::new()];
|
||||
for tok in tokens {
|
||||
// If token itself contains segment separators, split it (best-effort)
|
||||
let mut cur = String::new();
|
||||
for ch in tok.chars() {
|
||||
if SEG_SEPS.contains(&ch) {
|
||||
let s = cur.trim();
|
||||
if let Some(msg) = segments.last_mut()
|
||||
&& !s.is_empty()
|
||||
{
|
||||
msg.push(s.to_string());
|
||||
}
|
||||
cur.clear();
|
||||
if let Some(last) = segments.last()
|
||||
&& !last.is_empty()
|
||||
{
|
||||
segments.push(Vec::new());
|
||||
}
|
||||
} else {
|
||||
cur.push(ch);
|
||||
}
|
||||
}
|
||||
let s = cur.trim();
|
||||
if let Some(segment) = segments.last_mut()
|
||||
&& !s.is_empty()
|
||||
{
|
||||
segment.push(s.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
// Now, inside each segment, normalize tokens by splitting on soft punctuation
|
||||
segments.into_iter().any(|seg| {
|
||||
let atoms = seg
|
||||
.iter()
|
||||
.flat_map(|t| t.split(|c| SOFT_SEPS.contains(&c)))
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty());
|
||||
|
||||
let mut has_delete = false;
|
||||
let mut has_force = false;
|
||||
|
||||
for a in atoms {
|
||||
if DELETE_CMDLETS.iter().any(|cmd| a.eq_ignore_ascii_case(cmd)) {
|
||||
has_delete = true;
|
||||
}
|
||||
if a.eq_ignore_ascii_case("-force")
|
||||
|| a.get(..7)
|
||||
.is_some_and(|p| p.eq_ignore_ascii_case("-force:"))
|
||||
{
|
||||
has_force = true;
|
||||
}
|
||||
}
|
||||
|
||||
has_delete && has_force
|
||||
})
|
||||
}
|
||||
|
||||
/// Check for /f or /F flag in CMD del/erase arguments.
|
||||
fn has_force_flag_cmd(args: &[String]) -> bool {
|
||||
args.iter().any(|a| a.eq_ignore_ascii_case("/f"))
|
||||
}
|
||||
|
||||
/// Check for /s or /S flag in CMD rd/rmdir arguments.
|
||||
fn has_recursive_flag_cmd(args: &[String]) -> bool {
|
||||
args.iter().any(|a| a.eq_ignore_ascii_case("/s"))
|
||||
}
|
||||
|
||||
/// Check for /q or /Q flag in CMD rd/rmdir arguments.
|
||||
fn has_quiet_flag_cmd(args: &[String]) -> bool {
|
||||
args.iter().any(|a| a.eq_ignore_ascii_case("/q"))
|
||||
}
|
||||
|
||||
fn args_have_url(args: &[String]) -> bool {
|
||||
args.iter().any(|arg| looks_like_url(arg))
|
||||
}
|
||||
|
||||
fn looks_like_url(token: &str) -> bool {
|
||||
// Strip common PowerShell punctuation around inline URLs (quotes, parens, trailing semicolons).
|
||||
// Capture the middle token after trimming leading quotes/parens/whitespace and trailing semicolons/closing parens.
|
||||
static RE: Lazy<Option<Regex>> =
|
||||
Lazy::new(|| Regex::new(r#"^[ "'\(\s]*([^\s"'\);]+)[\s;\)]*$"#).ok());
|
||||
// If the token embeds a URL alongside other text (e.g., Start-Process('https://...'))
|
||||
// as a single shlex token, grab the substring starting at the first URL prefix.
|
||||
let lowercase_token = token.to_ascii_lowercase();
|
||||
let urlish = lowercase_token
|
||||
.find("https://")
|
||||
.or_else(|| lowercase_token.find("http://"))
|
||||
.map(|idx| &token[idx..])
|
||||
.unwrap_or(token);
|
||||
|
||||
let candidate = RE
|
||||
.as_ref()
|
||||
.and_then(|re| re.captures(urlish))
|
||||
.and_then(|caps| caps.get(1))
|
||||
.map(|m| m.as_str())
|
||||
.unwrap_or(urlish);
|
||||
let Ok(url) = Url::parse(candidate) else {
|
||||
return false;
|
||||
};
|
||||
matches!(url.scheme(), "http" | "https")
|
||||
}
|
||||
|
||||
fn executable_basename(exe: &str) -> Option<String> {
|
||||
let name = exe
|
||||
.rsplit(['/', '\\'])
|
||||
.next()
|
||||
.filter(|name| !name.is_empty())?;
|
||||
let name = match name.as_bytes() {
|
||||
[drive, b':', ..] if drive.is_ascii_alphabetic() => &name[2..],
|
||||
_ => name,
|
||||
};
|
||||
(!name.is_empty()).then(|| name.to_ascii_lowercase())
|
||||
}
|
||||
|
||||
fn is_powershell_executable(exe: &str) -> bool {
|
||||
matches!(
|
||||
executable_basename(exe).as_deref(),
|
||||
Some("powershell") | Some("powershell.exe") | Some("pwsh") | Some("pwsh.exe")
|
||||
)
|
||||
}
|
||||
|
||||
fn is_browser_executable(name: &str) -> bool {
|
||||
matches!(
|
||||
name,
|
||||
"chrome"
|
||||
| "chrome.exe"
|
||||
| "msedge"
|
||||
| "msedge.exe"
|
||||
| "firefox"
|
||||
| "firefox.exe"
|
||||
| "iexplore"
|
||||
| "iexplore.exe"
|
||||
)
|
||||
}
|
||||
|
||||
struct ParsedPowershell<'a> {
|
||||
tokens: Vec<String>,
|
||||
script: Option<&'a str>,
|
||||
}
|
||||
|
||||
fn parse_powershell_invocation(args: &[String]) -> Option<ParsedPowershell<'_>> {
|
||||
if args.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut idx = 0;
|
||||
while idx < args.len() {
|
||||
let arg = &args[idx];
|
||||
let lower = arg.to_ascii_lowercase();
|
||||
match lower.as_str() {
|
||||
"-command" | "/command" | "-c" => {
|
||||
let script = args.get(idx + 1)?;
|
||||
if idx + 2 != args.len() {
|
||||
return None;
|
||||
}
|
||||
let tokens = shlex_split(script)?;
|
||||
return Some(ParsedPowershell {
|
||||
tokens,
|
||||
script: Some(script),
|
||||
});
|
||||
}
|
||||
_ if lower.starts_with("-command:") || lower.starts_with("/command:") => {
|
||||
if idx + 1 != args.len() {
|
||||
return None;
|
||||
}
|
||||
let (_, script) = arg.split_once(':')?;
|
||||
let tokens = shlex_split(script)?;
|
||||
return Some(ParsedPowershell {
|
||||
tokens,
|
||||
script: Some(script),
|
||||
});
|
||||
}
|
||||
"-nologo" | "-noprofile" | "-noninteractive" | "-mta" | "-sta" => {
|
||||
idx += 1;
|
||||
}
|
||||
_ if lower.starts_with('-') => {
|
||||
idx += 1;
|
||||
}
|
||||
_ => {
|
||||
let rest = args[idx..].to_vec();
|
||||
return Some(ParsedPowershell {
|
||||
tokens: rest,
|
||||
script: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::is_dangerous_command_windows;
|
||||
|
||||
fn vec_str(items: &[&str]) -> Vec<String> {
|
||||
items.iter().map(std::string::ToString::to_string).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn powershell_start_process_url_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"powershell",
|
||||
"-NoLogo",
|
||||
"-Command",
|
||||
"Start-Process 'https://example.com'"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn powershell_start_process_url_with_trailing_semicolon_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"powershell",
|
||||
"-Command",
|
||||
"Start-Process('https://example.com');"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn powershell_start_process_mixed_case_urls_are_dangerous() {
|
||||
for script in [
|
||||
"Start-Process('HTTP://example.com');",
|
||||
"Start-Process('hTtPs://example.com');",
|
||||
] {
|
||||
assert!(
|
||||
is_dangerous_command_windows(&vec_str(&["powershell", "-Command", script])),
|
||||
"{script}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn powershell_start_process_local_is_not_flagged() {
|
||||
assert!(!is_dangerous_command_windows(&vec_str(&[
|
||||
"powershell",
|
||||
"-Command",
|
||||
"Start-Process notepad.exe"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_start_with_url_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"cmd",
|
||||
"/c",
|
||||
"start",
|
||||
"https://example.com"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn msedge_with_url_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"msedge.exe",
|
||||
"https://example.com"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explorer_with_directory_is_not_flagged() {
|
||||
assert!(!is_dangerous_command_windows(&vec_str(&[
|
||||
"explorer.exe",
|
||||
"."
|
||||
])));
|
||||
}
|
||||
|
||||
// Force delete tests for PowerShell
|
||||
|
||||
#[test]
|
||||
fn powershell_remove_item_force_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"powershell",
|
||||
"-Command",
|
||||
"Remove-Item test -Force"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn powershell_remove_item_recurse_force_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"powershell",
|
||||
"-Command",
|
||||
"Remove-Item test -Recurse -Force"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn powershell_ri_alias_force_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"pwsh",
|
||||
"-Command",
|
||||
"ri test -Force"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn powershell_remove_item_without_force_is_not_flagged() {
|
||||
assert!(!is_dangerous_command_windows(&vec_str(&[
|
||||
"powershell",
|
||||
"-Command",
|
||||
"Remove-Item test"
|
||||
])));
|
||||
}
|
||||
|
||||
// Force delete tests for CMD
|
||||
#[test]
|
||||
fn cmd_del_force_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"cmd", "/c", "del", "/f", "test.txt"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_erase_force_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"cmd", "/c", "erase", "/f", "test.txt"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_del_without_force_is_not_flagged() {
|
||||
assert!(!is_dangerous_command_windows(&vec_str(&[
|
||||
"cmd", "/c", "del", "test.txt"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_rd_recursive_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"cmd", "/c", "rd", "/s", "/q", "test"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_rd_without_quiet_is_not_flagged() {
|
||||
assert!(!is_dangerous_command_windows(&vec_str(&[
|
||||
"cmd", "/c", "rd", "/s", "test"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_rmdir_recursive_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"cmd", "/c", "rmdir", "/s", "/q", "test"
|
||||
])));
|
||||
}
|
||||
|
||||
// Test exact scenario from issue #8567
|
||||
#[test]
|
||||
fn powershell_remove_item_path_recurse_force_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"powershell",
|
||||
"-Command",
|
||||
"Remove-Item -Path 'test' -Recurse -Force"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn powershell_remove_item_force_with_semicolon_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"powershell",
|
||||
"-Command",
|
||||
"Remove-Item test -Force; Write-Host done"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn powershell_remove_item_force_inside_block_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"powershell",
|
||||
"-Command",
|
||||
"if ($true) { Remove-Item test -Force}"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn powershell_remove_item_force_inside_brackets_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"powershell",
|
||||
"-Command",
|
||||
"[void]( Remove-Item test -Force)]"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_del_path_containing_f_is_not_flagged() {
|
||||
assert!(!is_dangerous_command_windows(&vec_str(&[
|
||||
"cmd",
|
||||
"/c",
|
||||
"del",
|
||||
"C:/foo/bar.txt"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_rd_path_containing_s_is_not_flagged() {
|
||||
assert!(!is_dangerous_command_windows(&vec_str(&[
|
||||
"cmd",
|
||||
"/c",
|
||||
"rd",
|
||||
"C:/source"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_bypass_chained_del_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"cmd", "/c", "echo", "hello", "&", "del", "/f", "file.txt"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn powershell_chained_no_space_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"powershell",
|
||||
"-Command",
|
||||
"Write-Host hi;Remove-Item -Force C:\\tmp"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn powershell_comma_separated_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"powershell",
|
||||
"-Command",
|
||||
"del,-Force,C:\\foo"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_echo_del_is_not_dangerous() {
|
||||
assert!(!is_dangerous_command_windows(&vec_str(&[
|
||||
"cmd", "/c", "echo", "del", "/f"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_del_single_string_argument_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"cmd",
|
||||
"/c",
|
||||
"del /f file.txt"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_del_chained_single_string_argument_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"cmd",
|
||||
"/c",
|
||||
"echo hello & del /f file.txt"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_chained_no_space_del_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"cmd",
|
||||
"/c",
|
||||
"echo hi&del /f file.txt"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_chained_andand_no_space_del_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"cmd",
|
||||
"/c",
|
||||
"echo hi&&del /f file.txt"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_chained_oror_no_space_del_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"cmd",
|
||||
"/c",
|
||||
"echo hi||del /f file.txt"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_start_url_single_string_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"cmd",
|
||||
"/c",
|
||||
"start https://example.com"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_chained_no_space_rmdir_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"cmd",
|
||||
"/c",
|
||||
"echo hi&rmdir /s /q testdir"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_del_force_uppercase_flag_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"cmd", "/c", "DEL", "/F", "file.txt"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmdexe_r_del_force_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"cmd.exe", "/r", "del", "/f", "file.txt"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_start_quoted_url_single_string_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"cmd",
|
||||
"/c",
|
||||
r#"start "https://example.com""#
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_start_title_then_url_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"cmd",
|
||||
"/c",
|
||||
r#"start "" https://example.com"#
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn powershell_rm_alias_force_is_dangerous() {
|
||||
assert!(is_dangerous_command_windows(&vec_str(&[
|
||||
"powershell",
|
||||
"-Command",
|
||||
"rm test -Force"
|
||||
])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn powershell_benign_force_separate_command_is_not_dangerous() {
|
||||
assert!(!is_dangerous_command_windows(&vec_str(&[
|
||||
"powershell",
|
||||
"-Command",
|
||||
"Get-ChildItem -Force; Remove-Item test"
|
||||
])));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user