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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
use std::collections::HashMap;
use std::collections::HashSet;
use std::ops::Range;
use std::sync::Arc;

use boreal_parser::rule;

use super::expression::{compile_bool_expression, Expression, VariableIndex};
use super::external_symbol::ExternalSymbol;
use super::{variable, CompilationError, CompilerParams, Namespace};
use crate::bytes_pool::{BytesPoolBuilder, BytesSymbol, StringSymbol};
use crate::module::Type as ModuleType;
use crate::statistics;

/// A compiled scanning rule.
#[derive(Debug)]
#[cfg_attr(all(test, feature = "serialize"), derive(PartialEq))]
pub(crate) struct Rule {
    /// Name of the rule.
    pub(crate) name: String,

    /// Index of the namespace containing the rule.
    ///
    /// This refers to the [`super::Compiler::namespaces`] or
    /// [`crate::Scanner::namespaces`] list.
    pub(crate) namespace_index: usize,

    /// Tags associated with the rule.
    pub(crate) tags: Vec<String>,

    /// Metadata associated with the rule.
    pub(crate) metadatas: Vec<Metadata>,

    /// Number of variables used by the rule.
    pub(crate) nb_variables: usize,

    /// Condition of the rule.
    pub(crate) condition: Expression,

    /// Is the rule marked as private.
    pub(crate) is_private: bool,
}

impl Rule {
    #[cfg(feature = "serialize")]
    pub(crate) fn deserialize<R: std::io::Read>(
        ctx: &crate::wire::DeserializeContext,
        reader: &mut R,
    ) -> std::io::Result<Self> {
        wire::deserialize_rule(ctx, reader)
    }
}

/// A metadata associated with a rule.
#[derive(Debug, PartialEq)]
pub struct Metadata {
    /// Name of the metadata.
    ///
    /// Use [`crate::Scanner::get_string_symbol`] to retrieve the string.
    pub name: StringSymbol,

    /// The value of the metadata.
    pub value: MetadataValue,
}

/// Value of a rule metadata.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum MetadataValue {
    /// Bytestring variant.
    ///
    /// Use [`crate::Scanner::get_bytes_symbol`] to retrieve the string.
    Bytes(BytesSymbol),
    /// Integer variant.
    Integer(i64),
    /// Boolean variant.
    Boolean(bool),
}

/// Object used to compile a rule.
#[derive(Debug)]
pub(super) struct RuleCompiler<'a> {
    /// Namespace in which the rule is built and added to.
    pub namespace: &'a Namespace,

    /// Variables declared in this rule.
    ///
    /// The index of the variable in this vector will match the index of the variable
    /// in the compiled rules's variable vec. It can thus be used to compile
    /// access to the variable.
    pub variables: Vec<RuleCompilerVariable>,

    /// Map of the name of a bounded identifier to its type and index in the bounded identifier
    /// stack.
    pub bounded_identifiers: HashMap<String, Arc<(ModuleType, usize)>>,

    /// List of rules wildcard used in for expressions.
    ///
    /// This will be added to the compiler if the rule is successfully compiled,
    /// and used to ensure no rules matching those wildcard can be declared anymore
    /// in the namespace.
    pub rule_wildcard_uses: Vec<String>,

    /// List of external symbols defined in the compiler.
    pub external_symbols: &'a Vec<ExternalSymbol>,

    /// Compilation parameters
    pub params: &'a CompilerParams,

    /// Current depth in the rule's condition AST.
    ///
    /// As evaluation of a rule condition involves recursion, this is used to limit the
    /// depth of this recursion and prevent stack overflows.
    pub condition_depth: u32,

    /// Warnings emitted while compiling the rule.
    pub warnings: Vec<CompilationError>,

    /// Bytes intern pool.
    pub bytes_pool: &'a mut BytesPoolBuilder,
}

/// Helper struct used to track variables being compiled in a rule.
#[derive(Debug)]
pub(super) struct RuleCompilerVariable {
    /// Name of the variable.
    pub name: String,

    /// Has the variable been used.
    ///
    /// If by the end of the compilation of the rule, the variable is unused, a compilation
    /// error is raised.
    pub used: bool,
}

