From be3e034abff93ce062f834abfe6f19164d60f520 Mon Sep 17 00:00:00 2001 From: Thomas Patzke Date: Mon, 14 Oct 2024 22:08:15 +0200 Subject: [PATCH] Additional escape characters in SigmaString.to_regex() --- sigma/conversion/base.py | 2 +- sigma/types.py | 4 ++-- tests/test_types.py | 12 +++++++++--- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/sigma/conversion/base.py b/sigma/conversion/base.py index 8fc9a7b..3fc32e7 100644 --- a/sigma/conversion/base.py +++ b/sigma/conversion/base.py @@ -1340,7 +1340,7 @@ def convert_condition_field_eq_val_str( return expr.format( field=self.escape_and_quote_field(cond.field), value=self.convert_value_str(value, state), - regex=self.convert_value_re(value.to_regex(), state), + regex=self.convert_value_re(value.to_regex(self.add_escaped_re), state), backend=self, ) except TypeError: # pragma: no cover diff --git a/sigma/types.py b/sigma/types.py index e0ec69d..c465d3c 100644 --- a/sigma/types.py +++ b/sigma/types.py @@ -572,14 +572,14 @@ def convert( ) return s - def to_regex(self) -> "SigmaRegularExpression": + def to_regex(self, custom_escaped: str = "") -> "SigmaRegularExpression": """Convert SigmaString into a regular expression.""" return SigmaRegularExpression( self.convert( escape_char="\\", wildcard_multi=".*", wildcard_single=".", - add_escaped=".*+?^$[](){}\\|", + add_escaped=".*+?^$[](){}\\|" + custom_escaped, ) ) diff --git a/tests/test_types.py b/tests/test_types.py index 665edea..1ca55b6 100644 --- a/tests/test_types.py +++ b/tests/test_types.py @@ -389,16 +389,22 @@ def test_strings_convert_invalid_part(): def test_strings_to_regex(): - s = SigmaString("Test*Special?(Plain)[\\*\\?]") + s = SigmaString("Test*Special?(Plain)/[\\*\\?]") assert s.s == ( "Test", SpecialChars.WILDCARD_MULTI, "Special", SpecialChars.WILDCARD_SINGLE, - "(Plain)[*?]", + "(Plain)/[*?]", ) r = s.to_regex() - assert r.regexp == "Test.*Special.\\(Plain\\)\\[\\*\\?\\]" + assert r.regexp == "Test.*Special.\\(Plain\\)/\\[\\*\\?\\]" + + +def test_strings_to_regex_with_additional_escape_chars(): + s = SigmaString("Test*Special?(Plain)/[\\*\\?]") + r = s.to_regex("/") + assert r.regexp == "Test.*Special.\\(Plain\\)\\/\\[\\*\\?\\]" def test_string_index(sigma_string):