grippo 0.1.0

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 crate::parse::{FieldSink, FieldValue, Hint, ParseError, Parsed, Parser};
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
    }

    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(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_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");
    }
}