use super::{Decoder, stock};
use crate::parse::{DECODE_MAX_BYTES, Parser, valid_parser_name};
#[test]
fn every_text_and_rsyslog_stock_decoder_decodes_writes_no_field_and_has_a_valid_name() {
let text: Vec<Decoder> = stock()
.into_iter()
.filter(|d| {
d.name().starts_with("utf") || d.name().starts_with("charset") || d.name() == "rsyslog"
})
.collect();
assert_eq!(
text.len(),
usize::from(cfg!(feature = "decode-text")) * 4
+ usize::from(cfg!(feature = "decode-rsyslog"))
);
for decoder in text {
assert!(valid_parser_name(decoder.name()), "{}", decoder.name());
assert!(decoder.decodes());
assert_eq!(decoder.max_bytes(), DECODE_MAX_BYTES);
}
}
#[cfg(feature = "decode-text")]
mod text_rows {
use super::super::{Codec, Decoder, stock};
use crate::charset::Charset;
use crate::parse::{Decoded, Fields, ParseError, Parsed, Parser, valid_parser_name};
use crate::shared_tests::corpus::file_bytes;
pub fn decoder(label: &str) -> Decoder {
Decoder::new(Codec::Text(Charset::for_label(label).unwrap()))
}
pub fn read(decoder: &Decoder, bytes: &[u8]) -> Vec<u8> {
let mut out = b"kept".to_vec();
decoder.decode(bytes, &mut out).unwrap();
assert_eq!(&out[..4], b"kept");
out.split_off(4)
}
pub fn text(label: &str, bytes: &[u8]) -> String {
String::from_utf8(read(&decoder(label), bytes)).unwrap()
}
#[test]
fn every_charset_gets_a_valid_decoder_name() {
let names: Vec<String> = stock().iter().map(|d| d.name().to_owned()).collect();
for want in ["utf8", "utf16le", "utf16be", "charset:windows-1252"] {
assert!(names.iter().any(|n| n == want), "{want} in {names:?}");
}
let labels = [
"windows-1250",
"windows-1251",
"windows-1252",
"windows-1253",
"windows-1254",
"windows-1255",
"windows-1256",
"windows-1257",
"windows-1258",
"windows-874",
"iso-8859-2",
"iso-8859-8-i",
"iso-8859-15",
"koi8-r",
"koi8-u",
"ibm866",
"macintosh",
"x-mac-cyrillic",
"x-user-defined",
"gbk",
"gb18030",
"big5",
"euc-jp",
"euc-kr",
"shift_jis",
"iso-2022-jp",
];
for label in labels {
let d = decoder(label);
assert!(valid_parser_name(d.name()), "{label}: {}", d.name());
assert!(d.name().starts_with("charset:"), "{label}: {}", d.name());
}
assert_eq!(decoder("latin1").name(), "charset:windows-1252");
assert_eq!(decoder("utf-16").name(), "utf16le");
}
#[test]
fn text_reads_in_each_charset() {
let rows: &[(&str, &[u8], &str)] = &[
("utf-16le", b"a\x00b\x00", "ab"),
("utf-16le", b"\xFF\xFEa\x00b\x00", "ab"),
("utf-16be", b"\xFE\xFF\x00a\x00b", "ab"),
("utf-16be", b"\xFE\xFF\x00a\x00", "a\u{FFFD}"),
("utf-16be", b"\x00a\xD8\x3D\xDE\x00", "a\u{1F600}"),
("utf-16le", b"a\x00\x00\xD8b\x00", "a\u{FFFD}b"),
("utf-16le", b"a\x00b", "a\u{FFFD}"),
("utf-16le", b"", ""),
("utf-8", b"\xEF\xBB\xBFok\xFF", "ok\u{FFFD}"),
(
"windows-1252",
b"caf\xE9 \x80 \x93q\x94",
"caf\u{e9} \u{20ac} \u{201c}q\u{201d}",
),
(
"windows-1251",
b"\xCF\xF0\xE8\xE2\xE5\xF2",
"\u{41f}\u{440}\u{438}\u{432}\u{435}\u{442}",
),
(
"shift_jis",
b"\x83\x65\x83\x58\x83\x67",
"\u{30c6}\u{30b9}\u{30c8}",
),
];
for (label, bytes, want) in rows {
assert_eq!(text(label, bytes), *want, "{label} {bytes:?}");
}
}
#[test]
fn a_decode_stops_at_its_cap_and_leaves_out_alone() {
let euros = vec![0x80_u8; 5000];
let d = decoder("windows-1252");
assert_eq!(
read(&d.clone().with_max_bytes(15_000), &euros).len(),
15_000
);
let mut out = b"kept".to_vec();
let got = d.with_max_bytes(14_999).decode(&euros, &mut out);
assert!(
matches!(
got,
Err(ParseError::Limit {
what: "decoded bytes"
})
),
"{got:?}"
);
assert_eq!(out, b"kept");
}
#[test]
fn utf16_pairs_cut_by_a_decode_step_come_back_whole() {
let want: String = std::iter::once('x')
.chain(std::iter::repeat_n('\u{1F600}', 5000))
.collect();
let units: Vec<u16> = want.encode_utf16().collect();
let le: Vec<u8> = units.iter().flat_map(|u| u.to_le_bytes()).collect();
let be: Vec<u8> = units.iter().flat_map(|u| u.to_be_bytes()).collect();
for (label, bytes) in [("utf-16le", le), ("utf-16be", be)] {
assert_eq!(text(label, &bytes), want, "{label}");
}
}
#[test]
fn a_text_decoder_hands_on_its_text_and_writes_no_field() {
let d = decoder("utf-16le");
let mut out = Fields::new();
let got = d.parse(b"\xFF\xFEo\x00k\x00", &mut out).unwrap();
assert_eq!(got, Parsed::Decoded(Decoded::new(b"ok".to_vec())));
assert_eq!(out.as_slice().len(), 0);
assert!(d.decodes());
assert!(!d.detectable());
}
#[test]
fn real_utf16_files_decode_to_their_utf8_twin() {
let sample = |name: &str| {
file_bytes(
"quick-xml-documents",
&format!("tests/documents/encoding/{name}"),
)
};
let twin = String::from_utf8(sample("utf8.xml")).unwrap();
for (name, label) in [
("utf16le.xml", "utf-16le"),
("utf16le-bom.xml", "utf-16le"),
("utf16be.xml", "utf-16be"),
("utf16be-bom.xml", "utf-16be"),
] {
assert_eq!(text(label, &sample(name)), twin, "{name}");
}
}
pub use crate::shared_tests::windows_text::lab;
#[test]
fn one_text_written_five_ways_by_powershell_reads_the_same() {
let ways: &[(&str, &str)] = &[
("ps_redirect.txt", "utf-16le"),
("ps_outfile_default.txt", "utf-16le"),
("ps_utf16le.txt", "utf-16le"),
("ps_utf16be.txt", "utf-16be"),
("ps_utf8_bom.txt", "utf-8"),
("ps_setcontent_default.txt", "windows-1252"),
];
let mut texts = std::collections::BTreeSet::new();
for (name, label) in ways {
for (image, bytes) in lab(name) {
let read = text(label, &bytes);
assert!(
read.starts_with("alpha line one\r\nbeta line two"),
"{image}/{name}: {read:?}"
);
assert!(read.ends_with("result=ok\r\n"), "{image}/{name}: {read:?}");
texts.insert(read);
}
}
assert!(texts.len() <= 1, "{texts:?}");
}
#[test]
fn a_real_utf16_json_file_reads_as_json() {
for (image, bytes) in lab("ps_service_utf16.json") {
let json = text("utf-16le", &bytes);
assert!(!json.contains('\u{FFFD}') && !json.starts_with('\u{FEFF}'));
let value: serde_json::Value = serde_json::from_str(&json).unwrap();
let rows = value.as_array().unwrap();
assert!(rows.iter().all(|r| r["Name"].is_string()), "{image}");
}
}
#[cfg(feature = "decode-base64")]
pub fn payloads(line: &[u8]) -> Vec<&[u8]> {
const FLAG: &[u8] = b"-EncodedCommand ";
let mut found = Vec::new();
let mut from = 0;
while let Some(at) = memchr::memmem::find(&line[from..], FLAG) {
let start = from + at + FLAG.len();
let len = line[start..]
.iter()
.take_while(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'='))
.count();
found.push(&line[start..start + len]);
from = start + len;
}
found
}
#[cfg(feature = "decode-base64")]
#[test]
fn real_encoded_commands_in_windows_events_decode_to_scripts() {
use crate::shared_tests::corpus::for_each_record_of;
let base64 = Decoder::new(Codec::Base64 {
url_safe: false,
skip_whitespace: false,
});
let utf16 = decoder("utf-16le");
let script_of = |payload: &[u8], at: &str| -> String {
let mut bytes = Vec::new();
base64
.decode(payload, &mut bytes)
.unwrap_or_else(|e| panic!("{at}: {e}"));
let script = String::from_utf8(read(&utf16, &bytes)).unwrap();
assert!(!script.contains('\u{FFFD}'), "{at}: {script:?}");
script
};
let (mut commands, mut nested) = (0, 0);
for_each_record_of(&["xml-lines"], |r| {
for payload in payloads(r.bytes) {
let script = script_of(payload, &r.at());
commands += 1;
for inner in payloads(script.as_bytes()) {
script_of(inner, &r.at());
nested += 1;
}
}
});
assert!(commands >= 2, "{commands} encoded commands");
assert!(nested >= 1, "{nested} commands holding a command");
}
#[cfg(all(feature = "decode-base64", feature = "parse-ndjson"))]
#[test]
fn a_chain_reads_base64_then_utf16_then_the_json() {
use std::sync::Arc;
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use crate::format;
use crate::parse::{ParsePlan, Parsers, Status};
let mut registry = Parsers::new();
format::register_stock(&mut registry).unwrap();
registry
.register(Arc::new(
Decoder::new(Codec::Text(Charset::UTF_16BE)).named("charset:utf-16be"),
))
.unwrap();
let json = r#"{"user":"kay","n":7}"#;
let le: Vec<u8> = json.encode_utf16().flat_map(u16::to_le_bytes).collect();
let with_mark: Vec<u8> = [b"\xFF\xFE".as_slice(), &le].concat();
let be: Vec<u8> = json.encode_utf16().flat_map(u16::to_be_bytes).collect();
let rows: &[(&str, &[u8], Status)] = &[
("utf16le", &le, Status::Parsed),
("utf16le", &with_mark, Status::Parsed),
("utf16be", &be, Status::Parsed),
("charset:utf-16be", &be, Status::Parsed),
("utf16be", &le, Status::Fallback),
];
for (decoder, bytes, status) in rows {
let chain = format!(r#"ndjson > field("payload"):base64 > {decoder} > ndjson"#);
let line = format!(r#"{{"payload":"{}"}}"#, STANDARD.encode(bytes));
let plan = ParsePlan::chain(&chain, ®istry).unwrap();
let mut out = Fields::new();
let outcome = plan.parse_stateless(line.as_bytes(), &mut out);
assert_eq!(outcome.status, *status, "{chain} {bytes:?}");
if *status == Status::Parsed {
assert_eq!(outcome.layers, 4, "{chain}");
let user = out.get("ndjson.user").map(|v| v.bytes.to_vec());
assert_eq!(user.as_deref(), Some(b"kay".as_slice()), "{chain}");
}
}
}
}
#[cfg(all(feature = "decode-text", feature = "decode-base64", feature = "scrub"))]
mod encoded_command {
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use super::super::{Codec, Decoder};
use super::text_rows::{lab, payloads};
use crate::charset::Charset;
use crate::scrub::{GITLEAKS, Kind, Report, RuleConfig, Scrubber};
const KEY: &str = "AKIALALEMEL33243OLIB";
const EXAMPLE_KEY: &str = "AKIAIOSFODNN7EXAMPLE";
fn command_line(units: &[u16]) -> String {
let bytes: Vec<u8> = units.iter().flat_map(|u| u.to_le_bytes()).collect();
format!(
"powershell.exe -NoProfile -EncodedCommand {}",
STANDARD.encode(bytes)
)
}
fn encode(script: &str) -> Vec<u16> {
script.encode_utf16().collect()
}
fn script_of(line: &str) -> Vec<u8> {
let payload = payloads(line.as_bytes())[0];
let mut bytes = Vec::new();
Decoder::new(Codec::Base64 {
url_safe: false,
skip_whitespace: false,
})
.decode(payload, &mut bytes)
.unwrap();
let mut text = Vec::new();
Decoder::new(Codec::Text(Charset::UTF_16LE))
.decode(&bytes, &mut text)
.unwrap();
text
}
fn scrub(text: &[u8]) -> (Option<String>, Report) {
let scrubber = Scrubber::new(&RuleConfig::from_toml(GITLEAKS).unwrap()).unwrap();
let mut scratch = scrubber.scratch();
let mut report = scrubber.report();
let out = scrubber
.scrub_text(text, &mut scratch, &mut report)
.map(|b| String::from_utf8(b).unwrap());
(out, report)
}
fn aws(report: &Report) -> u32 {
report.count("aws-access-token", Kind::Redacted)
}
#[test]
fn a_key_in_an_encoded_command_is_redacted_after_base64_and_utf16() {
let script = format!("$env:AWS_ACCESS_KEY_ID = '{KEY}'; aws s3 ls");
let line = command_line(&encode(&script));
let (_, report) = scrub(line.as_bytes());
assert_eq!(aws(&report), 0, "base64 hides the key from the rules");
let utf16 = STANDARD.decode(payloads(line.as_bytes())[0]).unwrap();
let (_, report) = scrub(&utf16);
assert_eq!(aws(&report), 0, "UTF-16 hides it too");
let text = script_of(&line);
assert_eq!(text, script.as_bytes());
let (out, report) = scrub(&text);
let out = out.expect("the decoded script is scrubbed");
assert_eq!(aws(&report), 1);
assert!(!out.contains(KEY) && out.contains("aws s3 ls"), "{out}");
}
#[test]
fn a_lone_surrogate_around_a_key_doesnt_hide_it() {
let mut units = vec![0xD800];
units.extend(encode(&format!("Write-Output '{KEY}'")));
units.push(0xDC00);
let line = command_line(&units);
let text = script_of(&line);
let read = String::from_utf8(text.clone()).unwrap();
assert!(
read.starts_with('\u{FFFD}') && read.ends_with('\u{FFFD}'),
"{read:?}"
);
let (out, report) = scrub(&text);
assert_eq!(aws(&report), 1, "{out:?}");
assert!(!out.unwrap().contains(KEY));
}
#[test]
fn a_real_encoded_command_from_a_lab_vm_scrubs_its_password() {
for (image, bytes) in lab("encoded_command.txt") {
let line = String::from_utf8(bytes).unwrap();
let text = script_of(line.trim());
let script = String::from_utf8(text.clone()).unwrap();
assert!(script.contains(EXAMPLE_KEY), "{image}: {script}");
let (out, report) = scrub(&text);
let out = out.unwrap_or_else(|| panic!("{image}: nothing redacted in {script}"));
assert!(!out.contains("Hunter2Example!"), "{image}: {out}");
assert_eq!(aws(&report), 0, "{image}: a documented example key stays");
assert!(out.contains(EXAMPLE_KEY), "{image}: {out}");
}
}
}
#[cfg(feature = "decode-rsyslog")]
mod rsyslog_rows {
use super::super::{Codec, Decoder, Escaped, stock};
use crate::parse::{ParseError, Parser};
use crate::shared_tests::corpus::for_each_record_of;
fn decoder(prefix: u8, escaped: Escaped) -> Decoder {
Decoder::new(Codec::Rsyslog { prefix, escaped })
}
fn decoded(prefix: u8, escaped: Escaped, input: &[u8]) -> Vec<u8> {
let mut out = b"kept".to_vec();
decoder(prefix, escaped).decode(input, &mut out).unwrap();
assert_eq!(&out[..4], b"kept");
out.split_off(4)
}
#[test]
fn the_stock_decoder_is_named_rsyslog_and_reads_the_hash_prefix() {
let stock = stock();
let d = stock.iter().find(|d| d.name() == "rsyslog").unwrap();
assert_eq!(
d.codec(),
Codec::Rsyslog {
prefix: b'#',
escaped: Escaped::Controls
}
);
assert!(crate::parse::valid_parser_name(d.name()));
assert!(d.decodes() && !d.detectable());
}
#[test]
fn each_escape_rsyslog_writes_reads_back_and_nothing_else_does() {
use Escaped::{Controls, ControlsAndHigh};
let rows: &[(u8, Escaped, &[u8], &[u8])] = &[
(b'#', Controls, b"a#011b", b"a\tb"),
(b'#', Controls, b"#012#015", b"\n\r"),
(b'#', Controls, b"x#000y", b"x\0y"),
(b'#', Controls, b"#033[0m", b"\x1b[0m"),
(b'#', Controls, b"#037#040", b"\x1f#040"),
(
b'#',
Controls,
b"#064 #177 #200 #377",
b"#064 #177 #200 #377",
),
(b'#', Controls, b"##011", b"#\t"),
(b'#', Controls, b"#01 #0 # #", b"#01 #0 # #"),
(
b'#',
Controls,
b"#018 #0a1 #-11 #400",
b"#018 #0a1 #-11 #400",
),
(b'#', Controls, b"end#01", b"end#01"),
(b'#', Controls, b"", b""),
(
b'#',
ControlsAndHigh,
b"#303#251 #200 #377 #177",
b"\xC3\xA9 \x80 \xFF #177",
),
(b'\\', Controls, b"a\\011b\\n#011", b"a\tb\\n#011"),
(b'0', Controls, b"0010 0011", b"\x08 \t"),
];
for (prefix, escaped, input, want) in rows {
assert_eq!(
decoded(*prefix, *escaped, input),
*want,
"{} {escaped:?} {:?}",
*prefix as char,
String::from_utf8_lossy(input)
);
}
}
#[test]
fn a_decode_stops_at_its_cap_and_leaves_out_alone() {
let input = b"#011".repeat(100);
let d = decoder(b'#', Escaped::Controls);
assert_eq!(decoded(b'#', Escaped::Controls, &input), vec![b'\t'; 100]);
let mut out = b"kept".to_vec();
d.clone()
.with_max_bytes(100)
.decode(&input, &mut out)
.unwrap();
assert_eq!(out.len(), 104);
let mut out = b"kept".to_vec();
let got = d.with_max_bytes(99).decode(&input, &mut out);
assert!(
matches!(
got,
Err(ParseError::Limit {
what: "decoded bytes"
})
),
"{got:?}"
);
assert_eq!(out, b"kept");
}
#[test]
fn real_relayed_lines_lose_their_escapes_and_a_second_pass_changes_nothing() {
let d = decoder(b'#', Escaped::Controls);
let (mut lines, mut escaped, mut tls_hello, mut line_feed) = (0, 0, 0, 0);
for_each_record_of(&["cef", "mixed"], |r| {
let mut once = Vec::new();
d.decode(r.bytes, &mut once).unwrap();
let mut twice = Vec::new();
d.decode(&once, &mut twice).unwrap();
assert_eq!(once, twice, "{}", r.at());
lines += 1;
if once != r.bytes {
escaped += 1;
assert!(once.len() < r.bytes.len(), "{}", r.at());
}
if memchr::memmem::find(&once, b"request=\x16\x03\x01 requestClient").is_some() {
tls_hello += 1;
}
if memchr::memmem::find(&once, b"\n DstMac=").is_some() {
line_feed += 1;
}
});
assert!(lines >= 100, "{lines} lines");
assert!(escaped >= 10, "{escaped} lines held an escape");
assert!(tls_hello >= 6, "{tls_hello} Barracuda lines");
assert!(line_feed >= 4, "{line_feed} Radiflow lines");
}
#[cfg(all(feature = "parse-syslog", feature = "parse-kv"))]
#[test]
fn a_chain_reads_real_relayed_lines_with_their_bytes_back() {
use crate::format;
use crate::parse::{Fields, ParsePlan, Parsers};
let mut registry = Parsers::new();
format::register_stock(&mut registry).unwrap();
let as_written = ParsePlan::chain("syslog_nopri > kv", ®istry).unwrap();
let unescaped = ParsePlan::chain("syslog_nopri > rsyslog > kv", ®istry).unwrap();
let (mut hello, mut line_feed) = (0, 0);
for_each_record_of(&["cef", "mixed"], |r| {
let escaped = r.bytes.windows(4).any(|w| {
w[0] == b'#'
&& w[1] == b'0'
&& (b'0'..=b'3').contains(&w[2])
&& (b'0'..=b'7').contains(&w[3])
});
if !escaped {
return;
}
let (mut before, mut after) = (Fields::new(), Fields::new());
let kept = as_written.parse_stateless(r.bytes, &mut before);
let read = unescaped.parse_stateless(r.bytes, &mut after);
assert_eq!(
(read.status, read.layers),
(kept.status, kept.layers + 1),
"{}: {:?}",
r.at(),
read.error
);
let value =
|fields: &Fields<'_>, name: &str| fields.get(name).map(|v| v.bytes.to_vec());
if value(&before, "kv.request").as_deref() == Some(b"#026#003#001".as_slice()) {
assert_eq!(
value(&after, "kv.request").as_deref(),
Some(b"\x16\x03\x01".as_slice())
);
hello += 1;
}
let mac = value(&before, "kv.SrcMac").unwrap_or_default();
if let Some(clean) = mac.strip_suffix(b"#012") {
assert_eq!(
value(&after, "kv.SrcMac").as_deref(),
Some(clean),
"{}",
r.at()
);
line_feed += 1;
}
});
assert!(hello >= 6, "{hello} Barracuda lines");
assert!(line_feed >= 4, "{line_feed} Radiflow lines");
}
}