impl<'a> RuleCompiler<'a> {
    pub(super) fn new(
        rule_variables: &[rule::VariableDeclaration],
        namespace: &'a Namespace,
        external_symbols: &'a Vec<ExternalSymbol>,
        params: &'a CompilerParams,
        bytes_pool: &'a mut BytesPoolBuilder,
    ) -> Result<Self, CompilationError> {
        if rule_variables.len() > params.max_strings_per_rule {
            return Err(CompilationError::TooManyStrings {
                span: rule_variables[params.max_strings_per_rule].span.clone(),
                limit: params.max_strings_per_rule,
            });
        }

        let mut names_set = HashSet::new();
        let mut variables = Vec::with_capacity(rule_variables.len());
        for var in rule_variables {
            // Check duplicated names, but only for non anonymous strings
            if !var.name.is_empty() && !names_set.insert(var.name.clone()) {
                return Err(CompilationError::DuplicatedVariable {
                    name: var.name.clone(),
                    span: var.span.clone(),
                });
            }

            variables.push(RuleCompilerVariable {
                name: var.name.clone(),
                used: false,
            });
        }

        Ok(Self {
            namespace,
            variables,
            bounded_identifiers: HashMap::new(),
            rule_wildcard_uses: Vec::new(),
            external_symbols,
            params,
            condition_depth: 0,
            warnings: Vec::new(),
            bytes_pool,
        })
    }

    /// Find a variable used in a rule by name.
    ///
    /// The provided span is the one of the expression using the variable, and is
    /// used for the error if the find fails.
    ///
    /// This function allows anonymous variables. To only allow named variable, use
    /// [`self.find_named_variable`] instead.
    pub(super) fn find_variable(
        &mut self,
        name: &str,
        span: &Range<usize>,
    ) -> Result<VariableIndex, CompilationError> {
        if name.is_empty() {
            Ok(VariableIndex(None))
        } else {
            Ok(VariableIndex(Some(self.find_named_variable(name, span)?)))
        }
    }

    /// Find a variable used in a rule by name, without accepting anonymous variables.
    pub(super) fn find_named_variable(
        &mut self,
        name: &str,
        span: &Range<usize>,
    ) -> Result<usize, CompilationError> {
        for (index, var) in self.variables.iter_mut().enumerate() {
            if var.name == name {
                var.used = true;
                return Ok(index);
            }
        }
        Err(CompilationError::UnknownVariable {
            variable_name: name.to_owned(),
            span: span.clone(),
        })
    }

    /// Add a bounded identifier.
    pub(super) fn add_bounded_identifier(
        &mut self,
        name: &str,
        typ: ModuleType,
        span: &Range<usize>,
    ) -> Result<(), CompilationError> {
        let index = self.bounded_identifiers.len();
        match self
            .bounded_identifiers
            .insert(name.to_string(), Arc::new((typ, index)))
        {
            Some(_) => Err(CompilationError::DuplicatedIdentifierBinding {
                identifier: name.to_string(),
                span: span.clone(),
            }),
            None => Ok(()),
        }
    }

    /// Remove a bounded identifier.
    pub(super) fn remove_bounded_identifier(&mut self, name: &str) {
        drop(self.bounded_identifiers.remove(name));
    }

    pub(super) fn add_warning(&mut self, err: CompilationError) -> Result<(), CompilationError> {
        if matches!(err, CompilationError::RegexUnknownEscape { .. })
            && self.params.disable_unknown_escape_warning
        {
            return Ok(());
        }

        if self.params.fail_on_warnings {
            Err(err)
        } else {
            self.warnings.push(err);
            Ok(())
        }
    }
}

