boreal 1.1.0

A library to evaluate YARA rules, used to scan bytes for textual and binary pattern
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
use std::ops::Range;

use crate::regex::Hir;

use super::analysis::{analyze_hir, HirAnalysis};
use super::{MatchType, Matches, Modifiers};

mod dfa;
mod simple;

// Maximum length against which a regex validator of a AC literal match will be run.
//
// For example, lets say you have the `{ AA [1-] BB CC DD [1-] FF }` hex string. The
// `\xbb\xcc\xdd` literal is extracted, with:
// - the pre validator `\xaa.{1,}?\xbb\xcc\xdd$`
// - the post validator `^\xbb\xcc\xdd.{1,}?\xff`
//
// Both the pre and post validator will be run against a slice which maximum length is
// limited by the constant. Which means that `\xaa0\xbb\xcc\xdd` + ('0' * MAX+1) + '\xff'
// will not match.
const MAX_SPLIT_MATCH_LENGTH: usize = 4096;

#[derive(Debug)]
#[cfg_attr(all(test, feature = "serialize"), derive(PartialEq))]
pub(super) enum Validator {
    NonGreedy {
        forward: Option<HalfValidator>,
        reverse: Option<HalfValidator>,
    },
    Greedy {
        reverse: dfa::DfaValidator,
        full: dfa::DfaValidator,
    },
}

impl Validator {
    pub(super) fn new(
        pre: Option<&Hir>,
        post: Option<&Hir>,
        full: &Hir,
        modifiers: Modifiers,
    ) -> Result<Self, crate::regex::Error> {
        let reverse = match pre {
            Some(pre) => {
                let left_analysis = analyze_hir(pre, modifiers.dot_all);

                // XXX: If the left HIR has greedy repetitions, then the HIR cannot be split into a
                // (left, literals, right) triplet. This is because the greedy repetitions can
                // "eat" the literals, leading to incorrect matches.
                //
                // For example, a regex that looks like: `a.+foo.b` will extract the literal foo,
                // but against the string `aafoobbaafoobb`, it will match on the entire string,
                // while a (pre, post) matching would match twice.
                if left_analysis.has_greedy_repetitions {
                    let reverse = dfa::DfaValidator::new(pre, &left_analysis, modifiers, true)?;

                    let full_analysis = analyze_hir(full, modifiers.dot_all);
                    let full = dfa::DfaValidator::new(full, &full_analysis, modifiers, false)?;

                    return Ok(Self::Greedy { reverse, full });
                }

                Some(HalfValidator::new(pre, &left_analysis, modifiers, true)?)
            }
            None => None,
        };

        let forward = match post {
            Some(hir) => {
                let analysis = analyze_hir(hir, modifiers.dot_all);
                Some(HalfValidator::new(hir, &analysis, modifiers, false)?)
            }
            None => None,
        };

        Ok(Self::NonGreedy { forward, reverse })
    }

    #[cfg(feature = "serialize")]
    pub(super) fn deserialize<R: std::io::Read>(
        modifiers: Modifiers,
        reader: &mut R,
    ) -> std::io::Result<Self> {
        wire::deserialize_validator(modifiers, reader)
    }

    pub(super) fn validate_match(
        &self,
        mem: &[u8],
        mat: Range<usize>,
        start_position: usize,
        match_type: MatchType,
    ) -> Matches {
        match self {
            Self::NonGreedy { forward, reverse } => {
                let end = match forward {
                    Some(validator) => {
                        let end = std::cmp::min(
                            mem.len(),
                            mat.start.saturating_add(MAX_SPLIT_MATCH_LENGTH),
                        );
                        match validator.find_anchored_fwd(mem, mat.start, end, match_type) {
                            Some(end) => end,
                            None => return Matches::None,
                        }
                    }
                    None => mat.end,
                };

                match reverse {
                    None => Matches::Single(mat.start..end),
                    Some(validator) => {
                        // The left validator can yield multiple matches.
                        // For example, `a.?bb`, with the `bb` atom, can match as many times as there are
                        // 'a' characters before the `bb` atom.
                        let mut matches = Vec::new();
                        let mut start = std::cmp::max(
                            start_position,
                            mat.end.saturating_sub(MAX_SPLIT_MATCH_LENGTH),
                        );
                        while let Some(s) =
                            validator.find_anchored_rev(mem, start, mat.end, match_type)
                        {
                            matches.push(s..end);
                            start = s + 1;
                            if start > mat.end {
                                break;
                            }
                        }
                        Matches::Multiple(matches)
                    }
                }
            }
            Self::Greedy { reverse, full } => {
                let mut matches = Vec::new();

                let mut start = std::cmp::max(
                    start_position,
                    mat.end.saturating_sub(MAX_SPLIT_MATCH_LENGTH),
                );
                let end =
                    std::cmp::min(mem.len(), mat.start.saturating_add(MAX_SPLIT_MATCH_LENGTH));

                while let Some(s) = reverse.find_anchored_rev(mem, start, mat.end, match_type) {
                    if let Some(e) = full.find_anchored_fwd(mem, s, end, match_type) {
                        matches.push(s..e);
                    }
                    start = s + 1;
                    if start > mat.end {
                        break;
                    }
                }

                Matches::Multiple(matches)
            }
        }
    }
}

