Source code for sigma.processing.conditions.fields

from dataclasses import dataclass, field

from sigma.processing.conditions.base import FieldNameProcessingCondition
from typing import Literal
from sigma.policy.regex_engine import RegexPattern
from sigma.rule import SigmaDetectionItem
from sigma.exceptions import SigmaConfigurationError


[docs] @dataclass class IncludeFieldCondition(FieldNameProcessingCondition): """ Matches on field name if it is contained in fields list. The parameter 'mode' determines if field names are matched as plain string ("plain") or regular expressions ("re"). """ fields: list[str] mode: Literal["plain", "re"] = field(default="plain") patterns: list[RegexPattern] = field(init=False, repr=False, default_factory=list) def __post_init__(self) -> None: if self.mode == "plain": pass elif self.mode == "re": engine = self.resolve_regex_engine() compiled = [] for field_pattern in self.fields: try: compiled.append(engine.compile(field_pattern)) except engine.error as e: raise SigmaConfigurationError( f"Regular expression '{field_pattern}' in field name condition is invalid: {e}" ) from e self.patterns = compiled else: raise SigmaConfigurationError( f"Invalid field name matching mode '{self.mode}', supported types are 'plain' or 're'." )
[docs] def match_field_name( self, field: str | None, ) -> bool: if field is None: return False elif self.mode == "plain": return field in self.fields else: # regular expression matching try: return any((pattern.match(field) for pattern in self.patterns)) except Exception as e: msg = f" (while processing field '{field}'" if len(e.args) > 1: e.args = (e.args[0] + msg,) + e.args[1:] else: e.args = (e.args[0] + msg,) raise
[docs] @dataclass class ExcludeFieldCondition(IncludeFieldCondition): """Matches on field name if it is not contained in fields list."""
[docs] def match_field_name( self, field: str | None, ) -> bool: return not super().match_field_name(field)