grippo 0.3.0

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
Documentation
use std::borrow::Cow;

use proptest::prelude::*;

use super::{args, normalised};
use crate::shared_tests::corpus::for_each_record_of;
use crate::windows::argv;

const EN_DASH: char = '\u{2013}';
const EM_DASH: char = '\u{2014}';
const BAR: char = '\u{2015}';

fn values(text: &str) -> Vec<String> {
    normalised(text).map(|a| a.value.into_owned()).collect()
}

fn raw(text: &str) -> Vec<&str> {
    args(text).map(|s| &text[s]).collect()
}

#[test]
fn a_parameter_dash_reads_as_a_hyphen() {
    for dash in ['-', EN_DASH, EM_DASH, BAR] {
        let text = format!("Connect-Db {dash}Password hunter2 {dash}Port 5432");
        assert_eq!(
            values(&text),
            ["Connect-Db", "-Password", "hunter2", "-Port", "5432"],
            "{dash:?}"
        );
    }
    // Only the first character of a word, and only unquoted: a dash inside a
    // word or a string stays.
    assert_eq!(
        values(&format!("a{EN_DASH}b '{EN_DASH}x' {EM_DASH}")),
        [
            format!("a{EN_DASH}b"),
            format!("{EN_DASH}x"),
            "-".to_owned()
        ]
    );
}

#[test]
fn string_quotes_come_in_both_sets() {
    let single = ['\'', '\u{2018}', '\u{2019}', '\u{201a}', '\u{201b}'];
    let double = ['"', '\u{201c}', '\u{201d}', '\u{201e}'];
    for open in single.into_iter().chain(double) {
        for close in single.into_iter().chain(double) {
            // A string closes on any quote of its own set, whichever opened it.
            let same_set = single.contains(&open) == single.contains(&close);
            let text = format!("-Password {open}hunter 2{close} -Port 1");
            let want: Vec<String> = if same_set {
                ["-Password", "hunter 2", "-Port", "1"]
                    .map(String::from)
                    .to_vec()
            } else {
                // Closed by nothing: the string runs to the end of the text.
                vec!["-Password".to_owned(), format!("hunter 2{close} -Port 1")]
            };
            assert_eq!(values(&text), want, "{open:?} {close:?}");
        }
    }
}

#[test]
fn curly_quotes_hold_what_the_c_runtime_splits() {
    let text = "-Password \u{201c}hunter 2\u{201d}";
    assert_eq!(raw(text), ["-Password", "\u{201c}hunter 2\u{201d}"]);
    let msvc: Vec<_> = argv(text).map(|s| &text[s]).collect();
    assert_eq!(msvc, ["-Password", "\u{201c}hunter", "2\u{201d}"]);
}