impl std::fmt::Display for Validator {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NonGreedy { forward, reverse } => {
                write!(f, "NonGreedy {{ ")?;
                match reverse {
                    Some(v) => write!(f, "reverse: {v}")?,
                    None => write!(f, "reverse: none")?,
                }
                write!(f, ", ")?;
                match forward {
                    Some(v) => write!(f, "forward: {v}")?,
                    None => write!(f, "forward: none")?,
                }
                write!(f, " }}")
            }
            Self::Greedy { .. } => {
                write!(f, "Greedy {{ reverse: Dfa, full: Dfa }}")
            }
        }
    }
}

#[derive(Debug)]
#[cfg_attr(all(test, feature = "serialize"), derive(PartialEq))]
pub(super) enum HalfValidator {
    // Simplified validator for very simple regex expressions.
    Simple(simple::SimpleValidator),
    // Dfa validator, handling all the complex cases
    Dfa(dfa::DfaValidator),
}

impl HalfValidator {
    fn new(
        hir: &Hir,
        analysis: &HirAnalysis,
        modifiers: Modifiers,
        reverse: bool,
    ) -> Result<Self, crate::regex::Error> {
        match simple::SimpleValidator::new(hir, analysis, modifiers, reverse) {
            Some(v) => Ok(Self::Simple(v)),
            None => Ok(Self::Dfa(dfa::DfaValidator::new(
                hir, analysis, modifiers, reverse,
            )?)),
        }
    }

    fn find_anchored_fwd(
        &self,
        haystack: &[u8],
        start: usize,
        end: usize,
        match_type: MatchType,
    ) -> Option<usize> {
        match self {
            Self::Simple(validator) => validator.find_anchored_fwd(haystack, start, end),
            Self::Dfa(validator) => validator.find_anchored_fwd(haystack, start, end, match_type),
        }
    }

    fn find_anchored_rev(
        &self,
        haystack: &[u8],
        start: usize,
        end: usize,
        match_type: MatchType,
    ) -> Option<usize> {
        match self {
            Self::Simple(validator) => validator.find_anchored_rev(haystack, start, end),
            Self::Dfa(validator) => validator.find_anchored_rev(haystack, start, end, match_type),
        }
    }
}

impl std::fmt::Display for HalfValidator {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Simple(_) => write!(f, "Simple"),
            Self::Dfa(_) => write!(f, "Dfa"),
        }
    }
}

#[cfg(feature = "serialize")]
mod wire {
    use std::io;

    use crate::wire::{Deserialize, Serialize};

    use crate::matcher::Modifiers;

    use super::simple::SimpleValidator;
    use super::{dfa, HalfValidator, Validator};