pub(super) fn compile_rule(
    rule: rule::Rule,
    namespace: &Namespace,
    namespace_index: usize,
    external_symbols: &Vec<ExternalSymbol>,
    params: &CompilerParams,
    parsed_contents: &str,
    bytes_pool: &mut BytesPoolBuilder,
) -> Result<CompiledRule, CompilationError> {
    // Check duplication of tags
    let mut tags_spans = HashMap::with_capacity(rule.tags.len());
    for v in &rule.tags {
        if let Some(span1) = tags_spans.insert(&v.tag, v.span.clone()) {
            return Err(CompilationError::DuplicatedRuleTag {
                tag: v.tag.clone(),
                span1,
                span2: v.span.clone(),
            });
        }
    }

    let metadatas: Vec<_> = rule
        .metadatas
        .into_iter()
        .map(|rule::Metadata { name, value }| Metadata {
            name: bytes_pool.insert_str(&name),
            value: match value {
                rule::MetadataValue::Bytes(v) => MetadataValue::Bytes(bytes_pool.insert(&v)),
                rule::MetadataValue::Integer(v) => MetadataValue::Integer(v),
                rule::MetadataValue::Boolean(v) => MetadataValue::Boolean(v),
            },
        })
        .collect();

    let mut compiler = RuleCompiler::new(
        &rule.variables,
        namespace,
        external_symbols,
        params,
        bytes_pool,
    )?;
    let condition = compile_bool_expression(&mut compiler, rule.condition)?;

    let mut variables = Vec::with_capacity(rule.variables.len());
    let mut variables_statistics = Vec::new();

    for (i, var) in rule.variables.into_iter().enumerate() {
        if !compiler.variables[i].used && !var.name.starts_with('_') {
            return Err(CompilationError::UnusedVariable {
                name: var.name,
                span: var.span,
            });
        }

        let (var, stats) = variable::compile_variable(&mut compiler, var, parsed_contents)?;
        if let Some(stats) = stats {
            variables_statistics.push(stats);
        }
        variables.push(var);
    }

    Ok(CompiledRule {
        rule: Rule {
            name: rule.name,
            namespace_index,
            tags: rule.tags.into_iter().map(|v| v.tag).collect(),
            metadatas,
            nb_variables: variables.len(),
            condition,
            is_private: rule.is_private,
        },
        variables,
        variables_statistics,
        warnings: compiler.warnings,
        rule_wildcard_uses: compiler.rule_wildcard_uses,
    })
}

