mod cmdlets;
mod encoded;
mod lex;
mod statement;
#[cfg(test)]
mod tests;
use super::{ClassifyError, MAX_DEPTH, ShellContext, Sink};
use crate::action::AtomicAction;
use crate::obfuscation::{Dialect, assess};
pub const POWERSHELL: &str = "PowerShell";
#[must_use]
pub fn is_powershell(shell: &str) -> bool {
shell.eq_ignore_ascii_case(POWERSHELL)
}
const EVALUATORS: &[&str] = &[
"iex",
"invoke-expression",
"icm",
"invoke-command",
"add-type",
"start-job",
"invoke-item",
];
const BUILDERS: &[&str] = &[
"[scriptblock]",
".invoke(",
"frombase64string",
"newscriptblock",
"downloadstring(",
"downloadfile(",
];
#[must_use]
pub fn classify(
command: &str,
ctx: &ShellContext<'_>,
) -> (super::ParseOutcome, Vec<(AtomicAction, bool)>) {
let mut sink = Sink::default();
let stopped = classify_into(command, ctx, &mut sink, 0).err();
let needs_review =
sink.needs_review || stopped.as_ref().is_some_and(ClassifyError::needs_review);
let reason = sink.skipped.or(stopped).map_or_else(
|| {
"PowerShell is read in preview: a line is never allowed on that reading alone"
.to_owned()
},
|e| e.to_string(),
);
let outcome = super::ParseOutcome::Unparseable {
reason,
atoms: sink.atoms,
needs_review,
};
(outcome, sink.globs)
}
pub(super) fn classify_into(
command: &str,
ctx: &ShellContext<'_>,
sink: &mut Sink,
depth: u8,
) -> Result<(), ClassifyError> {
if depth > MAX_DEPTH {
return Err(ClassifyError::TooDeep);
}
let assessed = assess(command, Dialect::PowerShell);
if assessed.obfuscated() {
sink.push(super::obfuscated_atom(&assessed))?;
}
let lower = command.to_ascii_lowercase();
let tokens = lex::lex(command).map_err(|e| {
ClassifyError::Lex(match e {
lex::LexError::Single => crate::lexer::LexError::UnterminatedSingleQuote,
_ => crate::lexer::LexError::UnterminatedDoubleQuote,
})
})?;
let evaluates = BUILDERS.iter().any(|b| lower.contains(b))
|| tokens.iter().any(|t| {
matches!(t, lex::Tok::Word(w) if w.literal().is_some_and(|l| {
EVALUATORS.contains(&l.to_ascii_lowercase().as_str())
}))
});
let piped_only = statement::evaluates_piped_input_only(&tokens);
if evaluates && !piped_only {
opaque(sink)?;
for url in urls(command) {
let line = format!("curl -fsSL {} | sh", statement::quote(&url));
super::commands::classify_into(&line, ctx, sink, depth + 1)?;
}
}
for decoded in encoded::base64_literals(command) {
if let Err(e) = classify_into(&decoded, ctx, sink, depth + 1) {
sink.skip(e);
}
}
let posix = statement::translate(&tokens, ctx, sink, depth)?;
if !posix.trim().is_empty() {
super::commands::classify_into(&posix, ctx, sink, depth)?;
}
Ok(())
}
fn opaque(sink: &mut Sink) -> Result<(), ClassifyError> {
sink.push(AtomicAction::Shell {
argv: vec!["@opaque-code".to_owned(), "powershell".to_owned()],
})
}
fn urls(text: &str) -> Vec<String> {
let lower = text.to_ascii_lowercase();
let mut out = Vec::new();
for scheme in ["https://", "http://"] {
for (at, _) in lower.match_indices(scheme) {
let end = text[at..]
.find(|c: char| c.is_whitespace() || "'\"`)(;|,".contains(c))
.map_or(text.len(), |e| at + e);
let url = text[at..end].to_owned();
if !out.contains(&url) {
out.push(url);
}
}
}
out
}
pub(super) fn nested(argv: &[String], ctx: &ShellContext<'_>, sink: &mut Sink, depth: u8) {
if !argv
.first()
.is_some_and(|first| is_powershell_program(first))
{
return;
}
let before = sink.skipped.take();
let read = match statement::cli_command(&argv[1..]) {
statement::Cli::Command(line) => classify_into(&line, ctx, sink, depth + 1),
statement::Cli::Encoded(text) => opaque(sink).and_then(|()| {
encoded::utf16le_base64(&text)
.map_or(Ok(()), |line| classify_into(&line, ctx, sink, depth + 1))
}),
statement::Cli::Nothing => Ok(()),
};
let kept = sink
.skipped
.take()
.into_iter()
.chain(read.err())
.find(ClassifyError::needs_review);
sink.skipped = before;
if let Some(error) = kept {
sink.skip(error);
}
}
pub(super) fn is_powershell_program(word: &str) -> bool {
let name = word
.rsplit(['/', '\\'])
.next()
.unwrap_or(word)
.to_ascii_lowercase();
let name = name.strip_suffix(".exe").unwrap_or(&name);
matches!(name, "powershell" | "pwsh" | "powershell_ise")
}