From 803d3db0c9401683b7e92a3eb88d35549fbe51a2 Mon Sep 17 00:00:00 2001 From: cccs-cs <142235036+cccs-cs@users.noreply.github.com> Date: Wed, 10 Jul 2024 15:36:34 -0400 Subject: [PATCH] Fix issue-231 Only modify a copy of self.filter.condition[0] so that the filter can be applied to multiple rules. --- sigma/filters.py | 7 ++++--- tests/test_filters.py | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/sigma/filters.py b/sigma/filters.py index efb80962..8e383fdc 100644 --- a/sigma/filters.py +++ b/sigma/filters.py @@ -188,19 +188,20 @@ def apply_on_rule( if not self._should_apply_on_rule(rule): return rule + filter_condition = self.filter.condition[0] for original_cond_name, condition in self.filter.detections.items(): cond_name = "_filt_" + ("".join(random.choices(string.ascii_lowercase, k=10))) # Replace each instance of the original condition name with the new condition name to avoid conflicts - self.filter.condition[0] = re.sub( + filter_condition = re.sub( rf"[^ ]*{original_cond_name}[^ ]*", cond_name, - self.filter.condition[0], + filter_condition, ) rule.detection.detections[cond_name] = condition for i, condition in enumerate(rule.detection.condition): - rule.detection.condition[i] = f"({condition}) and " + f"({self.filter.condition[0]})" + rule.detection.condition[i] = f"({condition}) and " + f"({filter_condition})" # Reparse the rule to update the parsed conditions rule.detection.__post_init__() diff --git a/tests/test_filters.py b/tests/test_filters.py index eae3dac5..793c3247 100644 --- a/tests/test_filters.py +++ b/tests/test_filters.py @@ -1,3 +1,5 @@ +import copy +import uuid from pathlib import Path from typing import Callable @@ -133,6 +135,19 @@ def test_basic_filter_application_against_correlation_rule( ] +def test_filter_application_to_several_rules(sigma_filter, test_backend, rule_collection): + rule_copy = copy.deepcopy(rule_collection.rules[0]) + rule_copy.id = uuid.UUID("257f7780-ea6c-48d4-ae8e-2b95b3740d84") + sigma_filter.filter.rules.append(SigmaRuleReference(str(rule_copy.id))) + + rule_collection.rules.extend([rule_copy, sigma_filter]) + + assert ( + test_backend.convert(rule_collection) + == ['(EventID=4625 or EventID2=4624) and not User startswith "adm_"'] * 2 + ) + + def test_reducing_rule_collections(sigma_filter, test_backend, rule_collection): rule_collection.rules += [sigma_filter]