    impl Serialize for Validator {
        fn serialize<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
            match self {
                Validator::NonGreedy { forward, reverse } => {
                    0_u8.serialize(writer)?;
                    forward.serialize(writer)?;
                    reverse.serialize(writer)?;
                }
                Validator::Greedy { reverse, full } => {
                    1_u8.serialize(writer)?;
                    reverse.serialize(writer)?;
                    full.serialize(writer)?;
                }
            }
            Ok(())
        }
    }

    pub(super) fn deserialize_validator<R: io::Read>(
        modifiers: Modifiers,
        reader: &mut R,
    ) -> io::Result<Validator> {
        let discriminant = u8::deserialize_reader(reader)?;
        match discriminant {
            0 => {
                let forward_opt = bool::deserialize_reader(reader)?;
                let forward = if forward_opt {
                    Some(deserialize_half_validator(modifiers, false, reader)?)
                } else {
                    None
                };
                let reverse_opt = bool::deserialize_reader(reader)?;
                let reverse = if reverse_opt {
                    Some(deserialize_half_validator(modifiers, true, reader)?)
                } else {
                    None
                };
                Ok(Validator::NonGreedy { forward, reverse })
            }
            1 => {
                let reverse = dfa::DfaValidator::deserialize(modifiers, true, reader)?;
                let full = dfa::DfaValidator::deserialize(modifiers, true, reader)?;
                Ok(Validator::Greedy { reverse, full })
            }
            v => Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("invalid discriminant when deserializing a validator: {v}"),
            )),
        }
    }

    impl Serialize for HalfValidator {
        fn serialize<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
            match self {
                Self::Simple(simple) => {
                    0_u8.serialize(writer)?;
                    simple.serialize(writer)?;
                }
                Self::Dfa(dfa) => {
                    1_u8.serialize(writer)?;
                    dfa.serialize(writer)?;
                }
            }
            Ok(())
        }
    }

    fn deserialize_half_validator<R: io::Read>(
        modifiers: Modifiers,
        reverse: bool,
        reader: &mut R,
    ) -> io::Result<HalfValidator> {
        let discriminant = u8::deserialize_reader(reader)?;
        match discriminant {
            0 => Ok(HalfValidator::Simple(SimpleValidator::deserialize_reader(
                reader,
            )?)),
            1 => {
                let dfa = dfa::DfaValidator::deserialize(modifiers, reverse, reader)?;
                Ok(HalfValidator::Dfa(dfa))
            }
            v => Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("invalid discriminant when deserializing a half validator: {v}"),
            )),
        }
    }

    #[cfg(test)]
    mod tests {
        use dfa::DfaValidator;

        use crate::matcher::analysis::analyze_hir;
        use crate::regex::Hir;
        use crate::wire::tests::test_round_trip_custom_deser;

        use super::*;

        #[test]
        fn test_wire_validator() {
            let hir = Hir::Dot;
            let analysis = analyze_hir(&hir, false);
            let modifiers = Modifiers::default();

            test_round_trip_custom_deser(
                &Validator::NonGreedy {
                    forward: None,
                    reverse: Some(HalfValidator::Simple(
                        SimpleValidator::new(&hir, &analysis, modifiers, false).unwrap(),
                    )),
                },
                |reader| deserialize_validator(modifiers, reader),
                &[0, 1, 2],
            );
            test_round_trip_custom_deser(
                &Validator::NonGreedy {
                    forward: Some(HalfValidator::Simple(
                        SimpleValidator::new(&hir, &analysis, modifiers, false).unwrap(),
                    )),
                    reverse: None,
                },
                |reader| deserialize_validator(modifiers, reader),
                &[0],
            );
            test_round_trip_custom_deser(
                &Validator::Greedy {
                    reverse: DfaValidator::new(&hir, &analysis, modifiers, false).unwrap(),
                    full: DfaValidator::new(&hir, &analysis, modifiers, false).unwrap(),
                },
                |reader| deserialize_validator(modifiers, reader),
                &[0, 1, 14],
            );

            // Test failure when compiling expressions.
            let mut reader = io::Cursor::new(b"\x05");
            assert!(deserialize_validator(modifiers, &mut reader).is_err());
        }

        #[test]
        fn test_wire_half_validator() {
            let hir = Hir::Dot;
            let analysis = analyze_hir(&hir, false);
            let modifiers = Modifiers::default();

            test_round_trip_custom_deser(
                &HalfValidator::Simple(
                    SimpleValidator::new(&hir, &analysis, modifiers, false).unwrap(),
                ),
                |reader| deserialize_half_validator(modifiers, false, reader),
                &[0, 1],
            );
            test_round_trip_custom_deser(
                &HalfValidator::Dfa(DfaValidator::new(&hir, &analysis, modifiers, false).unwrap()),
                |reader| deserialize_half_validator(modifiers, false, reader),
                &[0, 1],
            );

            // Test failure when compiling expressions.
            let mut reader = io::Cursor::new(b"\x05");
            assert!(deserialize_half_validator(modifiers, false, &mut reader).is_err());
        }
    }
}

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

    #[test]
    fn test_types_traits() {
        test_type_traits_non_clonable(
            Validator::new(None, None, &Hir::Empty, Modifiers::default()).unwrap(),
        );
        test_type_traits_non_clonable(
            HalfValidator::new(
                &Hir::Empty,
                &analyze_hir(&Hir::Empty, false),
                Modifiers::default(),
                false,
            )
            .unwrap(),
        );
    }
}