Source code for sigma.filters

from __future__ import annotations

import copy
import random
import re
import string
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, ClassVar

from typing import Self

from sigma import exceptions as sigma_exceptions
from sigma.correlations import SigmaCorrelationRule, SigmaRuleReference
from sigma.rule import SigmaDetection, SigmaDetections, SigmaLogSource, SigmaRule, SigmaRuleBase
from sigma.rule.logsource import EmptyLogSource

if TYPE_CHECKING:
    from sigma.exceptions import SigmaRuleLocation
    from sigma.policy import SigmaPolicy


[docs] @dataclass class SigmaGlobalFilter(SigmaDetections): """ The ``filter`` section of a Sigma filter: the detections and the condition of the filter and the references to the rules it applies to. :param rules: Rules the filter applies to. Either the string ``"any"`` to apply the filter to all rules matching the log source of the filter, or a list of references to rule IDs or names. """ rules: list[SigmaRuleReference] | str = field(default_factory=list)
[docs] @classmethod def from_dict( cls: type[Self], detections: dict[str, Any], source: SigmaRuleLocation | None = None, policy: "SigmaPolicy | None" = None, ) -> Self: """ Parse the ``filter`` section of a Sigma filter. The ``rules`` field is required. It can be ``any`` (case-insensitive), a single rule ID or name or a list of rule IDs or names. An empty list is treated like ``any``. All other keys except ``condition`` are parsed as detection definitions. :param detections: Content of the ``filter`` section. :param source: Location of the filter, used in error messages. :param policy: Policy used to parse the detections. :raises SigmaFilterConditionError: if the condition is missing or isn't a single string. :raises SigmaFilterRuleReferenceError: if the ``rules`` field is missing or invalid. :return: Parsed filter section. """ try: if isinstance(detections["condition"], str): condition = [detections["condition"]] else: raise sigma_exceptions.SigmaFilterConditionError( "Sigma filter condition must be a string", source=source ) except KeyError: raise sigma_exceptions.SigmaFilterConditionError( "Sigma filter must contain exactly one condition", source=source ) try: rules: list[SigmaRuleReference] | str if isinstance(detections["rules"], str): # Check if it's "any" keyword if detections["rules"].lower() == "any": rules = detections["rules"].lower() else: # Single rule reference rules = [SigmaRuleReference(detections["rules"])] elif isinstance(detections["rules"], list): # Empty list is treated as "any" if not detections["rules"]: rules = "any" else: rules = [SigmaRuleReference(detection) for detection in detections["rules"]] else: raise sigma_exceptions.SigmaFilterRuleReferenceError( "Sigma filter rules field must be 'any', a rule ID/name, or a list of rule IDs/names", source=source, ) except KeyError: # Rules field is required - must explicitly specify "any" or specific rule references raise sigma_exceptions.SigmaFilterRuleReferenceError( "Sigma filter must have a 'rules' field (use 'any' to apply to all rules matching the logsource)", source=source, ) return cls( detections={ name: SigmaDetection.from_definition(definition, source, policy) for name, definition in detections.items() if name not in ( "condition", "rules", ) # TODO Fix standard }, rules=rules, condition=condition, source=source, policy=policy, )
[docs] def to_dict(self: Self) -> dict[str, Any]: """Convert the filter section into a dict, with rule references as plain strings.""" d = super().to_dict() d.update( { "rules": ( self.rules if isinstance(self.rules, str) else [ref.reference for ref in self.rules] ), } ) return d
@dataclass class EmptySigmaGlobalFilter(SigmaGlobalFilter): """ Empty Sigma global filter used as a placeholder for error handling purposes. """ detections: dict[str, SigmaDetection] = field(default_factory=dict) condition: list[str] = field(default_factory=list) rules: list[SigmaRuleReference] | str = field(default_factory=list) def __post_init__(self: Self) -> None: # Skip all checks and initializations pass
[docs] @dataclass class SigmaFilter(SigmaRuleBase): """ A Sigma filter: a separate document that adds a condition to existing rules to tune them for an environment without changing the rules themselves, e.g. to exclude known-benign activity. A filter applies to a rule if the log source of the filter contains the log source of the rule and the rule is referenced in the ``rules`` field of the filter section (or ``rules`` is ``any``). Correlation rules aren't modified, but the rules they refer to are filtered like any other rule. See :meth:`apply_on_rule` for how a filter is merged into a rule. :param logsource: Log source the filter applies to. It may be less specific than the log sources of the rules it applies to. :param filter: Parsed ``filter`` section with the filter detections, condition and rule references. """ logsource: SigmaLogSource = field(default_factory=SigmaLogSource) filter: SigmaGlobalFilter = field( default_factory=lambda: SigmaGlobalFilter({}, []), )
[docs] @classmethod def from_dict( # type: ignore[override] cls: type[Self], sigma_filter: dict[str, Any], collect_errors: bool = False, source: SigmaRuleLocation | None = None, policy: "SigmaPolicy | None" = None, ) -> Self: """ Converts from a dictionary object to a SigmaFilter object. :param sigma_filter: Parsed YAML content of the filter. :param collect_errors: Collect errors in the ``errors`` attribute instead of raising the first one. :param source: Location of the filter, used in error messages. :param policy: Policy used to parse the filter. :raises SigmaLogsourceError: if the log source is missing or invalid. :raises SigmaFilterError: if the ``filter`` section is missing or isn't a map. :return: Parsed filter. """ kwargs, errors = super().from_dict_common_params( sigma_filter, collect_errors, source, policy=policy ) # parse log source try: filter_logsource = SigmaLogSource.from_dict(sigma_filter["logsource"], source) except KeyError: filter_logsource = EmptyLogSource() errors.append( sigma_exceptions.SigmaLogsourceError( "Sigma filter must have a log source", source=source ) ) except AttributeError: filter_logsource = EmptyLogSource() errors.append( sigma_exceptions.SigmaLogsourceError( "Sigma logsource must be a valid YAML map", source=source ) ) except sigma_exceptions.SigmaError as e: filter_logsource = EmptyLogSource() errors.append(e) # parse detections try: filter_global_filter = SigmaGlobalFilter.from_dict( sigma_filter["filter"], source, policy=policy ) except KeyError: filter_global_filter = EmptySigmaGlobalFilter() errors.append( sigma_exceptions.SigmaFilterError( "Sigma filter must have a filter defined", source=source ) ) except TypeError: filter_global_filter = EmptySigmaGlobalFilter() errors.append( sigma_exceptions.SigmaFilterError( "Sigma filter must be a dictionary", source=source ) ) except sigma_exceptions.SigmaError as e: filter_global_filter = EmptySigmaGlobalFilter() errors.append(e) if not collect_errors and errors: raise errors[0] return cls( logsource=filter_logsource, filter=filter_global_filter, errors=errors, **kwargs, )
[docs] def to_dict(self: Self) -> dict[str, Any]: """Convert filter object into dict.""" d = super().to_dict() d.update( { "logsource": self.logsource.to_dict(), "filter": self.filter.to_dict(), } ) return d
def _should_apply_on_rule(self: Self, rule: SigmaRule | SigmaCorrelationRule) -> bool: """Check if the filter applies to the given rule (see class documentation).""" from sigma.collection import SigmaCollection # Don't apply filters to correlation rules if isinstance(rule, SigmaCorrelationRule): return False # Check if logsource matches if rule.logsource not in self.logsource: return False # If rules is "any", apply to all rules matching the logsource if isinstance(self.filter.rules, str) and self.filter.rules.lower() == "any": return True # At this point, rules must be a list (not a string) assert isinstance(self.filter.rules, list) # For each rule ID/title in the filter.rules, add the rule to the reference using the resolve method, # then filter each reference to see if the rule is in the reference matches = [] for reference in self.filter.rules: try: matches.append(SigmaCollection([rule])[reference.reference]) except sigma_exceptions.SigmaRuleNotFoundError: pass if not matches: return False return True # Keywords that must not be prefixed when rewriting filter conditions. They are compared # case-sensitively, like in the condition grammar in sigma.conditions, where e.g. "NOT" is # an ordinary identifier and not the negation operator. _CONDITION_KEYWORDS: frozenset[str] = frozenset({"not", "and", "or", "all", "any", "of", "1"}) # A single condition token: a detection identifier or an identifier pattern. Mirrors the # character sets of ``identifier`` (alphanumerics, ``_`` and ``-``) and ``identifier_pattern`` # (the same characters plus ``*``) in sigma.conditions. Identifiers may start with any of # these characters, e.g. ``_filter`` or ``2nd_filter``. _CONDITION_TOKEN: ClassVar[re.Pattern[str]] = re.compile(r"[a-zA-Z0-9_*-]+")
[docs] def apply_on_rule( self: Self, rule: SigmaRule | SigmaCorrelationRule ) -> SigmaRule | SigmaCorrelationRule: """ Apply the filter on a rule if it applies to it. The filter detections are copied into the rule under names with a random prefix, so they can't collide with the detections of the rule, and each condition of the rule is replaced with ``(<rule condition>) and (<filter condition>)``. The filter condition is rewritten to the prefixed names. It can therefore only refer to detections of the filter, and ``them`` refers to all filter detections. :param rule: Rule the filter is applied to. It is modified in place. :return: The given rule, with the filter applied if it applies to the rule. """ if not self._should_apply_on_rule(rule) or isinstance(rule, SigmaCorrelationRule): return rule # Generate one random prefix shared by all filter identifiers in this application. # Using a single prefix (rather than a fresh random name per identifier) preserves # the structure of the original identifier names so that wildcard patterns in the # filter condition (e.g. "1 of selection_*") continue to work after renaming. prefix = "_filt_" + "".join(random.choices(string.ascii_lowercase, k=10)) # Rename every filter detection identifier with the shared prefix. Each rule gets its own # copy of the filter detections: processing pipelines modify detections in place, so a # detection object shared between rules would be transformed again for every rule. for original_cond_name, condition in self.filter.detections.items(): rule.detection.detections[prefix + "_" + original_cond_name] = copy.deepcopy(condition) # Rewrite the filter condition string so that every identifier/pattern token is # prefixed. This handles: # - exact names: "selection" -> "PREFIX_selection" # - suffix wildcards: "selection_*" -> "PREFIX_selection_*" # - prefix wildcards: "*_allow" -> "PREFIX_*_allow" # - the "them" keyword: "1 of them" -> "1 of PREFIX_*" # - leading "_"/digits: "_filter" -> "PREFIX__filter" # Sigma keywords (not, and, or, all, any, of, 1) are left unchanged. # # Each token is a maximal run of the characters allowed in Sigma identifiers and # identifier patterns (see _CONDITION_TOKEN). Wildcards are only valid at the start or # end of a Sigma identifier pattern but the regex accepts any occurrence; the Sigma # condition parser is responsible for rejecting syntactically invalid patterns at parse # time. def _replace_token(m: re.Match[str]) -> str: token = m.group(0) if token in self._CONDITION_KEYWORDS: return token if token == "them": # "them" means all detections; replace with a pattern that matches all # filter identifiers carrying the current prefix. return prefix + "_*" return prefix + "_" + token filter_condition = self._CONDITION_TOKEN.sub(_replace_token, self.filter.condition[0]) for i, condition_str in enumerate(rule.detection.condition): rule.detection.condition[i] = f"({condition_str}) and " + f"({filter_condition})" # Reparse the rule to update the parsed conditions rule.detection.__post_init__() return rule
[docs] @classmethod def from_yaml( cls: type[Self], rule: str, collect_errors: bool = False, policy: "SigmaPolicy | None" = None, ) -> Self: """Convert YAML input string with single document into SigmaFilter object.""" return super().from_yaml(rule, collect_errors, policy=policy)