Skip to main content

goliath_rule/
resolved.rs

1//! The resolved form of a rule.
2//!
3//! Everything here refers to OCSF paths. Field names, modifiers, and
4//! transformations of the source rule language are gone by the time a rule
5//! reaches this form: `CommandLine|base64offset|contains` has become three
6//! wildcard patterns over `process.cmd_line`. An execution path only has to
7//! answer the questions in [`Test`].
8//!
9//! The enumerations here are deliberately not `#[non_exhaustive]`. Every
10//! execution path must answer every question, so a new kind of test has to
11//! stop an evaluator from compiling until it handles it, rather than fall into
12//! a catch-all arm that answers `false` and misses a detection. Adding one is
13//! a breaking change, and is released as one.
14
15use std::collections::BTreeMap;
16use std::fmt;
17use std::net::IpAddr;
18
19use goliath_sigma::{Pattern, RegexFlags};
20use serde::{Deserialize, Serialize};
21
22use crate::error::NetworkError;
23use crate::mapping::ClassValue;
24use crate::path::FieldPath;
25
26/// A rule ready for evaluation.
27#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
28pub struct ResolvedRule {
29    /// The rule's title.
30    pub title: String,
31    /// The rule's identifier, if it has one.
32    pub id: Option<String>,
33    /// The mapping set that resolved it, recorded on every alert.
34    pub mapping: MappingVersion,
35    /// Attribute values an event must have for the rule to apply at all.
36    pub class: BTreeMap<FieldPath, ClassValue>,
37    /// What the rule detects.
38    pub condition: Expr,
39}
40
41/// Which mapping set, at which version, resolved a rule.
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
43pub struct MappingVersion {
44    /// The mapping set's name.
45    pub name: String,
46    /// Its version.
47    pub version: u32,
48}
49
50/// A boolean expression over tests on an event.
51#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
52pub enum Expr {
53    /// Every operand holds. Empty holds.
54    And(Vec<Expr>),
55    /// At least one operand holds. Empty does not hold.
56    Or(Vec<Expr>),
57    /// The operand does not hold.
58    Not(Box<Expr>),
59    /// A test on the values some paths reach.
60    Field(Predicate),
61    /// A string test on any string value anywhere in the event.
62    Keyword(StringTest),
63}
64
65impl Expr {
66    /// Builds a conjunction, splicing in nested conjunctions and not wrapping
67    /// a single operand.
68    pub fn all(operands: Vec<Expr>) -> Self {
69        let mut flat = Vec::with_capacity(operands.len());
70        for operand in operands {
71            match operand {
72                Self::And(nested) => flat.extend(nested),
73                other => flat.push(other),
74            }
75        }
76        if flat.len() == 1 {
77            flat.remove(0)
78        } else {
79            Self::And(flat)
80        }
81    }
82
83    /// Builds a disjunction, splicing in nested disjunctions and not wrapping
84    /// a single operand.
85    pub fn any(operands: Vec<Expr>) -> Self {
86        let mut flat = Vec::with_capacity(operands.len());
87        for operand in operands {
88            match operand {
89                Self::Or(nested) => flat.extend(nested),
90                other => flat.push(other),
91            }
92        }
93        if flat.len() == 1 {
94            flat.remove(0)
95        } else {
96            Self::Or(flat)
97        }
98    }
99}
100
101/// A test on the values reached by any of several paths.
102///
103/// The paths are alternatives for the same fact, so their values are pooled
104/// before the test: a test that asks whether some value satisfies it holds if
105/// any path reaches one that does, and [`Test::Exists`] and [`Test::Null`] ask
106/// about the pool as a whole.
107#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
108pub struct Predicate {
109    /// Where to look.
110    pub paths: Vec<FieldPath>,
111    /// What to ask.
112    pub test: Test,
113}
114
115/// A question about the values a predicate's paths reach.
116#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
117pub enum Test {
118    /// Some string value matches the pattern.
119    String(StringTest),
120    /// Some string value matches the regular expression.
121    Regex {
122        /// The expression, as written in the rule.
123        pattern: String,
124        /// Flags from the rule.
125        flags: RegexFlags,
126    },
127    /// Some value is an IP address inside the network.
128    Cidr(Network),
129    /// Some non-null value exists, or, when `false`, none does.
130    Exists(bool),
131    /// No non-null value exists.
132    Null,
133    /// Some value equals the number, whether stored as a number or as its
134    /// decimal text.
135    Equals(Number),
136    /// Some value is the boolean.
137    Boolean(bool),
138    /// Some numeric value compares to the number as stated.
139    Compare {
140        /// The comparison.
141        op: Comparison,
142        /// The right-hand side.
143        value: Number,
144    },
145    /// Some value equals some value reached by another set of paths.
146    FieldRef {
147        /// The other field's paths.
148        paths: Vec<FieldPath>,
149        /// Whether case matters.
150        cased: bool,
151    },
152}
153
154/// A wildcard pattern and whether case matters.
155///
156/// When `cased` is false the pattern's literals are already folded with
157/// [`fold`](fn@crate::fold), so an execution path folds the event value and
158/// compares; it never folds the pattern again.
159#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
160pub struct StringTest {
161    /// The pattern.
162    pub pattern: Pattern,
163    /// Whether case matters.
164    pub cased: bool,
165}
166
167/// A number from a rule.
168#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
169pub enum Number {
170    /// An integer.
171    Integer(i64),
172    /// A floating point number.
173    Float(f64),
174}
175
176/// An ordering comparison.
177#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
178pub enum Comparison {
179    /// `<`
180    Less,
181    /// `<=`
182    LessOrEqual,
183    /// `>`
184    Greater,
185    /// `>=`
186    GreaterOrEqual,
187}
188
189/// An IP network: an address and a prefix length.
190///
191/// Deserialized from its text form through [`Network::parse`], so a prefix
192/// longer than the address cannot be constructed from a stored rule either.
193#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
194#[serde(try_from = "String", into = "String")]
195pub struct Network {
196    address: IpAddr,
197    prefix: u8,
198}
199
200impl Network {
201    /// Parses `address` or `address/prefix`.
202    ///
203    /// Returns `None` if the address does not parse or the prefix is longer
204    /// than the address.
205    pub fn parse(text: &str) -> Option<Self> {
206        let (address, prefix) = match text.split_once('/') {
207            Some((address, prefix)) => (address, Some(prefix)),
208            None => (text, None),
209        };
210        let address: IpAddr = address.parse().ok()?;
211        let max = Self::max_prefix(address);
212        let prefix = match prefix {
213            None => max,
214            Some(prefix) => prefix.parse::<u8>().ok().filter(|&p| p <= max)?,
215        };
216        Some(Self { address, prefix })
217    }
218
219    fn max_prefix(address: IpAddr) -> u8 {
220        match address {
221            IpAddr::V4(_) => 32,
222            IpAddr::V6(_) => 128,
223        }
224    }
225
226    /// Reports whether `candidate` lies inside this network.
227    ///
228    /// An IPv4 address never lies inside an IPv6 network or the reverse,
229    /// including IPv4-mapped IPv6 addresses; a rule author who wants both
230    /// writes both.
231    pub fn contains(&self, candidate: IpAddr) -> bool {
232        let (network, candidate) = match (self.address, candidate) {
233            (IpAddr::V4(network), IpAddr::V4(candidate)) => (
234                u128::from(network.to_bits()),
235                u128::from(candidate.to_bits()),
236            ),
237            (IpAddr::V6(network), IpAddr::V6(candidate)) => {
238                (network.to_bits(), candidate.to_bits())
239            }
240            _ => return false,
241        };
242        let host_bits = u32::from(Self::max_prefix(self.address) - self.prefix);
243        let shift = |bits: u128| bits.checked_shr(host_bits).unwrap_or(0);
244        shift(network) == shift(candidate)
245    }
246}
247
248impl TryFrom<String> for Network {
249    type Error = NetworkError;
250
251    fn try_from(text: String) -> Result<Self, Self::Error> {
252        Self::parse(&text).ok_or(NetworkError(text))
253    }
254}
255
256impl From<Network> for String {
257    fn from(network: Network) -> Self {
258        network.to_string()
259    }
260}
261
262impl fmt::Display for Network {
263    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
264        write!(f, "{}/{}", self.address, self.prefix)
265    }
266}
267
268#[cfg(test)]
269mod tests {
270    use super::*;
271
272    fn network(text: &str) -> Network {
273        Network::parse(text).expect("valid network")
274    }
275
276    fn ip(text: &str) -> IpAddr {
277        text.parse().expect("valid address")
278    }
279
280    #[test]
281    fn parses_networks_and_single_addresses() {
282        assert_eq!(network("10.0.0.0/8").to_string(), "10.0.0.0/8");
283        assert_eq!(network("10.1.2.3").to_string(), "10.1.2.3/32");
284        assert_eq!(network("fe80::/10").to_string(), "fe80::/10");
285        assert!(Network::parse("10.0.0.0/33").is_none());
286        assert!(Network::parse("fe80::/129").is_none());
287        assert!(Network::parse("10.0.0/8").is_none());
288    }
289
290    #[test]
291    fn contains_addresses_inside_the_prefix() {
292        let private = network("10.0.0.0/8");
293        assert!(private.contains(ip("10.255.1.2")));
294        assert!(!private.contains(ip("11.0.0.1")));
295
296        let link_local = network("fe80::/10");
297        assert!(link_local.contains(ip("fe80::1")));
298        assert!(!link_local.contains(ip("2001:db8::1")));
299    }
300
301    #[test]
302    fn edge_prefixes() {
303        assert!(network("0.0.0.0/0").contains(ip("203.0.113.9")));
304        assert!(network("::/0").contains(ip("2001:db8::1")));
305        assert!(network("192.0.2.7/32").contains(ip("192.0.2.7")));
306        assert!(!network("192.0.2.7/32").contains(ip("192.0.2.8")));
307    }
308
309    #[test]
310    fn address_families_never_mix() {
311        assert!(!network("0.0.0.0/0").contains(ip("::ffff:10.0.0.1")));
312        assert!(!network("::/0").contains(ip("10.0.0.1")));
313    }
314
315    #[test]
316    fn deserializing_checks_the_prefix() {
317        let parsed: Network = serde_json::from_str(r#""10.0.0.0/8""#).expect("valid");
318        assert_eq!(parsed, network("10.0.0.0/8"));
319        assert!(serde_json::from_str::<Network>(r#""10.0.0.0/200""#).is_err());
320    }
321
322    #[test]
323    fn single_operands_are_not_wrapped() {
324        let leaf = Expr::Keyword(StringTest {
325            pattern: Pattern::parse("x"),
326            cased: false,
327        });
328        assert_eq!(Expr::all(vec![leaf.clone()]), leaf);
329        assert_eq!(Expr::any(vec![leaf.clone()]), leaf);
330        assert_eq!(Expr::all(vec![]), Expr::And(vec![]));
331    }
332
333    #[test]
334    fn nested_operators_of_the_same_kind_are_spliced() {
335        let leaf = |text: &str| {
336            Expr::Keyword(StringTest {
337                pattern: Pattern::parse(text),
338                cased: false,
339            })
340        };
341        let nested = Expr::all(vec![
342            Expr::And(vec![leaf("a"), leaf("b")]),
343            Expr::Or(vec![leaf("c"), leaf("d")]),
344        ]);
345        assert_eq!(
346            nested,
347            Expr::And(vec![
348                leaf("a"),
349                leaf("b"),
350                Expr::Or(vec![leaf("c"), leaf("d")])
351            ])
352        );
353        // An empty nested conjunction holds, so splicing it away is exact.
354        assert_eq!(Expr::all(vec![Expr::And(vec![]), leaf("a")]), leaf("a"));
355    }
356}