grippo 0.1.3

Parse, match and scrub data at scale.
Documentation
// Project:   grippo
// File:      src/format/cef.rs
// Purpose:   The Common Event Format parser
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! `CEF:Version|Vendor|Product|DeviceVersion|SignatureID|Name|Severity|Extension`.
//!
//! The header's seven fields split on unescaped `|`, with `\|` and `\\`
//! escaped. The extension is `key=value` pairs, and a value runs to the space
//! before the next unescaped `key=`, so it may hold spaces. `\=`, `\\`, `\n`
//! and `\r` are escaped in a value.

use std::borrow::Cow;
use std::ops::Range;

use crate::parse::{FieldSink, FieldValue, Hint, ParseError, Parsed, Parser};
use crate::path::key_part;
use crate::strmatch::Signature;
use crate::tier::MatcherTier;

/// The header field names, in order.
pub const HEADER: [&str; 7] = [
    "version",
    "device_vendor",
    "device_product",
    "device_version",
    "signature_id",
    "name",
    "severity",
];

/// The CEF parser, registered as `cef`.
#[derive(Debug, Clone)]
pub struct Cef {
    signature: Signature,
}

impl Default for Cef {
    fn default() -> Self {
        Self::new()
    }
}

impl Cef {
    /// A CEF parser.
    ///
    /// # Panics
    ///
    /// Never: the signature's literal is fixed and non-empty.
    #[must_use]
    pub fn new() -> Self {
        let signature = Signature::builder()
            .anchored(["CEF:"])
            .verify(|span, _| header_ends(span).is_some())
            .build()
            .unwrap_or_else(|_| unreachable!("invariant: `CEF:` is a non-empty literal"));
        Self { signature }
    }
}

/// The end of each header field, the seventh being the start of the extension
/// less one. `None` with fewer than seven unescaped `|`.
fn header_ends(span: &[u8]) -> Option<[usize; 7]> {
    let mut ends = [0; 7];
    let mut n = 0;
    let mut i = 4;
    while n < 7 {
        match span.get(i)? {
            b'\\' => i += 2,
            b'|' => {
                ends[n] = i;
                n += 1;
                i += 1;
            }
            _ => i += 1,
        }
    }
    Some(ends)
}

/// `bytes` with `\x` for each `x` in `escaped` unescaped, borrowed when it
/// holds no backslash.
fn unescape(bytes: &[u8], map: fn(u8) -> Option<u8>) -> FieldValue<'_> {
    if !bytes.contains(&b'\\') {
        return FieldValue::borrowed(bytes, Hint::Text);
    }
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'\\'
            && let Some(&next) = bytes.get(i + 1)
            && let Some(plain) = map(next)
        {
            out.push(plain);
            i += 2;
            continue;
        }
        out.push(bytes[i]);
        i += 1;
    }
    FieldValue {
        bytes: Cow::Owned(out),
        hint: Hint::Text,
    }
}

const fn header_escape(b: u8) -> Option<u8> {
    match b {
        b'|' | b'\\' => Some(b),
        _ => None,
    }
}

const fn value_escape(b: u8) -> Option<u8> {
    match b {
        b'=' | b'\\' => Some(b),
        b'n' => Some(b'\n'),
        b'r' => Some(b'\r'),
        _ => None,
    }
}

const fn key_byte(b: u8) -> bool {
    b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-' | b'[' | b']')
}

/// The next `key=` at or after `from`: the key's start and the `=`.
fn next_key(ext: &[u8], mut from: usize) -> Option<(usize, usize)> {
    while from < ext.len() {
        match ext[from] {
            b'\\' => from += 2,
            b'=' => {
                let start = ext[..from]
                    .iter()
                    .rposition(|&b| !key_byte(b))
                    .map_or(0, |p| p + 1);
                if start < from && (start == 0 || ext[start - 1] == b' ') {
                    return Some((start, from));
                }
                from += 1;
            }
            _ => from += 1,
        }
    }
    None
}