#[test]
fn a_doubled_quote_is_one_quote() {
    let rows = [
        ("'it''s here'", "it's here"),
        (r#""say ""hi"" now""#, r#"say "hi" now"#),
        ("\"a\u{201d}\u{201d}b\"", "a\u{201d}b"),
        ("'a\u{2019}\u{2018}b'", "a\u{2018}b"),
        ("'x'''", "x'"),
        ("''", ""),
        // A backtick is an escape in a double-quoted string and nothing in a single one.
        (r#""a`"b""#, r#"a"b"#),
        (r"'a`b'", r"a`b"),
    ];
    for (text, want) in rows {
        assert_eq!(values(text), [want], "{text}");
    }
}

#[test]
fn a_backtick_escapes_the_next_character() {
    let rows = [
        // Ticks inside a parameter name, as obfuscation tools write them.
        ("-Pass`word", "-Password"),
        ("-`Pas`s`w`ord", "-Password"),
        // A tick before a, b, e, f, n, r, t, v or 0 is a control character, as in PowerShell.
        ("-Pass`word`r", "-Password\r"),
        ("a` b", "a b"),
        ("a`nb", "a\nb"),
        ("a`tb`0", "a\tb\0"),
        ("`$x", "$x"),
        ("tail`", "tail"),
        ("\"a`nb\"", "a\nb"),
    ];
    for (text, want) in rows {
        assert_eq!(values(text), [want], "{text:?}");
    }
    assert_eq!(raw("a` b c"), ["a` b", "c"]);
}

#[test]
fn quotes_inside_a_word_join_it() {
    assert_eq!(values("-Pass\"word\" x"), ["-Password", "x"]);
    assert_eq!(values("-Pass'word' x"), ["-Password", "x"]);
    assert_eq!(
        values("-Password:\u{201c}hunter 2\u{201d} x"),
        ["-Password:hunter 2", "x"]
    );
    assert_eq!(
        raw("-Password:\u{201c}hunter 2\u{201d} x"),
        ["-Password:\u{201c}hunter 2\u{201d}", "x"]
    );
    // Statement and list punctuation stays in the word.
    assert_eq!(values("a,b;c|d&e (f) {g}"), ["a,b;c|d&e", "(f)", "{g}"]);
}

#[test]
fn white_space_is_powershell_white_space() {
    // Space, tab, vertical tab, form feed, line breaks, NEL, no-break space and
    // the Unicode separators end a word.
    for sep in [
        ' ', '\t', '\u{b}', '\u{c}', '\n', '\r', '\u{85}', '\u{a0}', '\u{1680}', '\u{2000}',
        '\u{200a}', '\u{2028}', '\u{2029}', '\u{202f}', '\u{205f}', '\u{3000}',
    ] {
        assert_eq!(values(&format!("a{sep}b")), ["a", "b"], "{sep:?}");
    }
    // Zero-width characters aren't separators.
    for joiner in ['\u{200b}', '\u{200d}', '\u{feff}'] {
        assert_eq!(
            values(&format!("a{joiner}b")),
            [format!("a{joiner}b")],
            "{joiner:?}"
        );
    }
    assert_eq!(raw("  a \t b  "), ["a", "b"]);
}

#[test]
fn an_open_string_takes_the_rest() {
    assert_eq!(
        values("-Password \"hunter 2 -Port 1"),
        ["-Password", "hunter 2 -Port 1"]
    );
    assert_eq!(values("x '"), ["x", ""]);
    assert_eq!(values(""), Vec::<String>::new());
    assert_eq!(values(" \t "), Vec::<String>::new());
}

#[test]
fn plain_words_borrow() {
    let text = "Get-Item -Path C:\\x";
    assert!(normalised(text).all(|a| matches!(a.value, Cow::Borrowed(_))));
    let text = "a 'b'";
    let owned: Vec<_> = normalised(text)
        .map(|a| matches!(a.value, Cow::Owned(_)))
        .collect();
    assert_eq!(owned, [false, true]);
}

/// Each line of the Sysmon and Security 4688 command lines of a PowerShell host.
fn powershell_lines() -> Vec<String> {
    let mut lines = Vec::new();
    for_each_record_of(&["xml-lines"], |r| {
        let text = String::from_utf8_lossy(r.bytes);
        let mut rest: &str = &text;
        let tag = "Name='CommandLine'>";
        while let Some(at) = rest.find(tag) {
            rest = &rest[at + tag.len()..];
            let end = rest.find("</Data>").unwrap_or(rest.len());
            let line = rest[..end].replace("&gt;", ">").replace("&amp;", "&");
            if line.to_ascii_lowercase().contains("powershell") {
                lines.push(line);
            }
        }
        if let Some(line) = text.strip_prefix("\tProcess Command Line:\t")
            && line.to_ascii_lowercase().contains("powershell")
        {
            lines.push(line.trim_end_matches(['\r', '\n']).to_owned());
        }
    });
    lines
}

/// What holds for any text: the words are ordered spans on char boundaries
/// with only white space between them, and a borrowed value is the span.
fn check_text(text: &str) {
    let spans: Vec<_> = args(text).collect();
    let mut end = 0;
    for span in &spans {
        assert!(
            end <= span.start && span.start < span.end,
            "{text:?}: {spans:?}"
        );
        assert!(
            text.get(end..span.start)
                .is_some_and(|gap| gap.chars().all(super::is_break))
        );
        assert!(text.get(span.clone()).is_some(), "{text:?}: {span:?}");
        end = span.end;
    }
    assert!(
        text.get(end..)
            .is_some_and(|rest| rest.chars().all(super::is_break))
    );
    let words: Vec<_> = normalised(text).collect();
    assert_eq!(
        words.iter().map(|w| w.span.clone()).collect::<Vec<_>>(),
        spans
    );
    for word in &words {
        if let Cow::Borrowed(v) = word.value {
            assert_eq!(v, &text[word.span.clone()], "{text:?}");
        }
    }
}

#[test]
fn real_powershell_command_lines() {
    let lines = powershell_lines();
    assert!(
        lines.len() >= 20,
        "{} PowerShell command lines",
        lines.len()
    );
    for line in &lines {
        check_text(line);
    }
    // A 4688 command text with a sub-expression and a variable.
    let text = r"& {C:\Windows\System32\rundll32.exe C:\windows\System32\comsvcs.dll, MiniDump (Get-Process lsass).id $env:TEMP\lsass-comsvcs.dmp full}";
    assert!(lines.iter().any(|l| l.contains(text)), "not in the corpus");
    assert_eq!(
        values(text),
        [
            "&",
            r"{C:\Windows\System32\rundll32.exe",
            r"C:\windows\System32\comsvcs.dll,",
            "MiniDump",
            "(Get-Process",
            "lsass).id",
            r"$env:TEMP\lsass-comsvcs.dmp",
            "full}",
        ]
    );
}

proptest! {
    #[test]
    fn any_text_reads_consistently(
        text in "[ \t\n\\-\u{2013}\u{2015}'\"`\u{2018}\u{201a}\u{201c}\u{201e}a-c:;\u{a0}\u{3000}\u{1f600}]{0,40}"
    ) {
        check_text(&text);
    }

    #[test]
    fn a_ticked_name_matches_the_plain_one(
        name in "[A-Za-z]{1,12}",
        ticks in proptest::collection::vec(any::<bool>(), 12),
    ) {
        let mut ticked = String::from("-");
        for (c, tick) in name.chars().zip(ticks) {
            if tick && c.is_ascii_alphabetic() && !"abefnrtv".contains(c.to_ascii_lowercase()) {
                ticked.push('`');
            }
            ticked.push(c);
        }
        prop_assert_eq!(values(&ticked), [format!("-{name}")]);
    }
}