#[derive(Debug)]
pub(super) struct CompiledRule {
    pub rule: Rule,
    pub variables: Vec<variable::Variable>,
    pub variables_statistics: Vec<statistics::CompiledString>,
    pub warnings: Vec<CompilationError>,
    pub rule_wildcard_uses: Vec<String>,
}

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

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

    use crate::compiler::expression::Expression;
    use crate::wire::DeserializeContext;
    use crate::{BytesSymbol, StringSymbol};

    use super::{Metadata, MetadataValue, Rule};

    impl Serialize for Rule {
        fn serialize<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
            self.name.serialize(writer)?;
            self.namespace_index.serialize(writer)?;
            self.nb_variables.serialize(writer)?;
            self.is_private.serialize(writer)?;
            self.tags.serialize(writer)?;
            self.metadatas.serialize(writer)?;
            self.condition.serialize(writer)?;
            Ok(())
        }
    }

    pub(super) fn deserialize_rule<R: io::Read>(
        ctx: &DeserializeContext,
        reader: &mut R,
    ) -> io::Result<Rule> {
        let name = String::deserialize_reader(reader)?;
        let namespace_index = usize::deserialize_reader(reader)?;
        let nb_variables = usize::deserialize_reader(reader)?;
        let is_private = bool::deserialize_reader(reader)?;
        let tags = <Vec<String>>::deserialize_reader(reader)?;
        let metadatas = <Vec<Metadata>>::deserialize_reader(reader)?;
        let condition = Expression::deserialize(ctx, reader)?;
        Ok(Rule {
            name,
            namespace_index,
            tags,
            metadatas,
            nb_variables,
            condition,
            is_private,
        })
    }

    impl Serialize for Metadata {
        fn serialize<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
            self.name.serialize(writer)?;
            self.value.serialize(writer)?;
            Ok(())
        }
    }

    impl Deserialize for Metadata {
        fn deserialize_reader<R: io::Read>(reader: &mut R) -> io::Result<Self> {
            let name = StringSymbol::deserialize_reader(reader)?;
            let value = MetadataValue::deserialize_reader(reader)?;
            Ok(Self { name, value })
        }
    }

    impl Serialize for MetadataValue {
        fn serialize<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
            match self {
                Self::Bytes(s) => {
                    0_u8.serialize(writer)?;
                    s.serialize(writer)?;
                }
                Self::Integer(v) => {
                    1_u8.serialize(writer)?;
                    v.serialize(writer)?;
                }
                Self::Boolean(v) => {
                    2_u8.serialize(writer)?;
                    v.serialize(writer)?;
                }
            }
            Ok(())
        }
    }

    impl Deserialize for MetadataValue {
        fn deserialize_reader<R: io::Read>(reader: &mut R) -> io::Result<Self> {
            let discriminant = u8::deserialize_reader(reader)?;
            match discriminant {
                0 => Ok(Self::Bytes(BytesSymbol::deserialize_reader(reader)?)),
                1 => Ok(Self::Integer(i64::deserialize_reader(reader)?)),
                2 => Ok(Self::Boolean(bool::deserialize_reader(reader)?)),
                v => Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("invalid discriminant when deserializing a metadata value: {v}"),
                )),
            }
        }
    }

    #[cfg(test)]
    mod tests {
        use crate::compiler::BytesPoolBuilder;
        use crate::wire::tests::{
            test_invalid_deserialization, test_round_trip, test_round_trip_custom_deser,
        };

        use super::*;

        #[test]
        fn test_wire_rule() {
            let ctx = DeserializeContext::default();

            test_round_trip_custom_deser(
                &Rule {
                    name: "a".to_owned(),
                    namespace_index: 0,
                    nb_variables: 0,
                    is_private: false,
                    tags: Vec::new(),
                    metadatas: Vec::new(),
                    condition: Expression::Filesize,
                },
                |reader| deserialize_rule(&ctx, reader),
                &[0, 5, 13, 21, 22, 26, 30],
            );
        }

        #[test]
        fn test_wire_metadata() {
            let mut pool = BytesPoolBuilder::default();

            test_round_trip(
                &Metadata {
                    name: pool.insert_str("ab"),
                    value: MetadataValue::Boolean(true),
                },
                &[0, 16],
            );

            test_invalid_deserialization::<MetadataValue>(b"\x05");
        }

        #[test]
        fn test_wire_metadata_value() {
            let mut pool = BytesPoolBuilder::default();

            test_round_trip(&MetadataValue::Bytes(pool.insert(b"a")), &[0, 1]);
            test_round_trip(&MetadataValue::Integer(23), &[0, 1]);
            test_round_trip(&MetadataValue::Boolean(true), &[0, 1]);

            test_invalid_deserialization::<MetadataValue>(b"\x05");
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::test_helpers::{test_type_traits, test_type_traits_non_clonable};

    use super::*;

    #[test]
    fn test_types_traits() {
        test_type_traits_non_clonable(RuleCompiler {
            namespace: &Namespace::default(),
            variables: Vec::new(),
            bounded_identifiers: HashMap::new(),
            rule_wildcard_uses: Vec::new(),
            external_symbols: &vec![],
            params: &CompilerParams::default(),
            condition_depth: 0,
            warnings: Vec::new(),
            bytes_pool: &mut BytesPoolBuilder::default(),
        });
        let build_rule = || Rule {
            name: "a".to_owned(),
            namespace_index: 0,
            tags: Vec::new(),
            metadatas: Vec::new(),
            nb_variables: 0,
            condition: Expression::Filesize,
            is_private: false,
        };
        test_type_traits_non_clonable(build_rule());
        test_type_traits_non_clonable(CompiledRule {
            rule: build_rule(),
            variables: Vec::new(),
            variables_statistics: Vec::new(),
            warnings: Vec::new(),
            rule_wildcard_uses: Vec::new(),
        });
        test_type_traits_non_clonable(RuleCompilerVariable {
            name: "a".to_owned(),
            used: false,
        });
        let mut pool = BytesPoolBuilder::default();
        test_type_traits_non_clonable(Metadata {
            name: pool.insert_str(""),
            value: MetadataValue::Boolean(true),
        });
        test_type_traits(MetadataValue::Boolean(true));
    }
}