impl Parser for Cef {
    fn name(&self) -> &'static str {
        "cef"
    }

    fn tier(&self) -> MatcherTier {
        MatcherTier::Field
    }

    fn signature(&self) -> &Signature {
        &self.signature
    }

    /// A header field escapes `\` and `|`, an extension value `\`, `=`, and
    /// line ends as `\n` and `\r`. An extension value ending in other
    /// whitespace is refused, since the reader trims it.
    fn escape_value(
        &self,
        _input: &[u8],
        field: usize,
        at: Range<usize>,
        value: &[u8],
        out: &mut Vec<u8>,
    ) -> Option<Range<usize>> {
        let header = field < HEADER.len();
        if !header
            && value
                .last()
                .is_some_and(|&b| b.is_ascii_whitespace() && !matches!(b, b'\n' | b'\r'))
        {
            return None;
        }
        for &b in value {
            let escaped: &[u8] = match b {
                b'\\' => b"\\\\",
                b'|' if header => b"\\|",
                b'=' if !header => b"\\=",
                b'\n' if !header => b"\\n",
                b'\r' if !header => b"\\r",
                _ => {
                    out.push(b);
                    continue;
                }
            };
            out.extend_from_slice(escaped);
        }
        Some(at)
    }

    fn parse<'a>(
        &self,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
    ) -> Result<Parsed, ParseError> {
        if !input.starts_with(b"CEF:") {
            return Ok(Parsed::NoMatch);
        }
        let Some(ends) = header_ends(input) else {
            return Ok(Parsed::NoMatch);
        };
        let mut start = 4;
        for (name, end) in HEADER.iter().zip(ends) {
            out.field(name, unescape(&input[start..end], header_escape));
            start = end + 1;
        }
        let tail = input.len()
            - input
                .iter()
                .rev()
                .take_while(|b| b.is_ascii_whitespace())
                .count();
        let ext = &input[start.min(tail)..tail];
        let mut key = next_key(ext, 0);
        while let Some((k, eq)) = key {
            let next = next_key(ext, eq + 1);
            let end = next.map_or(ext.len(), |(n, _)| n.saturating_sub(1));
            let value = &ext[(eq + 1).min(end)..end];
            let value =
                &value[..value.len() - value.iter().rev().take_while(|&&b| b == b' ').count()];
            let name = std::str::from_utf8(&ext[k..eq]).unwrap_or_default();
            out.field(
                &key_part(Cow::Borrowed(name)),
                unescape(value, value_escape),
            );
            key = next;
        }
        Ok(Parsed::Done)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parse::Fields;

    fn parse(line: &str) -> (Parsed, Vec<(String, String)>) {
        let mut out = Fields::new();
        let p = Cef::new().parse(line.as_bytes(), &mut out).unwrap();
        let fields = out
            .as_slice()
            .iter()
            .map(|(n, v)| (n.clone(), String::from_utf8_lossy(&v.bytes).into_owned()))
            .collect();
        (p, fields)
    }

    fn get<'f>(fields: &'f [(String, String)], name: &str) -> &'f str {
        &fields.iter().find(|(n, _)| n == name).unwrap().1
    }

    #[test]
    fn a_dotted_extension_key_is_written_quoted_and_reads_back_whole() {
        for (name, value) in [(r#"["a.b"]"#, "1"), ("c", "2")] {
            let mut out = Fields::new();
            Cef::new()
                .parse(b"CEF:0|a|b|1|2|n|3|a.b=1 c=2", &mut out)
                .unwrap();
            let got = out
                .get(name)
                .map(|v| String::from_utf8_lossy(&v.bytes).into_owned());
            assert_eq!(got.as_deref(), Some(value), "{name}");
            #[cfg(feature = "record")]
            {
                use crate::record::Record;
                let keys: Vec<_> = crate::path::keys(name).collect();
                let at = (&out).find(&keys[..]).unwrap();
                assert_eq!((&out).text(at).unwrap(), value, "{name}");
            }
        }
    }

    #[test]
    fn a_full_record_reads_header_and_extension() {
        let (p, f) = parse(
            "CEF:0|Security|threatmanager|1.0|100|worm successfully stopped|10|src=10.0.0.1 dst=2.1.2.2 spt=1232\n",
        );
        assert_eq!(p, Parsed::Done);
        assert_eq!(get(&f, "device_vendor"), "Security");
        assert_eq!(get(&f, "name"), "worm successfully stopped");
        assert_eq!(get(&f, "severity"), "10");
        assert_eq!(get(&f, "src"), "10.0.0.1");
        assert_eq!(get(&f, "spt"), "1232");
        assert_eq!(f.len(), 10);
    }

    #[test]
    fn escapes_and_spaces_follow_the_spec() {
        let (_, f) = parse(
            r"CEF:0|ven\|dor|prod|1|id|na\\me|5|msg=hello world  act=a\=b c\\d cs1Label=x\ny",
        );
        assert_eq!(get(&f, "device_vendor"), "ven|dor");
        assert_eq!(get(&f, "name"), r"na\me");
        assert_eq!(get(&f, "msg"), "hello world");
        assert_eq!(get(&f, "act"), r"a=b c\d");
        assert_eq!(get(&f, "cs1Label"), "x\ny");
    }

    #[test]
    fn an_equals_inside_a_word_is_not_a_key() {
        let (_, f) = parse("CEF:0|v|p|1|id|n|5|request=http://x/?a=b c=d");
        assert_eq!(get(&f, "request"), "http://x/?a=b");
        assert_eq!(get(&f, "c"), "d");
    }

    #[test]
    fn a_short_header_is_no_match_and_writes_nothing() {
        let (p, f) = parse("CEF:0|v|p|1");
        assert_eq!(p, Parsed::NoMatch);
        assert_eq!(f, Vec::<(String, String)>::new());
        assert!(!Cef::new().signature().may_match(b"CEF:0|v|p|1"));
        assert!(Cef::new().signature().may_match(b"CEF:0|v|p|1|i|n|5|"));
    }

    #[test]
    fn an_empty_extension_is_a_record() {
        let (p, f) = parse("CEF:1|v|p|1|id|n|Low|");
        assert_eq!(p, Parsed::Done);
        assert_eq!(f.len(), 7);
        assert_eq!(get(&f, "severity"), "Low");
    }

    /// `value` escaped as field `field`, `None` when refused.
    fn escaped(field: usize, value: &str) -> Option<String> {
        let mut out = Vec::new();
        let span = Cef::new().escape_value(b"", field, 0..0, value.as_bytes(), &mut out);
        span.map(|_| String::from_utf8(out).unwrap())
    }

    #[test]
    fn values_escape_as_header_or_extension() {
        let cases: &[(usize, &str, Option<&str>)] = &[
            (5, r"a|b\c=d", Some(r"a\|b\\c=d")),
            (5, "line\nend ", Some("line\nend ")),
            (7, r"a|b\c=d", Some(r"a|b\\c\=d")),
            (7, "x\r\ny", Some(r"x\r\ny")),
            (7, "ends in a space ", None),
            (7, "ends in a tab\t", None),
            (7, "ends in a line end\n", Some(r"ends in a line end\n")),
            (7, "", Some("")),
        ];
        for &(field, value, want) in cases {
            assert_eq!(escaped(field, value).as_deref(), want, "{field} {value:?}");
        }
    }

    proptest::proptest! {
        /// An escaped header field and extension value read back as written.
        #[test]
        fn an_escaped_value_reads_back(
            name in r"[a-z|\\= \n\r]{0,12}",
            value in r"[a-z|\\= \n\r]{0,12}[a-z|\\=\n\r]",
        ) {
            let line = format!(
                "CEF:0|v|p|1|id|{}|5|k={} z=1",
                escaped(5, &name).unwrap(),
                escaped(7, &value).unwrap(),
            );
            let (p, f) = parse(&line);
            proptest::prop_assert_eq!(p, Parsed::Done);
            proptest::prop_assert_eq!(get(&f, "name"), name.as_str());
            proptest::prop_assert_eq!(get(&f, "k"), value.as_str());
            proptest::prop_assert_eq!(get(&f, "z"), "1");
        }
    }
}