use std::borrow::Cow;
use std::iter::repeat_n;
use proptest::prelude::*;
use super::{argv, normalised};
use crate::shared_tests::corpus::for_each_record_of;
fn values(line: &str) -> Vec<String> {
normalised(line).map(|a| a.value.into_owned()).collect()
}
fn after_program(args: &str) -> Vec<String> {
let mut all = values(&format!("prog {args}"));
assert_eq!(all.remove(0), "prog");
all
}
fn raw(line: &str) -> Vec<&str> {
argv(line).map(|s| &line[s]).collect()
}
fn quote(arg: &str) -> String {
let wrap = arg.is_empty() || arg.contains([' ', '\t']);
let mut out = String::new();
if wrap {
out.push('"');
}
let mut slashes = 0;
for c in arg.chars() {
if c == '\\' {
slashes += 1;
} else {
if c == '"' {
out.extend(repeat_n('\\', slashes + 1));
}
slashes = 0;
}
out.push(c);
}
if wrap {
out.extend(repeat_n('\\', slashes));
out.push('"');
}
out
}
fn quote_program(program: &str) -> String {
if program.is_empty() || program.contains([' ', '\t']) {
format!("\"{program}\"")
} else {
program.to_owned()
}
}
fn join(args: &[String]) -> String {
let (program, rest) = args.split_first().expect("a program name");
let mut line = quote_program(program);
for arg in rest {
line.push(' ');
line.push_str("e(arg));
}
line
}
fn reference(line: &str) -> Vec<String> {
let mut chars = line.chars().peekable();
let mut program = String::new();
let mut in_quotes = false;
while let Some(&c) = chars.peek() {
match c {
'"' => in_quotes = !in_quotes,
' ' | '\t' if !in_quotes => break,
_ => program.push(c),
}
chars.next();
}
let mut args = vec![program];
loop {
while matches!(chars.peek(), Some(' ' | '\t')) {
chars.next();
}
if chars.peek().is_none() {
return args;
}
let mut arg = String::new();
let mut in_quotes = false;
loop {
match chars.next() {
None | Some(' ' | '\t') if !in_quotes => break,
None => break,
Some('\\') => {
let mut slashes = 1;
while chars.next_if_eq(&'\\').is_some() {
slashes += 1;
}
if chars.next_if_eq(&'"').is_some() {
arg.extend(repeat_n('\\', slashes / 2));
if slashes % 2 == 1 || (in_quotes && chars.next_if_eq(&'"').is_some()) {
arg.push('"');
} else {
in_quotes = !in_quotes;
}
} else {
arg.extend(repeat_n('\\', slashes));
}
}
Some('"') => {
if in_quotes && chars.next_if_eq(&'"').is_some() {
arg.push('"');
} else {
in_quotes = !in_quotes;
}
}
Some(c) => arg.push(c),
}
}
args.push(arg);
}
}
fn check_line(line: &str) {
let spans: Vec<_> = argv(line).collect();
let mut end = 0;
for (i, span) in spans.iter().enumerate() {
assert!(
end <= span.start && span.end <= line.len(),
"{line:?}: {spans:?}"
);
let text = line
.get(span.clone())
.unwrap_or_else(|| panic!("{line:?}: {span:?}"));
assert!(
line[end..span.start]
.bytes()
.all(|b| b == b' ' || b == b'\t'),
"{line:?}: text between spans in {spans:?}"
);
assert!(
!text.starts_with([' ', '\t']) || text.is_empty(),
"{line:?}: span {i} starts with white space"
);
end = span.end;
}
assert_eq!(spans.first().map(|s| s.start), Some(0), "{line:?}");
assert!(
line[end..].bytes().all(|b| b == b' ' || b == b'\t'),
"{line:?}"
);
let args: Vec<_> = normalised(line).collect();
assert_eq!(
args.iter().map(|a| a.span.clone()).collect::<Vec<_>>(),
spans,
"{line:?}"
);
for arg in &args {
if let Cow::Borrowed(v) = arg.value {
assert_eq!(v, &line[arg.span.clone()], "{line:?}");
}
}
let got: Vec<String> = args.into_iter().map(|a| a.value.into_owned()).collect();
assert_eq!(got, reference(line), "{line:?}");
assert_eq!(
values(&join(&got)),
got,
"{line:?} quoted back as {:?}",
join(&got)
);
}
#[test]
fn microsoft_table() {
let rows: [(&str, &[&str]); 6] = [
(r#""a b c" d e"#, &["a b c", "d", "e"]),
(r#""ab\"c" "\\" d"#, &["ab\"c", "\\", "d"]),
(r#"a\\\b d"e f"g h"#, &["a\\\\\\b", "de fg", "h"]),
(r#"a\\\"b c d"#, &["a\\\"b", "c", "d"]),
(r#"a\\\\"b c" d e"#, &["a\\\\b c", "d", "e"]),
(r#"a"b"" c d"#, &["ab\" c d"]),
];
for (input, want) in rows {
assert_eq!(after_program(input), want, "{input}");
}
}
#[test]
fn program_name_has_its_own_rule() {
let rows: [(&str, &[&str]); 11] = [
(
r#""C:\Program Files\a.exe" x"#,
&[r"C:\Program Files\a.exe", "x"],
),
(
r"C:\Program Files\a.exe x",
&[r"C:\Program", r"Files\a.exe", "x"],
),
(r#""C:\dir\" x"#, &[r"C:\dir\", "x"]),
(r#""C:\a b"\c.exe x"#, &[r"C:\a b\c.exe", "x"]),
(r#"a"b c"d e"#, &["ab cd", "e"]),
(r#"prog\"x y"#, &[r"prog\x y"]),
(r#"prog a\"x y"#, &["prog", "a\"x", "y"]),
(r#""""#, &[""]),
(r#""" x"#, &["", "x"]),
(" x", &["", "x"]),
("", &[""]),
];
for (line, want) in rows {
assert_eq!(values(line), want, "{line:?}");
}
let bounds = |line: &str| argv(line).map(|s| (s.start, s.end)).collect::<Vec<_>>();
assert_eq!(bounds(" "), [(0, 0)]);
assert_eq!(bounds(" x"), [(0, 0), (1, 2)]);
assert_eq!(bounds(""), [(0, 0)]);
}
#[test]
fn spans_are_the_text_as_written() {
let line = "prog \"a b\" c\\\"d \t\"e f\"g \"open one";
assert_eq!(
raw(line),
["prog", "\"a b\"", "c\\\"d", "\"e f\"g", "\"open one"]
);
assert_eq!(values(line), ["prog", "a b", "c\"d", "e fg", "open one"]);
let mut args = argv(line);
assert_eq!(args.by_ref().count(), 5);
assert_eq!(args.next(), None);
assert_eq!(args.next(), None);
}
#[test]
fn quote_rules() {
let rows: [(&str, &[&str]); 12] = [
(r#"p a\\"b c" d"#, &["p", r"a\b c", "d"]),
(r#"p a\\\"b"#, &["p", r#"a\"b"#]),
(r"p \", &["p", r"\"]),
(r"p \\ \\\", &["p", r"\\", r"\\\"]),
(r#"p "\\\\""#, &["p", r"\\"]),
(r#"p "a""b c""#, &["p", "a\"b c"]),
(r#"p """"#, &["p", "\""]),
(r#"p a""b"#, &["p", "ab"]),
(r#"p "" x"#, &["p", "", "x"]),
(r#"p "a b "#, &["p", "a b "]),
(r"p ", &["p"]),
("p\ta\t\tb\t", &["p", "a", "b"]),
];
for (line, want) in rows {
assert_eq!(values(line), want, "{line:?}");
}
}
#[test]
fn only_space_and_tab_separate() {
let line = "p a\nb c\u{a0}d e\u{3000}f";
assert_eq!(values(line), ["p", "a\nb", "c\u{a0}d", "e\u{3000}f"]);
}
fn mask(line: &str, flag: &str) -> String {
let args: Vec<_> = normalised(line).collect();
let mut out = line.to_owned();
for (i, arg) in args.iter().enumerate().rev() {
let value = arg.value.to_ascii_lowercase();
let joined = value
.strip_prefix(flag)
.is_some_and(|rest| rest.starts_with([':', '=']));
if joined {
out.replace_range(arg.span.clone(), "*");
} else if value == flag
&& let Some(next) = args.get(i + 1)
{
out.replace_range(next.span.clone(), "*");
}
}
out
}
#[test]
fn quote_insertion_cannot_dodge_a_mask() {
let lines = [
"db.exe -password hunter2",
"db.exe -Password hunter2",
"db.exe -PASSWORD hunter2",
"db.exe -Pass\"word\" hunter2",
"db.exe \"-Password\" hunter2",
"db.exe -Pa\"\"ssword hunter2",
"db.exe -P\"a\"s\"s\"w\"o\"r\"d\" hunter2",
"db.exe \"-Pass\"word hunter2",
"db.exe -Password\thunter2",
"db.exe -Pass\"word\":hunter2",
"db.exe \"-Password=hunter2\"",
"db.exe -Pass\"word\"=\"hunter2\"",
];
for line in lines {
let masked = mask(line, "-password");
assert!(!masked.contains("hunter2"), "{line:?} left {masked:?}");
}
assert!(!"db.exe -Pass\"word\" hunter2".contains("-Password"));
}
#[test]
fn what_is_not_the_c_runtime_stays_as_written() {
assert_eq!(values(r#"p -Pass\"word"#), ["p", "-Pass\"word"]);
assert_eq!(values("p -p^a^s^s x"), ["p", "-p^a^s^s", "x"]);
assert_eq!(
values("p -Password \u{201c}hunter 2\u{201d}"),
["p", "-Password", "\u{201c}hunter", "2\u{201d}"]
);
assert_eq!(
mask("p -Password \u{201c}hunter 2\u{201d}", "-password"),
"p -Password * 2\u{201d}"
);
assert_eq!(values("p -P\"assword hunter2"), ["p", "-Password hunter2"]);
}
#[test]
fn unicode_stays_whole() {
let line = "\u{e9}.exe \"d\u{e9} \u{1f600}\" \u{201c}x";
assert_eq!(
raw(line),
["\u{e9}.exe", "\"d\u{e9} \u{1f600}\"", "\u{201c}x"]
);
assert_eq!(
values(line),
["\u{e9}.exe", "d\u{e9} \u{1f600}", "\u{201c}x"]
);
}
const REAL: [(&str, &[&str]); 6] = [
(
r#""C:\Windows\system32\chcp.com" 65001"#,
&[r"C:\Windows\system32\chcp.com", "65001"],
),
(
r#""C:\Windows\System32\rundll32.exe" C:\windows\System32\comsvcs.dll MiniDump 840 C:\Users\ADMINI~1\AppData\Local\Temp\lsass-comsvcs.dmp full"#,
&[
r"C:\Windows\System32\rundll32.exe",
r"C:\windows\System32\comsvcs.dll",
"MiniDump",
"840",
r"C:\Users\ADMINI~1\AppData\Local\Temp\lsass-comsvcs.dmp",
"full",
],
),
(
r#"C:\Windows\system32\cmd.exe /c "C:\Program Files\SplunkUniversalForwarder\bin\splunk.exe" _internal pre-flight-checks --answer-yes --no-prompt 2>&1"#,
&[
r"C:\Windows\system32\cmd.exe",
"/c",
r"C:\Program Files\SplunkUniversalForwarder\bin\splunk.exe",
"_internal",
"pre-flight-checks",
"--answer-yes",
"--no-prompt",
"2>&1",
],
),
(
r#"C:\Windows\system32\cmd.exe /c ""C:\Program Files\SplunkUniversalForwarder\etc\system\bin\powershell.cmd" --scheme""#,
&[
r"C:\Windows\system32\cmd.exe",
"/c",
r"C:\Program",
r"Files\SplunkUniversalForwarder\etc\system\bin\powershell.cmd --scheme",
],
),
(
r"PowerShell -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -EncodedCommand dwBoAG8AYQBtAGkA",
&[
"PowerShell",
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Unrestricted",
"-EncodedCommand",
"dwBoAG8AYQBtAGkA",
],
),
(
r#"C:\Windows\system32\cmd.exe /c "C:\Program Files\SplunkUniversalForwarder\bin\splunk.exe" _RAW_envvars"#,
&[
r"C:\Windows\system32\cmd.exe",
"/c",
r"C:\Program Files\SplunkUniversalForwarder\bin\splunk.exe",
"_RAW_envvars",
],
),
];
fn unescape(xml: &str) -> String {
xml.replace("<", "<")
.replace(">", ">")
.replace(""", "\"")
.replace("'", "'")
.replace("&", "&")
}
fn command_lines(text: &str) -> Vec<String> {
let mut found = Vec::new();
for tag in ["Name='CommandLine'>", "Name=\"CommandLine\">"] {
let mut rest = text;
while let Some(at) = rest.find(tag) {
rest = &rest[at + tag.len()..];
let end = rest.find("</Data>").unwrap_or(rest.len());
found.push(unescape(&rest[..end]));
}
}
if let Some(line) = text.strip_prefix("\tProcess Command Line:\t") {
found.push(line.trim_end_matches(['\r', '\n']).to_owned());
}
found.retain(|l| !l.is_empty());
found
}
fn corpus_command_lines() -> Vec<String> {
let mut lines = Vec::new();
for_each_record_of(&["xml-lines"], |r| {
lines.extend(command_lines(&String::from_utf8_lossy(r.bytes)));
});
lines
}
#[test]
fn real_sysmon_and_4688_command_lines() {
let lines = corpus_command_lines();
assert!(lines.len() >= 100, "{} command lines", lines.len());
for line in &lines {
check_line(line);
}
for (line, want) in REAL {
assert!(lines.iter().any(|l| l == line), "not in the corpus: {line}");
assert_eq!(values(line), want, "{line}");
}
}
fn lab_lines() -> Vec<(String, Vec<String>)> {
crate::shared_tests::windows_text::lab("security_4688.xml")
.into_iter()
.map(|(image, bytes)| {
let xml = String::from_utf8_lossy(&bytes);
(image, command_lines(xml.trim_start_matches('\u{feff}')))
})
.collect()
}
#[test]
fn lab_vm_4688_command_lines() {
let lab = lab_lines();
let rows: [(&str, &[&str]); 3] = [
(
r#""C:\WINDOWS\system32\cmd.exe" /c echo "C:\Program Files\App\app.exe" --user "DOMAIN\svc backup" "#,
&[
r"C:\WINDOWS\system32\cmd.exe",
"/c",
"echo",
r"C:\Program Files\App\app.exe",
"--user",
r"DOMAIN\svc backup",
],
),
(
r#""C:\WINDOWS\system32\cmd.exe" /c echo -Pass"word" Hunter2Example! -p^a^s^s x "#,
&[
r"C:\WINDOWS\system32\cmd.exe",
"/c",
"echo",
"-Password",
"Hunter2Example!",
"-p^a^s^s",
"x",
],
),
(
r#""C:\WINDOWS\system32\cmd.exe" /c echo "quoted arg" plain\path "trailing\\" a\\\"b "#,
&[
r"C:\WINDOWS\system32\cmd.exe",
"/c",
"echo",
"quoted arg",
"plain\\path",
"trailing\\",
"a\\\"b",
],
),
];
for (image, lines) in &lab {
assert!(!lines.is_empty(), "{image}: no command lines");
for line in lines {
check_line(line);
}
for (line, want) in rows {
assert!(
lines.iter().any(|l| l == line),
"{image}: Windows did not log {line}"
);
assert_eq!(values(line), want, "{image}: {line}");
}
}
}
#[cfg(feature = "scrub")]
mod scrubbed {
use super::normalised;
use crate::scrub::Scrubber;
fn scrub_line(scrubber: &Scrubber, line: &str) -> String {
let (mut scratch, mut report) = (scrubber.scratch(), scrubber.report());
let args: Vec<_> = normalised(line).collect();
let mut out = line.to_owned();
for i in (1..args.len()).rev() {
let value = args[i].value.as_bytes();
let flag = (i > 1).then(|| args[i - 1].value.trim_start_matches(['-', '/']));
let edit = flag
.and_then(|f| scrubber.scrub_field(&[f], value, &mut scratch, &mut report))
.or_else(|| scrubber.scrub_text(value, &mut scratch, &mut report));
if let Some(edit) = edit {
out.replace_range(args[i].span.clone(), &String::from_utf8_lossy(&edit));
}
}
out
}
#[test]
fn credential_flags_mask_through_quoting() {
let scrubber = Scrubber::gitleaks().unwrap();
let masked = "db.exe -Password [CREDENTIAL_FIELD_REDACTED]";
for line in [
"db.exe -Password hunter2",
"db.exe -Pass\"word\" hunter2",
"db.exe /Pa\"\"ssword \"hunter2\"",
"db.exe \"-Password\"\thunter2",
] {
let got = scrub_line(&scrubber, line);
assert!(
got.ends_with("[CREDENTIAL_FIELD_REDACTED]"),
"{line:?} gave {got:?}"
);
assert!(!got.contains("hunter2"), "{line:?} gave {got:?}");
}
assert_eq!(scrub_line(&scrubber, "db.exe -Password hunter2"), masked);
for line in [
"db.exe --pass\"word\"=hunter2",
"db.exe \"--password:hunter2\"",
] {
let got = scrub_line(&scrubber, line);
assert!(!got.contains("hunter2"), "{line:?} gave {got:?}");
}
assert_eq!(
scrub_line(&scrubber, "db.exe -Port 5432"),
"db.exe -Port 5432"
);
}
#[test]
fn the_raw_line_alone_is_dodged() {
let scrubber = Scrubber::gitleaks().unwrap();
let (mut scratch, mut report) = (scrubber.scratch(), scrubber.report());
let line = "db.exe -Pass\"word\"=hunter2";
let out = scrubber.scrub_text(line.as_bytes(), &mut scratch, &mut report);
assert_eq!(out, None, "the text layer reads the key as written");
assert!(!scrub_line(&scrubber, line).contains("hunter2"));
}
}
#[cfg(feature = "expr")]
#[test]
fn a_cel_filter_matches_the_normalised_line() {
use crate::expr::Program;
use crate::record::Line;
let program = Program::compile(r#"message.contains("-Password ")"#).unwrap();
let line = r#"db.exe -Pass"word" hunter2"#;
let joined = values(line).join(" ");
assert!(!program.matches_record(Line::new(line.as_bytes())));
assert!(program.matches_record(Line::new(joined.as_bytes())));
}
fn argument() -> impl Strategy<Value = String> {
"[a-zA-Z0-9 \t\"\\\\.:=\u{e9}\u{201c}]{0,12}"
}
proptest! {
#[test]
fn quoted_argv_splits_back(
program in "[a-zA-Z0-9 \t\\\\.:\u{e9}]{0,12}",
rest in proptest::collection::vec(argument(), 0..6),
) {
let mut args = vec![program];
args.extend(rest);
let line = join(&args);
prop_assert_eq!(values(&line), args, "{}", line);
}
#[test]
fn any_line_reads_consistently(line in "[ \t\"\\\\a-c=\u{e9}\u{201c}\u{1f600}]{0,40}") {
check_line(&line);
}
}