Skip to main content

goliath_normalize/
normalizer.rs

1//! Source definitions compiled for use, and records through them.
2
3use std::collections::BTreeMap;
4
5use goliath_ocsf::schema::{self, Base};
6use goliath_rule::FieldPath;
7use serde::{Deserialize, Deserializer, Serialize, Serializer};
8use serde_json::{Map, Value};
9
10use crate::definition::{Coercion, Decoding, FieldSpec, Framing, SourceDefinition};
11use crate::error::DefinitionError;
12use crate::{auditd, csv, syslog};
13
14/// A source definition, checked and compiled.
15///
16/// Built once, then used for every record of the source. Normalizing is
17/// deterministic: the same bytes under the same definition version always give
18/// the same outcome.
19#[derive(Debug, Clone)]
20pub struct Normalizer {
21    name: String,
22    version: u32,
23    framing: Framing,
24    decoding: Decoding,
25    columns: Vec<String>,
26    kinds: Vec<Kind>,
27    nil: Vec<Value>,
28    unwrap: Option<String>,
29    data_components: Vec<String>,
30}
31
32#[derive(Debug, Clone)]
33struct Kind {
34    name: String,
35    when: Vec<(SourcePath, Value)>,
36    /// `class_uid`, `category_uid`, `type_uid`, and `activity_id`.
37    class: Vec<(&'static str, Value)>,
38    /// The common fields, then the kind's own.
39    fields: Vec<Field>,
40    unmapped: Vec<SourcePath>,
41}
42
43#[derive(Debug, Clone)]
44struct Field {
45    target: FieldPath,
46    source: Source,
47}
48
49#[derive(Debug, Clone)]
50enum Source {
51    Constant(Value),
52    Path {
53        path: SourcePath,
54        coercion: Option<Coercion>,
55    },
56    Translate {
57        path: SourcePath,
58        map: BTreeMap<String, Value>,
59        otherwise: Option<Value>,
60    },
61}
62
63/// A dotted path into a decoded record. Unlike an OCSF path, it names exactly
64/// one value: records are read, not searched.
65///
66/// A member whose own name holds dots, as Falco's `proc.cmdline` does, is
67/// named by writing it out: `output_fields.proc.cmdline`. At each object a
68/// member named by the next segment alone is tried first, then by the next
69/// two joined with a dot, and so on.
70///
71/// In an array, a segment that is a number names the element at that index,
72/// counted from 0: `target.1.displayName` is the name of the second target.
73#[derive(Debug, Clone, PartialEq, Eq)]
74struct SourcePath {
75    text: String,
76    segments: Vec<String>,
77}
78
79impl SourcePath {
80    fn parse(text: &str) -> Option<Self> {
81        let segments: Vec<String> = text.split('.').map(str::to_owned).collect();
82        segments
83            .iter()
84            .all(|segment| !segment.is_empty())
85            .then(|| Self {
86                text: text.to_owned(),
87                segments,
88            })
89    }
90
91    fn lookup<'a>(&self, record: &'a Value) -> Option<&'a Value> {
92        find(record, &self.segments)
93    }
94
95    /// The name, within the object at `object`, of the member this path
96    /// names, if it is one.
97    fn member_of(&self, object: &Self) -> Option<String> {
98        (self.segments.len() > object.segments.len() && self.segments.starts_with(&object.segments))
99            .then(|| self.segments[object.segments.len()..].join("."))
100    }
101
102    /// Whether this path names the member `key` of the object at `object`.
103    fn is_member(&self, object: &Self, key: &str) -> bool {
104        self.member_of(object).is_some_and(|member| member == key)
105    }
106}
107
108fn find<'a>(value: &'a Value, segments: &[String]) -> Option<&'a Value> {
109    if segments.is_empty() {
110        return Some(value);
111    }
112    if let Some(items) = value.as_array() {
113        let index: usize = segments[0].parse().ok()?;
114        return find(items.get(index)?, &segments[1..]);
115    }
116    let object = value.as_object()?;
117    let mut name = String::new();
118    for (index, segment) in segments.iter().enumerate() {
119        if index > 0 {
120            name.push('.');
121        }
122        name.push_str(segment);
123        if let Some(found) = object
124            .get(&name)
125            .and_then(|member| find(member, &segments[index + 1..]))
126        {
127            return Some(found);
128        }
129    }
130    None
131}
132
133/// What became of one record.
134#[non_exhaustive]
135#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
136#[serde(rename_all = "snake_case")]
137pub enum Outcome {
138    /// The record became an OCSF event.
139    Event(Normalized),
140    /// The record could not become an event, and is kept whole.
141    DeadLetter(DeadLetter),
142}
143
144/// An OCSF event, and anything that did not convert on the way.
145#[non_exhaustive]
146#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
147pub struct Normalized {
148    /// Identifies the record the event came from, so that storage can drop
149    /// a record delivered twice.
150    pub id: EventId,
151    /// The event.
152    pub event: Value,
153    /// The kind of record it was.
154    pub kind: String,
155    /// Values that did not convert. Each is kept as written under
156    /// `unmapped`, and the event is still produced, so that a malformed field
157    /// cannot keep an event away from detection.
158    pub issues: Vec<Issue>,
159}
160
161impl Normalized {
162    /// An event made by the platform itself, such as a finding, with the
163    /// identity `id` and no issues.
164    pub fn new(id: EventId, event: Value, kind: impl Into<String>) -> Self {
165        Self {
166            id,
167            event,
168            kind: kind.into(),
169            issues: Vec::new(),
170        }
171    }
172}
173
174/// The identity of a record: 128 bits of the BLAKE3 hash of the source's
175/// name and the record's raw bytes.
176///
177/// It depends on nothing else, so a record delivered again, or collected
178/// again, gets the same identity and can be dropped as a duplicate. Two
179/// records with identical bytes from one source are the same record.
180///
181/// The hash is cryptographic on purpose. Whoever writes the logs chooses the
182/// bytes, and with a hash built only for speed they could craft a record
183/// whose identity equals that of another, and have storage drop one of the
184/// two as a duplicate.
185#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
186pub struct EventId([u8; 16]);
187
188impl EventId {
189    /// Keys the hash, so that identities cannot be confused with any other
190    /// use of BLAKE3. Changing it changes every identity.
191    const CONTEXT: &str = "goliath 2026-09-25 event id";
192
193    /// The identity of the record `raw` from the source `source`.
194    pub fn of(source: &str, raw: &[u8]) -> Self {
195        let mut hasher = blake3::Hasher::new_derive_key(Self::CONTEXT);
196        // The name's length first, so that no name and record pair can end
197        // where another pair's name does.
198        hasher.update(&(source.len() as u64).to_le_bytes());
199        hasher.update(source.as_bytes());
200        hasher.update(raw);
201        let mut id = [0; 16];
202        hasher.finalize_xof().fill(&mut id);
203        Self(id)
204    }
205
206    /// The identity's bytes.
207    pub fn as_bytes(&self) -> &[u8; 16] {
208        &self.0
209    }
210}
211
212impl std::fmt::Display for EventId {
213    /// Lowercase hexadecimal.
214    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
215        self.0.iter().try_for_each(|byte| write!(f, "{byte:02x}"))
216    }
217}
218
219impl std::str::FromStr for EventId {
220    type Err = String;
221
222    /// Parses the lowercase or uppercase hexadecimal [`Display`] writes.
223    ///
224    /// [`Display`]: std::fmt::Display
225    fn from_str(text: &str) -> Result<Self, Self::Err> {
226        let invalid = || format!("`{text}` is not 32 hexadecimal digits");
227        if text.len() != 32 {
228            return Err(invalid());
229        }
230        let mut id = [0; 16];
231        let (pairs, _) = text.as_bytes().as_chunks::<2>();
232        for (byte, pair) in id.iter_mut().zip(pairs) {
233            let pair = std::str::from_utf8(pair).map_err(|_| invalid())?;
234            *byte = u8::from_str_radix(pair, 16).map_err(|_| invalid())?;
235        }
236        Ok(Self(id))
237    }
238}
239
240/// As its hexadecimal text, so that it reads the same in JSON as in logs.
241impl Serialize for EventId {
242    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
243        serializer.collect_str(self)
244    }
245}
246
247impl<'de> Deserialize<'de> for EventId {
248    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
249        let text = String::deserialize(deserializer)?;
250        text.parse().map_err(serde::de::Error::custom)
251    }
252}
253
254impl std::fmt::Debug for EventId {
255    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
256        write!(f, "EventId({self})")
257    }
258}
259
260/// A value that did not convert.
261#[non_exhaustive]
262#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
263pub struct Issue {
264    /// The OCSF attribute it was meant for.
265    pub target: String,
266    /// Where it was read from.
267    pub source: String,
268    /// Why it did not convert.
269    pub reason: String,
270}
271
272/// A record that could not become an event.
273///
274/// The raw bytes are kept exactly, so the record can be processed again once
275/// the source definition is fixed. Nothing a source sends is dropped.
276#[non_exhaustive]
277#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
278pub struct DeadLetter {
279    /// The stage that failed.
280    pub stage: Stage,
281    /// Why.
282    pub error: String,
283    /// The record as received; for a stream that could not be framed, the
284    /// rest of the stream.
285    pub raw: Vec<u8>,
286}
287
288/// A stage of normalization, in order.
289#[non_exhaustive]
290#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
291#[serde(rename_all = "snake_case")]
292pub enum Stage {
293    /// Splitting the stream into records.
294    Framing,
295    /// Turning a record into a field map.
296    Decoding,
297    /// Choosing a kind and writing the OCSF event.
298    Mapping,
299}
300
301impl Stage {
302    /// The stage's name, as reports and metrics use it.
303    pub fn as_str(self) -> &'static str {
304        match self {
305            Self::Framing => "framing",
306            Self::Decoding => "decoding",
307            Self::Mapping => "mapping",
308        }
309    }
310}
311
312impl Normalizer {
313    /// Loads a source definition from YAML, as untrusted input.
314    ///
315    /// # Errors
316    ///
317    /// Returns [`DefinitionError`] if the YAML is not a valid definition.
318    pub fn from_yaml(text: &str) -> Result<Self, DefinitionError> {
319        let definition: SourceDefinition = goliath_sigma::yaml::from_str(text)?;
320        Self::new(&definition)
321    }
322
323    /// Checks and compiles a source definition.
324    ///
325    /// # Errors
326    ///
327    /// Returns [`DefinitionError`] if a path does not parse, two fields
328    /// would write over each other, a field writes an attribute that is set
329    /// otherwise, or a kind would accept every record; and if a class,
330    /// activity, or target is not in the OCSF schema, or a field writes a
331    /// value its attribute cannot hold.
332    pub fn new(definition: &SourceDefinition) -> Result<Self, DefinitionError> {
333        if definition.kinds.is_empty() {
334            return Err(DefinitionError::NoKinds);
335        }
336        let common = compile_fields("common", &definition.common)?;
337        let mut kinds = Vec::with_capacity(definition.kinds.len());
338        for kind in &definition.kinds {
339            if kind.when.is_empty() {
340                return Err(DefinitionError::Unconditional {
341                    kind: kind.name.clone(),
342                });
343            }
344            let when = kind
345                .when
346                .iter()
347                .map(|(path, value)| Ok((source_path(&kind.name, path)?, Value::from(value))))
348                .collect::<Result<_, DefinitionError>>()?;
349            let mut fields = common.clone();
350            fields.extend(compile_fields(&kind.name, &kind.fields)?);
351            check_overlaps(&kind.name, &fields)?;
352            check_schema(
353                &kind.name,
354                kind.class.class_uid,
355                kind.class.activity_id,
356                &fields,
357            )?;
358            let unmapped = kind
359                .unmapped
360                .iter()
361                .map(|path| {
362                    // `.` is the record itself, for sources that write every
363                    // field at its top level.
364                    if path == "." {
365                        Ok(SourcePath {
366                            text: path.clone(),
367                            segments: Vec::new(),
368                        })
369                    } else {
370                        source_path(&kind.name, path)
371                    }
372                })
373                .collect::<Result<_, _>>()?;
374
375            let class_uid = kind.class.class_uid;
376            let activity_id = kind.class.activity_id;
377            let category_uid = goliath_ocsf::Event::derive_category_uid(class_uid);
378            let type_uid = goliath_ocsf::Event::derive_type_uid(class_uid, activity_id);
379            kinds.push(Kind {
380                name: kind.name.clone(),
381                when,
382                class: vec![
383                    ("class_uid", Value::from(class_uid)),
384                    ("category_uid", Value::from(category_uid)),
385                    ("type_uid", Value::from(type_uid)),
386                    ("activity_id", Value::from(activity_id)),
387                ],
388                fields,
389                unmapped,
390            });
391        }
392        if (definition.decoding == Decoding::Csv) == definition.columns.is_empty() {
393            return Err(DefinitionError::Columns);
394        }
395        let fits = match definition.framing {
396            Framing::Lines => true,
397            Framing::JsonValues => definition.decoding == Decoding::Json,
398            Framing::AuditEvents => definition.decoding == Decoding::Auditd,
399            Framing::Syslog => {
400                matches!(definition.decoding, Decoding::Syslog | Decoding::SyslogJson)
401            }
402        };
403        if !fits {
404            return Err(DefinitionError::Decoding {
405                framing: match definition.framing {
406                    Framing::Lines => "lines",
407                    Framing::JsonValues => "json-values",
408                    Framing::AuditEvents => "audit-events",
409                    Framing::Syslog => "syslog",
410                },
411                decoding: match definition.decoding {
412                    Decoding::Json => "json",
413                    Decoding::Auditd => "auditd",
414                    Decoding::Syslog => "syslog",
415                    Decoding::SyslogJson => "syslog-json",
416                    Decoding::Csv => "csv",
417                },
418            });
419        }
420        Ok(Self {
421            name: definition.name.clone(),
422            version: definition.version,
423            framing: definition.framing,
424            decoding: definition.decoding,
425            columns: definition.columns.clone(),
426            kinds,
427            nil: definition
428                .nil
429                .iter()
430                .map(|text| Value::from(text.as_str()))
431                .collect(),
432            unwrap: definition.unwrap.clone(),
433            data_components: definition.data_components.clone(),
434        })
435    }
436
437    /// The source's name.
438    pub fn name(&self) -> &str {
439        &self.name
440    }
441
442    /// The ATT&CK data components the definition says its records supply,
443    /// such as `Process Creation`.
444    pub fn data_components(&self) -> &[String] {
445        &self.data_components
446    }
447
448    /// How the source's bytes split into records.
449    pub fn framing(&self) -> Framing {
450        self.framing
451    }
452
453    /// The definition's version, to be stored with every event it produces.
454    pub fn version(&self) -> u32 {
455        self.version
456    }
457
458    /// Splits `bytes` into records and normalizes each, calling `out` with
459    /// every outcome in order.
460    pub fn normalize(&self, bytes: &[u8], mut out: impl FnMut(Outcome)) {
461        match self.framing {
462            Framing::Lines => {
463                for line in bytes.split(|&byte| byte == b'\n') {
464                    let line = line.strip_suffix(b"\r").unwrap_or(line);
465                    if line.iter().all(u8::is_ascii_whitespace) {
466                        continue;
467                    }
468                    self.decoded(line, &mut out);
469                }
470            }
471            Framing::AuditEvents => {
472                for event in auditd::events(bytes) {
473                    match event {
474                        Ok(raw) => self.decoded(&raw, &mut out),
475                        Err(line) => out(dead(
476                            Stage::Framing,
477                            "the line names no audit event".to_owned(),
478                            line,
479                        )),
480                    }
481                }
482            }
483            Framing::Syslog => {
484                for message in syslog::messages(bytes) {
485                    match message {
486                        Ok(raw) => self.decoded(raw, &mut out),
487                        Err(rest) => out(dead(
488                            Stage::Framing,
489                            "the message is shorter than its octet count".to_owned(),
490                            rest,
491                        )),
492                    }
493                }
494            }
495            Framing::JsonValues => {
496                let mut stream = serde_json::Deserializer::from_slice(bytes).into_iter::<Value>();
497                let mut start = 0;
498                while let Some(next) = stream.next() {
499                    match next {
500                        Ok(record) => {
501                            let end = stream.byte_offset();
502                            self.records(&record, trim(&bytes[start..end]), &mut out);
503                            start = end;
504                        }
505                        Err(error) => {
506                            // Where one value ends cannot be known once the
507                            // stream is broken, so the rest is kept together.
508                            out(dead(
509                                Stage::Framing,
510                                error.to_string(),
511                                trim(&bytes[start..]),
512                            ));
513                            return;
514                        }
515                    }
516                }
517            }
518        }
519    }
520
521    /// Decodes and normalizes one framed record.
522    fn decoded(&self, raw: &[u8], out: &mut impl FnMut(Outcome)) {
523        let record = match self.decoding {
524            Decoding::Json => {
525                serde_json::from_slice::<Value>(raw).map_err(|error| error.to_string())
526            }
527            Decoding::Auditd => auditd::decode(raw),
528            Decoding::Syslog => syslog::decode(raw, syslog::Message::Text, jiff::Timestamp::now),
529            Decoding::SyslogJson => {
530                syslog::decode(raw, syslog::Message::Json, jiff::Timestamp::now)
531            }
532            Decoding::Csv => match csv::decode(raw, &self.columns) {
533                Ok(Some(record)) => Ok(record),
534                // The header of a file.
535                Ok(None) => return,
536                Err(error) => Err(error),
537            },
538        };
539        match record {
540            Ok(record) => self.records(&record, raw, out),
541            Err(error) => out(dead(Stage::Decoding, error, raw)),
542        }
543    }
544
545    /// Normalizes a decoded record, or each record of a batch the
546    /// definition unwraps.
547    fn records(&self, record: &Value, raw: &[u8], out: &mut impl FnMut(Outcome)) {
548        let batch = self.unwrap.as_ref().and_then(|member| {
549            if member == "." {
550                return record.as_array();
551            }
552            let object = record.as_object().filter(|object| object.len() == 1)?;
553            object.get(member)?.as_array()
554        });
555        match batch {
556            Some(items) => {
557                for item in items {
558                    let bytes = serde_json::to_vec(item).unwrap_or_default();
559                    out(self.record(item, &bytes));
560                }
561            }
562            None => out(self.record(record, raw)),
563        }
564    }
565
566    /// Normalizes one decoded record, whose raw bytes are `raw`.
567    fn record(&self, record: &Value, raw: &[u8]) -> Outcome {
568        if !record.is_object() {
569            return dead(
570                Stage::Decoding,
571                "the record is not a JSON object".to_owned(),
572                raw,
573            );
574        }
575        let Some(kind) = self.kinds.iter().find(|kind| {
576            kind.when
577                .iter()
578                .all(|(path, expected)| path.lookup(record) == Some(expected))
579        }) else {
580            return dead(
581                Stage::Mapping,
582                format!("no kind of source `{}` accepts the record", self.name),
583                raw,
584            );
585        };
586
587        let mut event = Map::new();
588        let mut unmapped = Map::new();
589        let mut issues = Vec::new();
590        let mut consumed: Vec<&SourcePath> = Vec::new();
591        for (name, value) in &kind.class {
592            event.insert((*name).to_owned(), value.clone());
593        }
594        for field in &kind.fields {
595            let path = match &field.source {
596                Source::Constant(value) => {
597                    set(&mut event, field.target.segments(), value.clone());
598                    continue;
599                }
600                Source::Path { path, .. } | Source::Translate { path, .. } => path,
601            };
602            let Some(found) = path
603                .lookup(record)
604                .filter(|value| !value.is_null() && !self.nil.contains(value))
605            else {
606                continue;
607            };
608            if !field.source.keeps_source() {
609                consumed.push(path);
610            }
611            match field.source.convert(found) {
612                Ok(value) => set(&mut event, field.target.segments(), value),
613                Err(reason) => {
614                    issues.push(Issue {
615                        target: field.target.as_str().to_owned(),
616                        source: path.text.clone(),
617                        reason,
618                    });
619                    // Kept by the name the `unmapped` lists would give it, or
620                    // by its whole path where they give none, so that it
621                    // cannot take another member's name.
622                    let name = kind
623                        .unmapped
624                        .iter()
625                        .find_map(|object| path.member_of(object))
626                        .unwrap_or_else(|| path.text.clone());
627                    unmapped.insert(name, found.clone());
628                }
629            }
630        }
631        for object in &kind.unmapped {
632            let Some(Value::Object(members)) = object.lookup(record) else {
633                continue;
634            };
635            for (key, member) in members {
636                if member.is_null() || consumed.iter().any(|path| path.is_member(object, key)) {
637                    continue;
638                }
639                // A name an earlier object already gave is qualified with
640                // this object's path, so that neither value is lost.
641                let name = if unmapped.contains_key(key) {
642                    format!("{}.{key}", object.text)
643                } else {
644                    key.clone()
645                };
646                unmapped.entry(name).or_insert_with(|| member.clone());
647            }
648        }
649        if !unmapped.is_empty() {
650            event.insert("unmapped".to_owned(), Value::Object(unmapped));
651        }
652        Outcome::Event(Normalized {
653            id: EventId::of(&self.name, raw),
654            event: Value::Object(event),
655            kind: kind.name.clone(),
656            issues,
657        })
658    }
659}
660
661fn dead(stage: Stage, error: String, raw: &[u8]) -> Outcome {
662    Outcome::DeadLetter(DeadLetter {
663        stage,
664        error,
665        raw: raw.to_vec(),
666    })
667}
668
669fn trim(bytes: &[u8]) -> &[u8] {
670    let start = bytes
671        .iter()
672        .position(|byte| !byte.is_ascii_whitespace())
673        .unwrap_or(bytes.len());
674    let end = bytes
675        .iter()
676        .rposition(|byte| !byte.is_ascii_whitespace())
677        .map_or(start, |position| position + 1);
678    &bytes[start..end]
679}
680
681fn source_path(kind: &str, text: &str) -> Result<SourcePath, DefinitionError> {
682    SourcePath::parse(text).ok_or_else(|| DefinitionError::SourcePath {
683        kind: kind.to_owned(),
684        path: text.to_owned(),
685    })
686}
687
688fn compile_fields(
689    kind: &str,
690    specs: &std::collections::BTreeMap<String, FieldSpec>,
691) -> Result<Vec<Field>, DefinitionError> {
692    specs
693        .iter()
694        .map(|(target, spec)| {
695            let path = FieldPath::parse(target).map_err(|source| DefinitionError::Target {
696                kind: kind.to_owned(),
697                target: target.clone(),
698                source,
699            })?;
700            let reserved = match path.segments()[0].as_str() {
701                "class_uid" | "category_uid" | "type_uid" | "activity_id" => {
702                    Some("the kind's `class`")
703                }
704                "unmapped" => Some("the kind's `unmapped` list"),
705                _ => None,
706            };
707            if let Some(reason) = reserved {
708                return Err(DefinitionError::Reserved {
709                    kind: kind.to_owned(),
710                    target: target.clone(),
711                    reason,
712                });
713            }
714            let source = match spec {
715                FieldSpec::Path(from) => Source::Path {
716                    path: source_path(kind, from)?,
717                    coercion: None,
718                },
719                FieldSpec::Converted { from, coercion } => Source::Path {
720                    path: source_path(kind, from)?,
721                    coercion: Some(*coercion),
722                },
723                FieldSpec::Translated {
724                    from,
725                    map,
726                    otherwise,
727                } => {
728                    let invalid = |reason| DefinitionError::Translation {
729                        kind: kind.to_owned(),
730                        target: target.clone(),
731                        reason,
732                    };
733                    let mut values = map.values().chain(otherwise).map(Value::from);
734                    let first = values.next().ok_or_else(|| invalid("is empty"))?;
735                    if values.any(|value| Writes::of(&value) != Writes::of(&first)) {
736                        return Err(invalid("mixes values of different types"));
737                    }
738                    Source::Translate {
739                        path: source_path(kind, from)?,
740                        map: map
741                            .iter()
742                            .map(|(key, value)| (key.clone(), Value::from(value)))
743                            .collect(),
744                        otherwise: otherwise.as_ref().map(Value::from),
745                    }
746                }
747                FieldSpec::Value { value } => Source::Constant(Value::from(value)),
748            };
749            Ok(Field {
750                target: path,
751                source,
752            })
753        })
754        .collect()
755}
756
757/// Rejects two fields writing the same attribute, or one inside another:
758/// the second write would replace or be lost under the first.
759fn check_overlaps(kind: &str, fields: &[Field]) -> Result<(), DefinitionError> {
760    for (index, first) in fields.iter().enumerate() {
761        for second in &fields[index + 1..] {
762            let (a, b) = (first.target.segments(), second.target.segments());
763            if a.starts_with(b) || b.starts_with(a) {
764                return Err(DefinitionError::Overlap {
765                    kind: kind.to_owned(),
766                    first: first.target.as_str().to_owned(),
767                    second: second.target.as_str().to_owned(),
768                });
769            }
770        }
771    }
772    Ok(())
773}
774
775/// Checks the class, the activity, and every field against the OCSF schema,
776/// so that a misspelled attribute fails here rather than produce events no
777/// rule reads.
778fn check_schema(
779    kind: &str,
780    class_uid: u32,
781    activity_id: u32,
782    fields: &[Field],
783) -> Result<(), DefinitionError> {
784    let class = schema::class(class_uid).ok_or_else(|| DefinitionError::UnknownClass {
785        kind: kind.to_owned(),
786        class_uid,
787        version: goliath_ocsf::SCHEMA_VERSION,
788    })?;
789    let activities = class
790        .attribute("activity_id")
791        .map(schema::Attribute::enum_values)
792        .unwrap_or_default();
793    if !activities.contains(&i64::from(activity_id)) {
794        return Err(DefinitionError::UnknownActivity {
795            kind: kind.to_owned(),
796            class: class.name(),
797            activity_id,
798        });
799    }
800    for field in fields {
801        let target = field.target.as_str();
802        let named = attribute_path(kind, class, field.target.segments())?;
803        let found = class
804            .resolve(&named)
805            .map_err(|source| DefinitionError::Attribute {
806                kind: kind.to_owned(),
807                source,
808            })?;
809        // A copy keeps whatever the source holds, and a free-form attribute
810        // takes anything, so neither has a type to check.
811        let Some(writes) = field.source.writes() else {
812            continue;
813        };
814        if found.free_form {
815            continue;
816        }
817        let attribute = found.attribute;
818        let fits = match writes {
819            Writes::Fingerprints => attribute.is_array() && attribute.type_name() == "fingerprint",
820            _ if attribute.is_array() => false,
821            Writes::Boolean => attribute.base() == Base::Boolean,
822            Writes::Integer => matches!(attribute.base(), Base::Integer | Base::Long),
823            Writes::Text => attribute.base() == Base::String,
824            Writes::Timestamp => attribute.type_name() == "timestamp_t",
825            Writes::Ip => attribute.type_name() == "ip_t",
826        };
827        if !fits {
828            let holds = match (attribute.is_array(), attribute.base()) {
829                (true, _) => format!("an array of `{}`", attribute.type_name()),
830                (false, Base::Object) => format!("an object `{}`", attribute.type_name()),
831                (false, _) => format!("`{}`", attribute.type_name()),
832            };
833            return Err(DefinitionError::Type {
834                kind: kind.to_owned(),
835                target: target.to_owned(),
836                holds,
837                writes: writes.describe(),
838            });
839        }
840        let values = attribute.enum_values();
841        let unknown = field
842            .source
843            .constants()
844            .filter_map(Value::as_i64)
845            .find(|value| !values.is_empty() && !values.contains(value));
846        if let Some(value) = unknown {
847            return Err(DefinitionError::UnknownValue {
848                kind: kind.to_owned(),
849                target: target.to_owned(),
850                value,
851            });
852        }
853    }
854    Ok(())
855}
856
857/// The attribute path of a target, without the indexes that name elements
858/// of arrays, such as `evidences.src_endpoint.ip` for
859/// `evidences.0.src_endpoint.ip`. Every array the target passes through
860/// must be followed by an index, and every index must follow an array.
861fn attribute_path(
862    kind: &str,
863    class: &schema::Class,
864    segments: &[String],
865) -> Result<String, DefinitionError> {
866    let target = || segments.join(".");
867    let is_index = |segment: &str| segment.bytes().all(|byte| byte.is_ascii_digit());
868    let mut named = String::new();
869    for (position, segment) in segments.iter().enumerate() {
870        // An index first is a name, which no class has.
871        if is_index(segment) && !named.is_empty() {
872            let array = class
873                .resolve(&named)
874                .is_ok_and(|found| found.attribute.is_array());
875            if !array {
876                return Err(DefinitionError::NotAnArray {
877                    kind: kind.to_owned(),
878                    target: target(),
879                    attribute: named,
880                });
881            }
882            continue;
883        }
884        if !named.is_empty() {
885            named.push('.');
886        }
887        named.push_str(segment);
888        let continues = segments
889            .get(position + 1)
890            .is_some_and(|next| !is_index(next));
891        if continues
892            && class
893                .resolve(&named)
894                .is_ok_and(|found| found.attribute.is_array() && !found.free_form)
895        {
896            return Err(DefinitionError::WithinArray {
897                kind: kind.to_owned(),
898                target: target(),
899            });
900        }
901    }
902    Ok(named)
903}
904
905/// What a field writes, where that is known before any record is read.
906#[derive(Debug, Clone, Copy, PartialEq, Eq)]
907enum Writes {
908    Boolean,
909    Integer,
910    Text,
911    Timestamp,
912    Ip,
913    Fingerprints,
914}
915
916impl Writes {
917    /// What writing `value` writes; nothing known for a list or an object.
918    fn of(value: &Value) -> Option<Self> {
919        match value {
920            Value::Bool(_) => Some(Self::Boolean),
921            Value::Number(_) => Some(Self::Integer),
922            Value::String(_) => Some(Self::Text),
923            _ => None,
924        }
925    }
926
927    fn describe(self) -> &'static str {
928        match self {
929            Self::Boolean => "a boolean",
930            Self::Integer => "an integer",
931            Self::Text => "text",
932            Self::Timestamp => "a timestamp",
933            Self::Ip => "an IP address",
934            Self::Fingerprints => "an array of fingerprints",
935        }
936    }
937}
938
939impl Source {
940    fn writes(&self) -> Option<Writes> {
941        match self {
942            Self::Constant(value) => Writes::of(value),
943            // Every value of a table has the same type, checked when it is
944            // compiled.
945            Self::Translate { map, .. } => map.values().next().and_then(Writes::of),
946            Self::Path { coercion: None, .. } => None,
947            Self::Path {
948                coercion: Some(coercion),
949                ..
950            } => Some(match coercion {
951                Coercion::String => Writes::Text,
952                Coercion::Integer => Writes::Integer,
953                Coercion::Timestamp | Coercion::UtcTimestamp | Coercion::UnixSeconds => {
954                    Writes::Timestamp
955                }
956                Coercion::Ip => Writes::Ip,
957                Coercion::Fingerprints => Writes::Fingerprints,
958            }),
959        }
960    }
961
962    /// Whether the source value also stays under `unmapped`, as written.
963    fn keeps_source(&self) -> bool {
964        matches!(
965            self,
966            Self::Path {
967                coercion: Some(Coercion::Fingerprints),
968                ..
969            }
970        )
971    }
972}
973
974impl Source {
975    /// Every value this source can write that is fixed by the definition.
976    fn constants(&self) -> impl Iterator<Item = &Value> {
977        let (map, extra) = match self {
978            Self::Constant(value) => (None, Some(value)),
979            Self::Translate { map, otherwise, .. } => (Some(map), otherwise.as_ref()),
980            Self::Path { .. } => (None, None),
981        };
982        map.into_iter().flat_map(BTreeMap::values).chain(extra)
983    }
984
985    /// The value to write for `found`, or why there is none.
986    fn convert(&self, found: &Value) -> Result<Value, String> {
987        match self {
988            Self::Constant(value) => Ok(value.clone()),
989            Self::Path { coercion, .. } => coerce(found, *coercion),
990            Self::Translate { map, otherwise, .. } => {
991                let key = match found {
992                    Value::String(text) => text.clone(),
993                    Value::Number(_) | Value::Bool(_) => found.to_string(),
994                    other => return Err(format!("cannot translate {}", describe(other))),
995                };
996                map.get(&key)
997                    .or(otherwise.as_ref())
998                    .cloned()
999                    .ok_or_else(|| format!("`{key}` is not in the translation table"))
1000            }
1001        }
1002    }
1003}
1004
1005/// Writes `value` at `segments`, creating objects on the way, and arrays
1006/// where a segment is an index, such as `0` of `evidences.0.src_endpoint`,
1007/// their elements before it empty objects. Overlapping targets are rejected
1008/// when the definition is compiled, so the way is always clear.
1009fn set(object: &mut Map<String, Value>, segments: &[String], value: Value) {
1010    let Some((first, rest)) = segments.split_first() else {
1011        return;
1012    };
1013    if rest.is_empty() {
1014        object.insert(first.clone(), value);
1015        return;
1016    }
1017    set_within(
1018        object.entry(first.clone()).or_insert(Value::Null),
1019        rest,
1020        value,
1021    );
1022}
1023
1024fn set_within(slot: &mut Value, segments: &[String], value: Value) {
1025    let Some((first, rest)) = segments.split_first() else {
1026        *slot = value;
1027        return;
1028    };
1029    if let Ok(index) = first.parse::<usize>() {
1030        if slot.is_null() {
1031            *slot = Value::Array(Vec::new());
1032        }
1033        let Value::Array(items) = slot else {
1034            return;
1035        };
1036        if items.len() <= index {
1037            items.resize(index + 1, Value::Object(Map::new()));
1038        }
1039        set_within(&mut items[index], rest, value);
1040    } else {
1041        if slot.is_null() {
1042            *slot = Value::Object(Map::new());
1043        }
1044        let Value::Object(object) = slot else {
1045            return;
1046        };
1047        set_within(
1048            object.entry(first.clone()).or_insert(Value::Null),
1049            rest,
1050            value,
1051        );
1052    }
1053}
1054
1055fn coerce(value: &Value, coercion: Option<Coercion>) -> Result<Value, String> {
1056    let Some(coercion) = coercion else {
1057        return Ok(value.clone());
1058    };
1059    match (coercion, value) {
1060        (Coercion::String, Value::String(_)) => Ok(value.clone()),
1061        (Coercion::String, Value::Number(number)) => Ok(Value::String(number.to_string())),
1062        (Coercion::Integer, Value::Number(number)) => number
1063            .as_i64()
1064            .map(Value::from)
1065            .ok_or_else(|| format!("{number} is not a whole number")),
1066        (Coercion::Integer, Value::String(text)) => {
1067            let trimmed = text.trim();
1068            match trimmed
1069                .strip_prefix("0x")
1070                .or_else(|| trimmed.strip_prefix("0X"))
1071            {
1072                Some(digits) => i64::from_str_radix(digits, 16),
1073                None => trimmed.parse::<i64>(),
1074            }
1075            .map(Value::from)
1076            .map_err(|_| format!("`{text}` is not a whole number"))
1077        }
1078        (Coercion::Timestamp, Value::String(text)) => text
1079            .parse::<jiff::Timestamp>()
1080            .map(|time| Value::from(time.as_millisecond()))
1081            .map_err(|error| format!("`{text}` is not an RFC 3339 time: {error}")),
1082        (Coercion::UtcTimestamp, Value::String(text)) => utc_timestamp(text),
1083        (Coercion::UnixSeconds, Value::String(text)) => unix_seconds(text),
1084        (Coercion::Ip, Value::String(text)) => text
1085            .trim()
1086            .parse::<std::net::IpAddr>()
1087            .map(|_| value.clone())
1088            .map_err(|_| format!("`{text}` is not an IP address")),
1089        (Coercion::UnixSeconds, Value::Number(number)) => unix_seconds(&number.to_string()),
1090        (Coercion::Fingerprints, Value::String(text)) => fingerprints(text),
1091        (coercion, other) => Err(format!(
1092            "cannot convert {} to {coercion:?}",
1093            describe(other)
1094        )),
1095    }
1096}
1097
1098/// File hashes written as `NAME=hash` joined by commas, as OCSF
1099/// fingerprints. A name OCSF has no algorithm for, such as `IMPHASH`, is
1100/// `Other`, with the name kept.
1101fn fingerprints(text: &str) -> Result<Value, String> {
1102    let mut found = Vec::new();
1103    for pair in text
1104        .split(',')
1105        .map(str::trim)
1106        .filter(|pair| !pair.is_empty())
1107    {
1108        let Some((name, hash)) = pair.split_once('=') else {
1109            return Err(format!("`{pair}` is not a hash written as NAME=hash"));
1110        };
1111        let name = name.trim().to_ascii_uppercase();
1112        let hash = hash.trim();
1113        if hash.is_empty() || !hash.bytes().all(|byte| byte.is_ascii_hexdigit()) {
1114            return Err(format!("`{pair}` does not hold a hexadecimal hash"));
1115        }
1116        let (algorithm, algorithm_id) = match name.as_str() {
1117            "MD5" => ("MD5", 1),
1118            "SHA1" | "SHA-1" => ("SHA-1", 2),
1119            "SHA256" | "SHA-256" => ("SHA-256", 3),
1120            "SHA512" | "SHA-512" => ("SHA-512", 4),
1121            other => (other, 99),
1122        };
1123        found.push(serde_json::json!({
1124            "algorithm": algorithm,
1125            "algorithm_id": algorithm_id,
1126            "value": hash,
1127        }));
1128    }
1129    if found.is_empty() {
1130        return Err("it holds no hash".to_owned());
1131    }
1132    Ok(Value::Array(found))
1133}
1134
1135/// An RFC 3339 time, with or without an offset, as milliseconds; one
1136/// without is UTC.
1137fn utc_timestamp(text: &str) -> Result<Value, String> {
1138    if let Ok(time) = text.parse::<jiff::Timestamp>() {
1139        return Ok(Value::from(time.as_millisecond()));
1140    }
1141    text.parse::<jiff::civil::DateTime>()
1142        .and_then(|time| time.to_zoned(jiff::tz::TimeZone::UTC))
1143        .map(|time| Value::from(time.timestamp().as_millisecond()))
1144        .map_err(|error| format!("`{text}` is not an RFC 3339 time: {error}"))
1145}
1146
1147/// Seconds since the epoch, such as `1727251200.123`, as milliseconds.
1148fn unix_seconds(text: &str) -> Result<Value, String> {
1149    let invalid = || format!("`{text}` is not a count of seconds since 1970");
1150    let (whole, fraction) = text.split_once('.').unwrap_or((text, ""));
1151    let digits = |part: &str| part.bytes().all(|byte| byte.is_ascii_digit());
1152    if whole.is_empty() || !digits(whole) || !digits(fraction) {
1153        return Err(invalid());
1154    }
1155    let seconds: i64 = whole.parse().map_err(|_| invalid())?;
1156    let millis: i64 = format!("{:0<3}", &fraction[..fraction.len().min(3)])
1157        .parse()
1158        .map_err(|_| invalid())?;
1159    seconds
1160        .checked_mul(1000)
1161        .and_then(|milliseconds| milliseconds.checked_add(millis))
1162        .map(Value::from)
1163        .ok_or_else(invalid)
1164}
1165
1166fn describe(value: &Value) -> &'static str {
1167    match value {
1168        Value::Null => "null",
1169        Value::Bool(_) => "a boolean",
1170        Value::Number(_) => "a number",
1171        Value::String(_) => "text",
1172        Value::Array(_) => "a list",
1173        Value::Object(_) => "an object",
1174    }
1175}