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 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
use std::collections::HashMap;
use std::fmt;
use std::fs;
use std::path::Path;
use serde::de::{self, Deserializer, MapAccess, Visitor};
use serde::{Deserialize, Serialize};
use serde_yaml::Value as Yaml;
use crate::document::Document;
use crate::optimiser::{self, Optimisations};
use crate::parser::{self, Expression};
use crate::solver;
use crate::tokeniser::{ModSym, Token, Tokeniser};
/// The detection block, this contains the logic that is to be run through the solver to evaluate a
/// `Document`.
#[derive(Clone, Serialize)]
pub struct Detection {
/// The core expression.
#[serde(skip_serializing)]
pub expression: Expression,
/// Additional expressions, defined using key/value pairs.
#[serde(skip_serializing)]
pub identifiers: HashMap<String, Expression>,
#[serde(rename = "condition")]
expression_raw: String,
#[serde(flatten)]
identifiers_raw: HashMap<String, Yaml>,
}
impl fmt::Debug for Detection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Detection")
.field("expression", &self.expression_raw)
.field("identifiers", &self.identifiers_raw)
.finish()
}
}
impl<'de> Deserialize<'de> for Detection {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct DetectionVisitor;
impl<'de> Visitor<'de> for DetectionVisitor {
type Value = Detection;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("struct Detection")
}
fn visit_map<V>(self, mut map: V) -> Result<Detection, V::Error>
where
V: MapAccess<'de>,
{
let mut identifiers: HashMap<String, Expression> = HashMap::new();
let mut identifiers_raw: HashMap<String, Yaml> = HashMap::new();
let mut expression = None;
while let Some(key) = map.next_key::<String>()? {
match key.as_ref() {
"condition" => {
if expression.is_some() {
return Err(de::Error::duplicate_field("condition"));
}
expression = Some(map.next_value::<String>()?);
}
_ => {
if identifiers.get(&key).is_some() {
return Err(de::Error::custom(format_args!(
"duplicate field `{}`",
key
)));
}
let v: Yaml = map.next_value()?;
identifiers.insert(
key.to_string(),
parser::parse_identifier(&v).map_err(|e| {
de::Error::custom(format!(
"failed to parse identifier - {:?}",
e
))
})?,
);
identifiers_raw.insert(key.to_string(), v.clone());
}
}
}
let expression_raw =
expression.ok_or_else(|| de::Error::missing_field("condition"))?;
let tokens = match expression_raw.tokenise() {
Ok(tokens) => tokens,
Err(err) => {
return Err(de::Error::custom(format_args!(
"invalid value: condition, failed to tokenise - {}",
err
)));
}
};
// Loop through the tokens making sure that all identifiers are present, this is a
// pain because we need to ignore fields... For now we can just check for misc
// symbol prefix and skip those if present
let mut i = 0;
for token in &tokens {
if i > 1 {
if let Token::Modifier(m) = &tokens[i - 2] {
match m {
ModSym::Flt | ModSym::Int | ModSym::Not | ModSym::Str => {
i += 1;
continue;
}
}
}
}
if let Token::Identifier(id) = token {
if !identifiers.contains_key(id) {
return Err(de::Error::custom(format_args!(
"invalid condition: identifier not found - {}",
id
)));
}
}
i += 1;
}
let expression = match parser::parse(&tokens) {
Ok(expression) => expression,
Err(err) => {
return Err(de::Error::custom(format_args!(
"invalid value: condition, failed to parse - {}",
err
)));
}
};
if !expression.is_solvable() {
return Err(de::Error::custom(format_args!(
"invalid value: condition, not solveable - {}",
expression
)));
}
Ok(Detection {
expression,
identifiers,
expression_raw,
identifiers_raw,
})
}
}
const FIELDS: &[&str] = &["identifiers", "condition"];
deserializer.deserialize_struct("Detection", FIELDS, DetectionVisitor)
}
}
/// A rule used by the solver to evaluate a `Document`.
///
/// A rule contains the detection logic, along with the true positive and negative tests. The
/// inclusion of these basic test allows for a basic level of verification to be ensured.
///
/// Rules are written in YAML and have a simple but powerful syntax.
///
/// # Syntax
///
/// There are two parts to a rule's logic: the condition & the identifiers.
///
/// ## Condition
///
/// The condition is the main expression and describes the top level logic for the rule. It can be
/// comprised of the following:
///
/// <table>
/// <thead>
/// <tr>
/// <th>Expression</th>
/// <th>Description</th>
/// </tr>
/// </thead>
/// <tbody>
/// <tr>
/// <td>_ <code>and</code> _</td>
/// <td>
/// <span>The logical conjunction of two operands, where the operands are any of the following:</span>
/// <ul>
/// <li>
/// <code>expression</code><span>: a nested expression.</span>
/// </li>
/// <li>
/// <code>identifier</code><span>: a key that matches an identifier in the detection block.</span>
/// </li>
/// </ul>
/// </td>
/// </tr>
/// <tr>
/// <td>_ <code>or</code> _</td>
/// <td>
/// <span>The logical disjunction of two operands, where the operands are any of the following:</span>
/// <ul>
/// <li>
/// <code>expression</code><span>: a nested expression.</span>
/// </li>
/// <li>
/// <code>identifier</code><span>: a key that matches an identifier in the detection block.</span>
/// </li>
/// </ul>
/// </td>
/// </tr>
/// <tr>
/// <td>_ <code>==</code> _</td>
/// <td>
/// <span>The equality comparison of two operands, where the operands are any of the following:</span>
/// <ul>
/// <li>
/// <code>integer</code><span>: an integer.</span>
/// </li>
/// <li>
/// <code>string</code><span>: a string.</span>
/// </li>
/// <li>
/// <code>int(field)</code><span>: a field that should be cast as an
/// integer.</span>
/// </li>
/// <li>
/// <code>str(field)</code><span>: a field that should be cast as a
/// string.</span>
/// </li>
/// </ul>
/// </td>
/// </tr>
/// <tr>
/// <td>_ <code>></code> _</td>
/// <td>
/// <span>The greater than comparison of two operands, where the operands are any of the following:</span>
/// <ul>
/// <li>
/// <code>integer</code><span>: an integer.</span>
/// </li>
/// <li>
/// <code>int(field)</code><span>: a field that should be cast as an
/// integer.</span>
/// </li>
/// </ul>
/// </td>
/// </tr>
/// <tr>
/// <td>_ <code>>=</code> _</td>
/// <td>
/// <span>The greater than or equal comparison of two operands, where the operands are any of the following:</span>
/// <ul>
/// <li>
/// <code>integer</code><span>: an integer.</span>
/// </li>
/// <li>
/// <code>int(field)</code><span>: a field that should be cast as an
/// integer.</span>
/// </li>
/// </ul>
/// </td>
/// </tr>
/// <tr>
/// <td>_ <code><</code> _</td>
/// <td>
/// <span>The less than comparison of two operands, where the operands are any of the following:</span>
/// <ul>
/// <li>
/// <code>integer</code><span>: an integer.</span>
/// </li>
/// <li>
/// <code>int(field)</code><span>: a field that should be cast as an
/// integer.</span>
/// </li>
/// </ul>
/// </td>
/// </tr>
/// <tr>
/// <td>_ <code><=</code> _</td>
/// <td>
/// <span>The less than or equal comparison of two operands, where the operands are any of the following:</span>
/// <ul>
/// <li>
/// <code>integer</code><span>: an integer.</span>
/// </li>
/// <li>
/// <code>int(field)</code><span>: a field that should be cast as an
/// integer.</span>
/// </li>
/// </ul>
/// </td>
/// </tr>
/// <tr>
/// <td><code>all(i)</code></td>
/// <td>
/// <span>An identifier mutator that evaluates to true only if all conditions for identifier <code>i</code> match.</span>
/// </td>
/// </tr>
/// <tr>
/// <td><code>not</code> _</td>
/// <td>
/// <span>Negate the result of an expression.</span>
/// <span>NOTE: This will only negate a result that is true or false, it will
/// noop if the result is missing.</span>
/// </td>
/// </tr>
/// <tr>
/// <td><code style="white-space:nowrap">of(i, x)</code></td>
/// <td>
/// <span>An identifier mutator that evaluates to true only if a minimum of <code>x</code> conditions for identifier <code>i</code> match.</span>
/// </td>
/// </tr>
/// </tbody>
/// </table>
///
/// # Identifiers
///
/// Identifiers are used to describe the matching logic for the values contained within documents.
/// These are then collected by the condition in order to create a rule that can be used to tag a
/// document.
///
/// Due to the nature of an identifier, they are essentially just variations on key/value
/// pairs. The following variations are supported, where mappings are treated as conjunctions and
/// sequences are treated as disjunctions:
///
/// ```text
/// # K/V Pairs
/// IDENTIFIER:
/// KEY: MATCH
///
/// # K/V Pairs with multiple matches
/// IDENTIFIER:
/// KEY:
/// - MATCH_0
/// - MATCH_1
///
/// # K/V Pairs (Grouped)
/// IDENTIFIER:
/// - KEY: MATCH
///
/// # K/V Pairs (Nested)
/// IDENTIFIER:
/// KEY:
/// KEY: MATCH
/// ```
///
/// Identifiers are unique keys that can be referenced in the `condition`.
///
/// Keys are used to get the values from documents. Keys can be wrapped in the following modifiers:
///
/// <table>
/// <thead>
/// <tr>
/// <th>Expression</th>
/// <th>Description</th>
/// </tr>
/// </thead>
/// <tbody>
/// <tr>
/// <td><code>all(k)</code></td>
/// <td>
/// <span>A key mutator that evaluates to true only if all matches for keys <code>k</code> match.</span>
/// </td>
/// </tr>
/// <tr>
/// <td><code style="white-space:nowrap">of(k, x)</code></td>
/// <td>
/// <span>A key mutator that evaluates to true only if a minimum of <code>x</code> matches for key <code>k</code> match.</span>
/// </td>
/// </tr>
/// </tbody>
/// </table>
///
/// Matches are the expressions which are evaluated against values returned by keys. They support the
/// following syntax:
///
/// <table>
/// <thead>
/// <tr>
/// <th>Expression</th>
/// <th>Description</th>
/// </tr>
/// </thead>
/// <tbody>
/// <tr>
/// <td><code>foo</code></td>
/// <td><span>An exact match</span></td>
/// </tr>
/// <tr>
/// <td><code>foo*</code></td>
/// <td><span>Starts with</span></td>
/// </tr>
/// <tr>
/// <td><code>*foo</code></td>
/// <td><span>Ends with</span></td>
/// </tr>
/// <tr>
/// <td><code>*foo*</code></td>
/// <td><span>Contains</span></td>
/// </tr>
/// <tr>
/// <td><code>?foo</code></td>
/// <td><span>Regex</span></td>
/// </tr>
/// <tr>
/// <td><code>i</code>_</td>
/// <td><span>A prefix to convert the match into a case insensitive match.</span></td>
/// </tr>
/// </tbody>
/// </table>
///
/// To escape any of the above in order to achieve literal string matching, combinations of `'` and `"` can be used.
///
/// # Examples
///
/// Here is a very simple rule example:
///
/// ```text
/// detection:
/// A:
/// foo: "foo*"
/// bar: "*bar"
/// B:
/// foobar:
/// - foobar
/// - foobaz
///
/// condition: A and B
///
/// true_positives:
/// - foo: foobar
/// bar: foobar
/// foobar: foobar
///
/// true_negatives:
/// - foo: bar
/// bar: foo
/// foobar: barfoo
/// ```
///
/// Here is a slightly more complex rule example:
///
/// ```text
/// detection:
/// A:
/// all(phrase):
/// - "*quick*"
/// - "*brown*"
/// B:
/// phrase: ibear
///
/// condition: A and not B
///
/// true_positives:
/// - phrase: the quick brown fox
///
/// true_negatives:
/// - foo: the quick brown BEAR
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Rule {
#[serde(default)]
optimised: bool,
pub detection: Detection,
pub true_positives: Vec<Yaml>,
pub true_negatives: Vec<Yaml>,
}
impl Rule {
/// Load a rule from a YAML file.
pub fn load(path: &Path) -> crate::Result<Self> {
let contents = fs::read_to_string(path).map_err(crate::error::rule_invalid)?;
Self::from_str(&contents)
}
/// Load a rule from a YAML string.
pub fn from_str(s: &str) -> crate::Result<Self> {
serde_yaml::from_str(s).map_err(crate::error::rule_invalid)
}
/// Load a rule from a YAML Value.
pub fn from_value(value: serde_yaml::Value) -> crate::Result<Self> {
serde_yaml::from_value(value).map_err(crate::error::rule_invalid)
}
/// Optimise the rule with the optimisations provided.
pub fn optimise(mut self, options: Optimisations) -> Self {
if self.optimised {
return self;
}
if options.coalesce {
self.detection.expression =
optimiser::coalesce(self.detection.expression, &self.detection.identifiers);
self.detection.identifiers.clear();
}
if options.shake {
self.detection.expression = optimiser::shake(self.detection.expression);
self.detection.identifiers = self
.detection
.identifiers
.into_iter()
.map(|(k, v)| (k, optimiser::shake(v)))
.collect();
}
if options.rewrite {
self.detection.expression = optimiser::rewrite(self.detection.expression);
self.detection.identifiers = self
.detection
.identifiers
.into_iter()
.map(|(k, v)| (k, optimiser::rewrite(v)))
.collect();
}
if options.matrix {
self.detection.expression = optimiser::matrix(self.detection.expression);
self.detection.identifiers = self
.detection
.identifiers
.into_iter()
.map(|(k, v)| (k, optimiser::matrix(v)))
.collect();
}
self.optimised = true;
self
}
/// Evaluates the rule against the provided `Document`, returning true if it has matched.
#[inline]
pub fn matches(&self, document: &dyn Document) -> bool {
solver::solve(&self.detection, document)
}
/// Validates the rule's detection logic against the provided true positives and negatives.
pub fn validate(&self) -> crate::Result<bool> {
let mut errors = vec![];
for test in &self.true_positives {
if !(solver::solve(&self.detection, test.as_mapping().unwrap())) {
errors.push(format!(
"failed to validate true positive check '{:?}'",
test
));
}
}
for test in &self.true_negatives {
if solver::solve(&self.detection, test.as_mapping().unwrap()) {
errors.push(format!(
"failed to validate true negative check '{:?}'",
test
));
}
}
if !errors.is_empty() {
return Err(crate::Error::new(crate::error::Kind::Validation).with(errors.join(";")));
}
Ok(true)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rule() {
let rule = r#"
detection:
A:
foo: 'foo*'
bar: '*bar'
B:
foobar:
- foobar
- foobaz
condition: A and B
true_positives:
- foo: foobar
bar: foobar
foobar: foobar
true_negatives:
- foo: bar
bar: foo
foobar: barfoo
"#;
let rule = Rule::from_str(rule).unwrap();
assert_eq!(rule.validate().unwrap(), true);
}
}