pySigma-backend-tenzir 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 DCSO Deutsche Cyber-Sicherheitsorganisation GmbH
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,171 @@
1
+ Metadata-Version: 2.4
2
+ Name: pySigma-backend-tenzir
3
+ Version: 0.1.0
4
+ Summary: pySigma tenzir backend
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Author: Hendrik Baecker
8
+ Author-email: hendrik.baecker@dcso.de
9
+ Requires-Python: >=3.11,<4.0
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Classifier: Programming Language :: Python :: 3.15
16
+ Requires-Dist: pysigma (>=2.2.0,<3.0.0)
17
+ Description-Content-Type: text/markdown
18
+
19
+ ![Tests](https://github.com/sigmahq/pySigma-backend-tenzir/actions/workflows/test.yml/badge.svg)
20
+ ![Coverage Badge](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/andurin/6c91f50b8a7980cfce8fb7b1b86c2862/raw/SigmaHQ-pySigma-backend-tenzir.json)
21
+ ![Status](https://img.shields.io/badge/Status-pre--release-orange)
22
+
23
+ # pySigma tenzir Backend
24
+
25
+ This is the Tenzir backend for pySigma. It provides the package `sigma.backends.tenzir` with the `TenzirTQL2Backend` class.
26
+
27
+ ## Usage
28
+
29
+ This backend can, like other pySigma backends, be used either with sigma-cli or in your own code.
30
+
31
+ ### Sigma CLI
32
+
33
+ ```bash
34
+ $ sigma convert -t tenzir_tql2 proc_creation_win_xwizard_execution_non_default_location.yml
35
+
36
+ Parsing Sigma rules [####################################] 100%
37
+
38
+ where (Image.to_lower().ends_with("\\xwizard.exe") or OriginalFileName.to_lower() == "xwizard.exe") and not (Image.to_lower().starts_with("c:\\windows\\system32\\") or Image.to_lower().starts_with("c:\\windows\\syswow64\\") or Image.to_lower().starts_with("c:\\windows\\winsxs\\"))
39
+ ```
40
+
41
+ ### Python Programmatic
42
+
43
+ ```python
44
+ from pathlib import Path
45
+ from sigma.backends.tenzir.tenzir_tql2 import TenzirTQL2Backend
46
+ from sigma.collection import SigmaCollection
47
+ from sigma.processing.resolver import ProcessingPipelineResolver
48
+
49
+ # Load rule file
50
+ sigma_rule_yaml = Path("proc_creation_win_xwizard_execution_non_default_location.yml").read_text()
51
+
52
+ # Create a Piperesolver instance for Sigma Processing Pipelines
53
+ piperesolver = ProcessingPipelineResolver()
54
+
55
+ # Add pipelines as needed to the resolver
56
+ # piperesolver.add_pipeline_class(sysmon_pipeline())
57
+
58
+ # Create Tenzir Backend instance
59
+ backend = TenzirTQL2Backend(resolved_pipeline)
60
+
61
+ # Load rule content as SigmaCollection
62
+ rules = SigmaCollection.from_yaml(sigma_rule_yaml)
63
+
64
+ # Let the backend convert the rule(s)
65
+ converted_rules = backend.convert(rules)
66
+
67
+ print(converted_rules)
68
+ ```
69
+
70
+ ## Value Types
71
+
72
+ The backend keeps the types of the Sigma rule and follows Tenzir's default typing.
73
+ Any type conversion of the data belongs in a preceding pipeline, not in the backend.
74
+
75
+ | Sigma value | Generated TQL |
76
+ |---|---|
77
+ | number (`4624`) | compared as number, never lowercased: `EventID == 4624` |
78
+ | string (`'4624'`, `foo`) | compared as string, case-insensitive via `to_lower()` |
79
+ | IPv4/IPv6 address (`192.168.1.1`, `::1`) | unquoted `ip` literal: `src_ip == 192.168.1.1` |
80
+ | `\|cidr` | `src_ip in 10.0.0.0/8` |
81
+
82
+ Lists with mixed types are split by type, e.g. `[4624, 'abc']` becomes
83
+ `(EventID == 4624 or EventID_lower == "abc")`.
84
+
85
+ IP detection uses only pure string parsing from Python's standard library
86
+ (`ipaddress`). No sockets, DNS or network access of any kind is performed.
87
+ Strings that only look like addresses (e.g. the version `2.4.31.566`) stay strings.
88
+ If a field is stored as a string in Tenzir but the rule contains an IP address, normalize
89
+ the field in a preceding pipeline, otherwise the comparison will not match.
90
+
91
+ ## Advanced Configuration
92
+
93
+ ### Field Existence Checks
94
+
95
+ The backend supports automatic field existence checks to ensure that fields exist (are not null) before checking their values. This is useful to avoid matching on undefined fields.
96
+
97
+ #### Enable Field Null Checks
98
+
99
+ By default, field null checks are disabled for backward compatibility. To enable them:
100
+
101
+ ```python
102
+ from sigma.backends.tenzir.tenzir_tql2 import TenzirTQL2Backend
103
+
104
+ backend = TenzirTQL2Backend()
105
+ backend.add_field_null_check = True
106
+
107
+ # Now all field-to-value conversions will include NOT NULL checks
108
+ ```
109
+
110
+ #### Behavior
111
+
112
+ When enabled, the backend automatically generates null existence checks for all unique fields used in the query. The checks are:
113
+
114
+ 1. **Deduplicated**: Each field is checked only once, even if it appears multiple times in the detection rule
115
+ 2. **Separated**: Null checks are output as separate `where` line before the main query
116
+ 3. **Sorted**: Fields are sorted alphabetically for consistent output
117
+
118
+ **Example:**
119
+
120
+ Input Sigma rule:
121
+ ```yaml
122
+ detection:
123
+ sel:
124
+ EventID: 4624
125
+ ProcessName: "cmd.exe"
126
+ condition: sel
127
+ ```
128
+
129
+ Generated output:
130
+ ```
131
+ where EventID != null and ProcessName != null
132
+ where EventID == 4624 and ProcessName.to_lower() == "cmd.exe"
133
+ ```
134
+
135
+ This ensures that:
136
+ - EventID field must exist and equal 4624
137
+ - ProcessName field must exist and equal "cmd.exe"
138
+ - Records are only matched if both conditions are true
139
+
140
+ #### With Repeated Fields
141
+
142
+ The null checks are automatically deduplicated when the same field appears multiple times:
143
+
144
+ Input Sigma rule:
145
+ ```yaml
146
+ detection:
147
+ sel:
148
+ EventID:
149
+ - 4624
150
+ - 4625
151
+ condition: sel
152
+ ```
153
+
154
+ Generated output:
155
+ ```
156
+ where EventID != null
157
+ where EventID in [4624, 4625]
158
+ ```
159
+
160
+ Note: The null check for `EventID` appears only once, not twice, even though it's referenced twice in the rule.
161
+
162
+ # Maintainer
163
+
164
+ This backend is currently maintained by:
165
+
166
+ * [Hendrik Baecker](https://github.com/andurin/)
167
+
168
+ # Copyright
169
+
170
+ Copyright (c) 2024-2026 DCSO GmbH
171
+
@@ -0,0 +1,152 @@
1
+ ![Tests](https://github.com/sigmahq/pySigma-backend-tenzir/actions/workflows/test.yml/badge.svg)
2
+ ![Coverage Badge](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/andurin/6c91f50b8a7980cfce8fb7b1b86c2862/raw/SigmaHQ-pySigma-backend-tenzir.json)
3
+ ![Status](https://img.shields.io/badge/Status-pre--release-orange)
4
+
5
+ # pySigma tenzir Backend
6
+
7
+ This is the Tenzir backend for pySigma. It provides the package `sigma.backends.tenzir` with the `TenzirTQL2Backend` class.
8
+
9
+ ## Usage
10
+
11
+ This backend can, like other pySigma backends, be used either with sigma-cli or in your own code.
12
+
13
+ ### Sigma CLI
14
+
15
+ ```bash
16
+ $ sigma convert -t tenzir_tql2 proc_creation_win_xwizard_execution_non_default_location.yml
17
+
18
+ Parsing Sigma rules [####################################] 100%
19
+
20
+ where (Image.to_lower().ends_with("\\xwizard.exe") or OriginalFileName.to_lower() == "xwizard.exe") and not (Image.to_lower().starts_with("c:\\windows\\system32\\") or Image.to_lower().starts_with("c:\\windows\\syswow64\\") or Image.to_lower().starts_with("c:\\windows\\winsxs\\"))
21
+ ```
22
+
23
+ ### Python Programmatic
24
+
25
+ ```python
26
+ from pathlib import Path
27
+ from sigma.backends.tenzir.tenzir_tql2 import TenzirTQL2Backend
28
+ from sigma.collection import SigmaCollection
29
+ from sigma.processing.resolver import ProcessingPipelineResolver
30
+
31
+ # Load rule file
32
+ sigma_rule_yaml = Path("proc_creation_win_xwizard_execution_non_default_location.yml").read_text()
33
+
34
+ # Create a Piperesolver instance for Sigma Processing Pipelines
35
+ piperesolver = ProcessingPipelineResolver()
36
+
37
+ # Add pipelines as needed to the resolver
38
+ # piperesolver.add_pipeline_class(sysmon_pipeline())
39
+
40
+ # Create Tenzir Backend instance
41
+ backend = TenzirTQL2Backend(resolved_pipeline)
42
+
43
+ # Load rule content as SigmaCollection
44
+ rules = SigmaCollection.from_yaml(sigma_rule_yaml)
45
+
46
+ # Let the backend convert the rule(s)
47
+ converted_rules = backend.convert(rules)
48
+
49
+ print(converted_rules)
50
+ ```
51
+
52
+ ## Value Types
53
+
54
+ The backend keeps the types of the Sigma rule and follows Tenzir's default typing.
55
+ Any type conversion of the data belongs in a preceding pipeline, not in the backend.
56
+
57
+ | Sigma value | Generated TQL |
58
+ |---|---|
59
+ | number (`4624`) | compared as number, never lowercased: `EventID == 4624` |
60
+ | string (`'4624'`, `foo`) | compared as string, case-insensitive via `to_lower()` |
61
+ | IPv4/IPv6 address (`192.168.1.1`, `::1`) | unquoted `ip` literal: `src_ip == 192.168.1.1` |
62
+ | `\|cidr` | `src_ip in 10.0.0.0/8` |
63
+
64
+ Lists with mixed types are split by type, e.g. `[4624, 'abc']` becomes
65
+ `(EventID == 4624 or EventID_lower == "abc")`.
66
+
67
+ IP detection uses only pure string parsing from Python's standard library
68
+ (`ipaddress`). No sockets, DNS or network access of any kind is performed.
69
+ Strings that only look like addresses (e.g. the version `2.4.31.566`) stay strings.
70
+ If a field is stored as a string in Tenzir but the rule contains an IP address, normalize
71
+ the field in a preceding pipeline, otherwise the comparison will not match.
72
+
73
+ ## Advanced Configuration
74
+
75
+ ### Field Existence Checks
76
+
77
+ The backend supports automatic field existence checks to ensure that fields exist (are not null) before checking their values. This is useful to avoid matching on undefined fields.
78
+
79
+ #### Enable Field Null Checks
80
+
81
+ By default, field null checks are disabled for backward compatibility. To enable them:
82
+
83
+ ```python
84
+ from sigma.backends.tenzir.tenzir_tql2 import TenzirTQL2Backend
85
+
86
+ backend = TenzirTQL2Backend()
87
+ backend.add_field_null_check = True
88
+
89
+ # Now all field-to-value conversions will include NOT NULL checks
90
+ ```
91
+
92
+ #### Behavior
93
+
94
+ When enabled, the backend automatically generates null existence checks for all unique fields used in the query. The checks are:
95
+
96
+ 1. **Deduplicated**: Each field is checked only once, even if it appears multiple times in the detection rule
97
+ 2. **Separated**: Null checks are output as separate `where` line before the main query
98
+ 3. **Sorted**: Fields are sorted alphabetically for consistent output
99
+
100
+ **Example:**
101
+
102
+ Input Sigma rule:
103
+ ```yaml
104
+ detection:
105
+ sel:
106
+ EventID: 4624
107
+ ProcessName: "cmd.exe"
108
+ condition: sel
109
+ ```
110
+
111
+ Generated output:
112
+ ```
113
+ where EventID != null and ProcessName != null
114
+ where EventID == 4624 and ProcessName.to_lower() == "cmd.exe"
115
+ ```
116
+
117
+ This ensures that:
118
+ - EventID field must exist and equal 4624
119
+ - ProcessName field must exist and equal "cmd.exe"
120
+ - Records are only matched if both conditions are true
121
+
122
+ #### With Repeated Fields
123
+
124
+ The null checks are automatically deduplicated when the same field appears multiple times:
125
+
126
+ Input Sigma rule:
127
+ ```yaml
128
+ detection:
129
+ sel:
130
+ EventID:
131
+ - 4624
132
+ - 4625
133
+ condition: sel
134
+ ```
135
+
136
+ Generated output:
137
+ ```
138
+ where EventID != null
139
+ where EventID in [4624, 4625]
140
+ ```
141
+
142
+ Note: The null check for `EventID` appears only once, not twice, even though it's referenced twice in the rule.
143
+
144
+ # Maintainer
145
+
146
+ This backend is currently maintained by:
147
+
148
+ * [Hendrik Baecker](https://github.com/andurin/)
149
+
150
+ # Copyright
151
+
152
+ Copyright (c) 2024-2026 DCSO GmbH
@@ -0,0 +1,52 @@
1
+ [project]
2
+ name = "pySigma-backend-tenzir"
3
+ version = "0.1.0"
4
+ description = "pySigma tenzir backend"
5
+ readme = "README.md"
6
+ authors = [
7
+ {name = "Hendrik Baecker",email = "hendrik.baecker@dcso.de"}
8
+ ]
9
+ license = "MIT"
10
+ repository = "https://github.com/dcso/pySigma-backend-tenzir"
11
+ dependencies = [
12
+ "pysigma (>=2.2.0,<3.0.0)"
13
+ ]
14
+ requires-python = ">=3.11,<4.0"
15
+
16
+
17
+ [tool.poetry]
18
+ packages = [
19
+ { include = "sigma" }
20
+ ]
21
+
22
+
23
+ [tool.poetry.group.test.dependencies]
24
+ pytest = ">=9.2.0,<10.0"
25
+ pytest-cov = ">=4,<8"
26
+ coverage = ">=7.15.4,<8.0.0"
27
+
28
+
29
+ [tool.poetry.group.dev.dependencies]
30
+ sigma-cli = "^4.0.0"
31
+ black = "^26.3.1"
32
+
33
+
34
+
35
+ [build-system]
36
+ requires = ["poetry-core>=1.0.0"]
37
+ build-backend = "poetry.core.masonry.api"
38
+
39
+
40
+ [tool.black]
41
+ line-length = 100
42
+
43
+ [tool.pytest.ini_options]
44
+ minversion = "6.0"
45
+ python_files = "test_*.py"
46
+ addopts = "-vv --cov=sigma --cov-report term --cov-report xml:cov.xml"
47
+ testpaths = [
48
+ "tests",
49
+ ]
50
+ filterwarnings = [
51
+ 'ignore:Unverified HTTPS request'
52
+ ]
@@ -0,0 +1,4 @@
1
+ # DCSO - pySigma-backend-tenzir
2
+ # Copyright (c) 2024-2026 DCSO GmbH
3
+
4
+ from .tenzir_tql2 import TenzirTQL2Backend
@@ -0,0 +1,773 @@
1
+ # DCSO - pySigma-backend-tenzir
2
+ # Copyright (c) 2024-2026 DCSO GmbH
3
+
4
+ import ipaddress
5
+ import re
6
+ from re import Pattern
7
+ from typing import Any, ClassVar, cast
8
+
9
+ from sigma.conditions import (
10
+ ConditionAND,
11
+ ConditionFieldEqualsValueExpression,
12
+ ConditionItem,
13
+ ConditionNOT,
14
+ ConditionOR,
15
+ )
16
+ from sigma.conversion.base import TextQueryBackend
17
+ from sigma.conversion.deferred import DeferredQueryExpression
18
+ from sigma.conversion.state import ConversionState
19
+ from sigma.rule import SigmaRule
20
+ from sigma.types import (
21
+ CompareOperators,
22
+ SigmaRegularExpressionFlag,
23
+ SigmaString,
24
+ )
25
+
26
+
27
+ class TenzirTQL2Backend(TextQueryBackend):
28
+ """Tenzir TQL2 backend."""
29
+
30
+ # Operator precedence: tuple of Condition{AND,OR,NOT} in order of precedence.
31
+ # The backend generates grouping if required
32
+ name: ClassVar[str] = "Tenzir TQL2"
33
+ formats: ClassVar[dict[str, str]] = {
34
+ "default": "Tenzir TQL2 queries",
35
+ }
36
+ requires_pipeline: ClassVar[bool] = (
37
+ # TODO: does the backend requires that a processing pipeline is provided?
38
+ # This information can be used by user interface programs like Sigma CLI
39
+ # to warn users about inappropriate usage of the backend.
40
+ False
41
+ )
42
+
43
+ precedence: ClassVar[tuple[type[ConditionItem], type[ConditionItem], type[ConditionItem]]] = (
44
+ ConditionNOT,
45
+ ConditionAND,
46
+ ConditionOR,
47
+ )
48
+ group_expression: ClassVar[str | None] = (
49
+ "({expr})" # Expression for precedence override grouping as format string with {expr} placeholder
50
+ )
51
+
52
+ # Generated query tokens
53
+ token_separator: str = " " # separator inserted between all boolean operators
54
+ or_token: ClassVar[str] = "or"
55
+ and_token: ClassVar[str] = "and"
56
+ not_token: ClassVar[str] = "not"
57
+ eq_token: ClassVar[str] = " == " # Token inserted between field and value (without separator)
58
+
59
+ # String output
60
+ ## Fields
61
+ ### Quoting
62
+ # field_quote: ClassVar[str] = (
63
+ # "'" # Character used to quote field characters if field_quote_pattern matches (or not, depending on field_quote_pattern_negation). No field name quoting is done if not set.
64
+ # )
65
+ # field_quote_pattern: ClassVar[Pattern] = re.compile(
66
+ # "^\\w+$"
67
+ # ) # Quote field names if this pattern (doesn't) matches, depending on field_quote_pattern_negation. Field name is always quoted if pattern is not set.
68
+ # field_quote_pattern_negation: ClassVar[bool] = (
69
+ # True # Negate field_quote_pattern result. Field name is quoted if pattern doesn't matches if set to True (default).
70
+ # )
71
+
72
+ ### Escaping
73
+ field_escape: ClassVar[str | None] = (
74
+ "\\" # Character to escape particular parts defined in field_escape_pattern.
75
+ )
76
+ field_escape_quote: ClassVar[bool] = True # Escape quote string defined in field_quote
77
+ field_escape_pattern: ClassVar[Pattern | None] = re.compile(
78
+ "\\s"
79
+ ) # All matches of this pattern are prepended with the string contained in field_escape.
80
+
81
+ ## Values
82
+ str_quote: ClassVar[str] = '"' # string quoting character (added as escaping character)
83
+ escape_char: ClassVar[str | None] = (
84
+ "\\" # Escaping character for special characters inside string
85
+ )
86
+ wildcard_multi: ClassVar[str | None] = "*" # Character used as multi-character wildcard
87
+ wildcard_single: ClassVar[str | None] = "*" # Character used as single-character wildcard
88
+ add_escaped: ClassVar[str] = "\\" # Characters quoted in addition to wildcards and string quote
89
+ filter_chars: ClassVar[str] = "" # Characters filtered
90
+ bool_values: ClassVar[dict[bool, str | None]] = { # Values to which boolean values are mapped.
91
+ True: "true",
92
+ False: "false",
93
+ }
94
+
95
+ # String matching operators. if none is appropriate eq_token is used.
96
+ startswith_expression: ClassVar[str | None] = "{field}.starts_with({value}, ignore_case=true)"
97
+ endswith_expression: ClassVar[str | None] = "{field}.ends_with({value}, ignore_case=true)"
98
+ contains_expression: ClassVar[str | None] = "{value} in {field}"
99
+ wildcard_match_expression: ClassVar[str | None] = (
100
+ "{field}.match_regex({value})" # Special expression if wildcards can't be matched with the eq_token operator
101
+ )
102
+
103
+ # Regular expressions
104
+ # Regular expression query as format string with placeholders {field}, {regex}, {flag_x} where x
105
+ # is one of the flags shortcuts supported by Sigma (currently i, m and s) and refers to the
106
+ # token stored in the class variable re_flags.
107
+ re_expression: ClassVar[str | None] = '{field}.match_regex("(?i:{regex})")'
108
+ re_escape_char: ClassVar[str] = "\\" # Character used for escaping in regular expressions
109
+ re_escape: ClassVar[list[str]] = [] # List of strings that are escaped
110
+ re_escape_escape_char: bool = True # If True, the escape character is also escaped
111
+ re_flag_prefix: bool = (
112
+ True # If True, the flags are prepended as (?x) group at the beginning of the regular expression, e.g. (?i). If this is not supported by the target, it should be set to False.
113
+ )
114
+ # Mapping from SigmaRegularExpressionFlag values to static string templates that are used in
115
+ # flag_x placeholders in re_expression template.
116
+ # By default, i, m and s are defined. If a flag is not supported by the target query language,
117
+ # remove it from re_flags or don't define it to ensure proper error handling in case of appearance.
118
+ re_flags: dict[SigmaRegularExpressionFlag, str] = (
119
+ { # noqa: RUF012 (not a ClassVar in the base class)
120
+ SigmaRegularExpressionFlag.IGNORECASE: "i",
121
+ SigmaRegularExpressionFlag.MULTILINE: "m",
122
+ SigmaRegularExpressionFlag.DOTALL: "s",
123
+ }
124
+ )
125
+
126
+ # Case sensitive string matching expression. String is quoted/escaped like a normal string.
127
+ # Placeholders {field} and {value} are replaced with field name and quoted/escaped string.
128
+ case_sensitive_match_expression: ClassVar[str | None] = "{field} == {value}"
129
+ # Case sensitive string matching operators similar to standard string matching. If not provided,
130
+ # case_sensitive_match_expression is used.
131
+ case_sensitive_startswith_expression: ClassVar[str | None] = "{field}.starts_with({value})"
132
+ case_sensitive_endswith_expression: ClassVar[str | None] = "{field}.ends_with({value})"
133
+ case_sensitive_contains_expression: ClassVar[str | None] = "{field}.contains({value})"
134
+
135
+ # CIDR expressions: define CIDR matching if backend has native support. Else pySigma expands
136
+ # CIDR values into string wildcard matches.
137
+ cidr_expression: ClassVar[str | None] = (
138
+ "{field} in {value}" # CIDR expression query as format string with placeholders {field}, {value} (the whole CIDR value), {network} (network part only), {prefixlen} (length of network mask prefix) and {netmask} (CIDR network mask only).
139
+ )
140
+
141
+ # Numeric comparison operators
142
+ compare_op_expression: ClassVar[str | None] = (
143
+ "{field}{operator}{value}" # Compare operation query as format string with placeholders {field}, {operator} and {value}
144
+ )
145
+ # Mapping between CompareOperators elements and strings used as replacement for {operator} in compare_op_expression
146
+ compare_operators: ClassVar[dict[CompareOperators, str] | None] = {
147
+ CompareOperators.LT: "<",
148
+ CompareOperators.LTE: "<=",
149
+ CompareOperators.GT: ">",
150
+ CompareOperators.GTE: ">=",
151
+ }
152
+
153
+ # Expression for comparing two event fields
154
+ field_equals_field_expression: ClassVar[str | None] = (
155
+ "{field1} == {field2}" # Field comparison expression with the placeholders {field1} and {field2} corresponding to left field and right value side of Sigma detection item
156
+ )
157
+ field_equals_field_escaping_quoting: tuple[bool, bool] = (
158
+ False,
159
+ False,
160
+ ) # If regular field-escaping/quoting is applied to field1 and field2. A custom escaping/quoting can be implemented in the convert_condition_field_eq_field_escape_and_quote method.
161
+
162
+ # Null/None expressions
163
+ field_null_expression: ClassVar[str | None] = (
164
+ "{field} == null" # Expression for field has null value as format string with {field} placeholder for field name
165
+ )
166
+
167
+ # Field existence condition expressions.
168
+ field_exists_expression: ClassVar[str | None] = (
169
+ 'this.has("{field}")' # Expression for field existence as format string with {field} placeholder for field name
170
+ )
171
+ field_not_exists_expression: ClassVar[str | None] = (
172
+ 'not this.has("{field}")' # Expression for field non-existence as format string with {field} placeholder for field name. If not set, field_exists_expression is negated with boolean NOT.
173
+ )
174
+
175
+ # Field value in list, e.g. "field in (value list)" or "field containsall (value list)"
176
+ convert_or_as_in: ClassVar[bool] = True # Convert OR as in-expression
177
+ convert_and_as_in: ClassVar[bool] = True # Convert AND as in-expression
178
+ in_expressions_allow_wildcards: ClassVar[bool] = (
179
+ False # Values in list can contain wildcards. If set to False (default) only plain values are converted into in-expressions.
180
+ )
181
+ field_in_list_expression: ClassVar[str | None] = (
182
+ "{field} {op} [{list}]" # Expression for field in list of values as format string with placeholders {field}, {op} and {list}
183
+ )
184
+ or_in_operator: ClassVar[str | None] = (
185
+ "in" # Operator used to convert OR into in-expressions. Must be set if convert_or_as_in is set
186
+ )
187
+ and_in_operator: ClassVar[str | None] = (
188
+ "contains-all" # Operator used to convert AND into in-expressions. Must be set if convert_and_as_in is set
189
+ )
190
+ list_separator: ClassVar[str | None] = ", " # List element separator
191
+
192
+ # Value not bound to a field
193
+ unbound_value_str_expression: ClassVar[str | None] = (
194
+ '"{value}"' # Expression for string value not bound to a field as format string with placeholder {value}
195
+ )
196
+ unbound_value_num_expression: ClassVar[str | None] = (
197
+ "{value}" # Expression for number value not bound to a field as format string with placeholder {value}
198
+ )
199
+ unbound_value_re_expression: ClassVar[str | None] = (
200
+ "_=~{value}" # Expression for regular expression not bound to a field as format string with placeholder {value} and {flag_x} as described for re_expression
201
+ )
202
+
203
+ # Correlations
204
+ correlation_methods: ClassVar[dict[str, str] | None] = {
205
+ "stats": "Correlation with 'every' command",
206
+ }
207
+ default_correlation_method: ClassVar[str] = "stats"
208
+ default_correlation_query: ClassVar[dict[str, str] | None] = {
209
+ "stats": "{search}\n{aggregate}\n{condition}"
210
+ }
211
+ temporal_correlation_query: ClassVar[dict[str, str] | None] = {
212
+ "stats": "{search}\n{typing}\n{aggregate}\n{condition}"
213
+ }
214
+
215
+ correlation_search_single_rule_expression: ClassVar[str | None] = "{query}"
216
+ correlation_search_multi_rule_expression: ClassVar[str | None] = "{queries}"
217
+ correlation_search_multi_rule_query_expression: ClassVar[str | None] = "({query})"
218
+ correlation_search_multi_rule_query_expression_joiner: ClassVar[str | None] = " or "
219
+
220
+ typing_expression: ClassVar[str | None] = "| eval event_type=case({queries})"
221
+ typing_rule_query_expression: ClassVar[str | None] = '{query}, "{ruleid}"'
222
+ typing_rule_query_expression_joiner: ClassVar[str | None] = ", "
223
+
224
+ # not yet supported for tenzir because all queries from correlated rules are combined into one query.
225
+ # correlation_search_field_normalization_expression: ClassVar[str] = " | rename {field} as {alias}"
226
+ # correlation_search_field_normalization_expression_joiner: ClassVar[str] = ""
227
+
228
+ event_count_aggregation_expression: ClassVar[dict[str, str] | None] = {"stats": """
229
+ every {timespan} {{
230
+ ts = round(time, {timespan})
231
+ summarize ts, event_count=count_distinct({field}), {groupby}
232
+ }}
233
+ """}
234
+ value_count_aggregation_expression: ClassVar[dict[str, str] | None] = {"stats": """
235
+ every {timespan} {{
236
+ ts = round(time, {timespan})
237
+ summarize ts, aggr_field=distinct({field}){groupby}
238
+ }}
239
+ """}
240
+ temporal_aggregation_expression: ClassVar[dict[str, str] | None] = {
241
+ "stats": "| eval timebucket=date_trunc({timespan}, @timestamp) | stats event_type_count=count_distinct(event_type){groupby}"
242
+ }
243
+
244
+ timespan_mapping: ClassVar[dict[str, str] | None] = {
245
+ "s": "s",
246
+ "m": "min",
247
+ "h": "h",
248
+ "d": "d",
249
+ "w": "w",
250
+ "M": "mo",
251
+ "y": "y",
252
+ }
253
+
254
+ referenced_rules_expression: ClassVar[dict[str, str] | None] = {"stats": "{ruleid}"}
255
+ referenced_rules_expression_joiner: ClassVar[dict[str, str] | None] = {"stats": ","}
256
+
257
+ groupby_expression_nofield: ClassVar = {"stats": " "}
258
+ groupby_expression: ClassVar[dict[str, str] | None] = {"stats": "{fields}"}
259
+ groupby_field_expression: ClassVar[dict[str, str] | None] = {"stats": "{field}"}
260
+ groupby_field_expression_joiner: ClassVar[dict[str, str] | None] = {"stats": ", "}
261
+
262
+ event_count_condition_expression: ClassVar[dict[str, str] | None] = {
263
+ "stats": "where event_count {op} {count}"
264
+ }
265
+ value_count_condition_expression: ClassVar[dict[str, str] | None] = {
266
+ "stats": "where length(aggr_field) {op} {count}"
267
+ }
268
+ temporal_condition_expression: ClassVar[dict[str, str] | None] = {
269
+ "stats": "where event_type_count {op} {count}"
270
+ }
271
+
272
+ # Query finalization: appending and concatenating deferred query part
273
+ deferred_start: ClassVar[str | None] = (
274
+ "\n| " # String used as separator between main query and deferred parts
275
+ )
276
+ deferred_separator: ClassVar[str | None] = (
277
+ "\n| " # String used to join multiple deferred query parts
278
+ )
279
+ deferred_only_query: ClassVar[str] = (
280
+ "*" # String used as query if final query only contains deferred expression
281
+ )
282
+
283
+ # Enable field existence checks for all field-to-value conversions
284
+ # add_field_null_check: ClassVar[bool] = False
285
+ add_field_null_check: ClassVar[bool] = True
286
+
287
+ @staticmethod
288
+ def _null_checked_fields(state: ConversionState) -> set[str]:
289
+ """Return the per-rule set of fields that need a null check (created on first use)."""
290
+ # processing_state is typed as Mapping but is a plain dict at runtime
291
+ processing_state = cast(dict[str, Any], state.processing_state)
292
+ return processing_state.setdefault("tenzir_null_checked_fields", set())
293
+
294
+ def _track_field_for_null_check(self, field: str, state: ConversionState) -> None:
295
+ """
296
+ Tracks a field name for null checks to be applied in finalize_query_default().
297
+ This ensures each field is checked for null only once, even if it appears multiple times.
298
+
299
+ Example:
300
+ Input fields: EventID, EventID, ProcessName
301
+ Deduplicated: EventID, ProcessName
302
+ Output: where EventID != null
303
+ where ProcessName != null
304
+ where <main_query>
305
+ """
306
+ if not self.add_field_null_check or isinstance(state, DeferredQueryExpression):
307
+ return
308
+
309
+ if "to_lower()" in field:
310
+ # Extract original field name without .to_lower() for tracking
311
+ field = field.replace(".to_lower()", "")
312
+
313
+ # Add field to set (automatically deduplicates)
314
+ self._null_checked_fields(state).add(field)
315
+
316
+ def _is_endswith_expression(self, arg: ConditionFieldEqualsValueExpression) -> bool:
317
+ """Check if an argument is an endswith expression (value starts with wildcard)."""
318
+ if not isinstance(arg.value, SigmaString):
319
+ return False
320
+ from sigma.types import SpecialChars
321
+
322
+ return (
323
+ arg.value.startswith(SpecialChars.WILDCARD_MULTI)
324
+ and not arg.value[1:].contains_special()
325
+ )
326
+
327
+ def _optimize_endswith_list(
328
+ self,
329
+ cond: ConditionOR,
330
+ state: ConversionState,
331
+ ) -> str | DeferredQueryExpression | None:
332
+ """
333
+ Optimize multiple endswith expressions for the same field into a single regex.
334
+ Returns None if optimization cannot be applied.
335
+ """
336
+ # Check all args are endswith expressions for the same field
337
+ args = [arg for arg in cond.args if isinstance(arg, ConditionFieldEqualsValueExpression)]
338
+ if not args or len(args) != len(cond.args):
339
+ return None
340
+
341
+ # Get the field from the first arg
342
+ field = args[0].field
343
+
344
+ # Check all args reference the same field and are endswith expressions
345
+ for arg in args:
346
+ if arg.field != field or not self._is_endswith_expression(arg):
347
+ return None
348
+
349
+ # All checks passed - we can optimize into a regex
350
+ # Extract suffixes (removing leading wildcard)
351
+ def re2_escape(s: str) -> str:
352
+ result = []
353
+ for ch in s:
354
+ if ch == "\\":
355
+ result.append("\\\\\\\\")
356
+ elif ch in r"^$*+?()[]{}|":
357
+ result.append("\\" + ch)
358
+ else:
359
+ result.append(ch)
360
+ return "".join(result)
361
+
362
+ suffixes = []
363
+ for arg in args:
364
+ # _is_endswith_expression guarantees a SigmaString value
365
+ suffix = cast(SigmaString, arg.value)[1:]
366
+ suffix_str = str(suffix)
367
+ escaped = re2_escape(suffix_str)
368
+ suffixes.append(escaped)
369
+
370
+ # Build regex pattern: matches any of the suffixes at end
371
+ pattern = f"({'|'.join(suffixes)})$"
372
+
373
+ # Track field for null checks
374
+ self._track_field_for_null_check(field, state)
375
+
376
+ # Apply to_lower to field if not already present
377
+ if ".to_lower()" not in field:
378
+ field = f"{field}.to_lower()"
379
+
380
+ # Return match_regex expression
381
+ return f'{field}?.match_regex("(?i){pattern}")'
382
+
383
+ def convert_condition_or(
384
+ self, cond: ConditionOR, state: ConversionState
385
+ ) -> str | DeferredQueryExpression | None:
386
+ """
387
+ Override to optimize endswith list into regex.
388
+ Falls back to default behavior if optimization doesn't apply.
389
+ """
390
+ # Try to optimize endswith list into regex
391
+ optimized = self._optimize_endswith_list(cond, state)
392
+ if optimized is not None:
393
+ return optimized
394
+
395
+ # Fall back to default OR conversion
396
+ return super().convert_condition_or(cond, state)
397
+
398
+ @staticmethod
399
+ def _ip_literal(value: object) -> str | None:
400
+ """Return a TQL IP literal if the value is a plain IPv4/IPv6 address string.
401
+
402
+ Tenzir parses ``192.168.1.1`` as an ip, so it is emitted unquoted and is never
403
+ lowercased. Only pure string parsing (stdlib ``ipaddress``) is used here; no
404
+ network access, sockets or DNS lookups are ever performed. Strings that merely
405
+ look like addresses (e.g. versions such as ``2.4.31.566``) are rejected.
406
+ """
407
+ if not (
408
+ isinstance(value, SigmaString) and len(value.s) == 1 and isinstance(value.s[0], str)
409
+ ):
410
+ return None
411
+ text = value.s[0]
412
+ if "%" in text: # IPv6 scope ids are not valid TQL ip literals
413
+ return None
414
+ try:
415
+ return str(ipaddress.ip_address(text))
416
+ except ValueError:
417
+ return None
418
+
419
+ @staticmethod
420
+ def _lowercase_value(value: SigmaString) -> None:
421
+ """Lowercase the plain string parts of a SigmaString in place (wildcards stay)."""
422
+ value.s = [item.lower() if isinstance(item, str) else item for item in value.s]
423
+
424
+ def _convert_literal_in_expression(
425
+ self,
426
+ literals: list[tuple[ConditionFieldEqualsValueExpression, str]],
427
+ cond: ConditionOR | ConditionAND,
428
+ state: ConversionState,
429
+ ) -> str:
430
+ """Render values that are compared as-is (numbers, IPs): never lowercased."""
431
+ for arg, _ in literals:
432
+ self._track_field_for_null_check(arg.field, state)
433
+ field = self.escape_and_quote_field(literals[0][0].field)
434
+ if len(literals) == 1:
435
+ return f"{field}{self.eq_token}{literals[0][1]}"
436
+ if (
437
+ self.field_in_list_expression is None
438
+ or self.list_separator is None
439
+ or self.or_in_operator is None
440
+ or self.and_in_operator is None
441
+ ):
442
+ raise NotImplementedError("Field in list expressions are not supported by the backend")
443
+ return self.field_in_list_expression.format(
444
+ field=field,
445
+ op=self.or_in_operator if isinstance(cond, ConditionOR) else self.and_in_operator,
446
+ list=self.list_separator.join(literal for _, literal in literals),
447
+ )
448
+
449
+ def convert_condition_as_in_expression(
450
+ self, cond: ConditionOR | ConditionAND, state: ConversionState
451
+ ) -> str | DeferredQueryExpression:
452
+ """
453
+ Convert a value list into an in-expression.
454
+
455
+ Tenzir's to_lower() only accepts strings and yields null for numbers, IPs and
456
+ lists, so it is applied only to string values. Types follow the Sigma rule:
457
+ numbers and IP addresses are compared as-is, strings are lowercased.
458
+ Mixed lists are split into one expression per type.
459
+ """
460
+ literals: list[tuple[ConditionFieldEqualsValueExpression, str]] = []
461
+ string_args: list[ConditionFieldEqualsValueExpression] = []
462
+ for arg in cond.args:
463
+ if not isinstance(arg, ConditionFieldEqualsValueExpression):
464
+ # the base class raises the appropriate TypeError
465
+ return super().convert_condition_as_in_expression(cond, state)
466
+ ip = self._ip_literal(arg.value)
467
+ if ip is not None:
468
+ literals.append((arg, ip))
469
+ elif isinstance(arg.value, SigmaString):
470
+ string_args.append(arg)
471
+ else:
472
+ literals.append((arg, str(arg.value))) # numbers etc.: never lowercase
473
+
474
+ if literals and string_args:
475
+ if len(string_args) == 1:
476
+ string_part = self.convert_condition_field_eq_val(string_args[0], state)
477
+ else:
478
+ string_part = self.convert_condition_as_in_expression(
479
+ type(cond)(cast(list[Any], string_args), cond.source), state
480
+ )
481
+ joiner = " or " if isinstance(cond, ConditionOR) else " and "
482
+ parts = [
483
+ self._convert_literal_in_expression(literals, cond, state),
484
+ str(string_part),
485
+ ]
486
+ return (self.group_expression or "({expr})").format(expr=joiner.join(parts))
487
+
488
+ if literals:
489
+ return self._convert_literal_in_expression(literals, cond, state)
490
+
491
+ for arg in string_args:
492
+ # Track field for null checks
493
+ self._track_field_for_null_check(arg.field, state)
494
+
495
+ if ".to_lower()" not in arg.field:
496
+ arg.field = f"{arg.field}.to_lower()"
497
+ if isinstance(arg.value, SigmaString):
498
+ arg.value = arg.value.lower()
499
+
500
+ return super().convert_condition_as_in_expression(cond, state)
501
+
502
+ def convert_condition_field_eq_val_str(
503
+ self, cond: ConditionFieldEqualsValueExpression, state: ConversionState
504
+ ) -> str | DeferredQueryExpression:
505
+ """Conversion of field = string value expressions"""
506
+ # Store the original field for null check tracking
507
+ original_field = cond.field
508
+
509
+ ip = self._ip_literal(cond.value)
510
+ if ip is not None:
511
+ self._track_field_for_null_check(original_field, state)
512
+ return f"{self.escape_and_quote_field(cond.field)}{self.eq_token}{ip}"
513
+
514
+ if ".to_lower()" not in cond.field:
515
+ cond.field = f"{cond.field}.to_lower()"
516
+ if isinstance(cond.value, SigmaString):
517
+ self._lowercase_value(cond.value)
518
+ value = super().convert_condition_field_eq_val_str(cond, state)
519
+ if (
520
+ isinstance(value, str)
521
+ and self.wildcard_match_expression is not None
522
+ and self.wildcard_multi is not None
523
+ and "match_regex" in value
524
+ ):
525
+ value = value.replace(self.wildcard_multi, ".*")
526
+ self._track_field_for_null_check(original_field, state)
527
+ return value
528
+
529
+ # TQL2 keywords and method names that must never receive optional-chaining '?'
530
+ _TQLKW: ClassVar[frozenset] = frozenset(
531
+ {
532
+ "where",
533
+ "and",
534
+ "or",
535
+ "not",
536
+ "null",
537
+ "true",
538
+ "false",
539
+ "in",
540
+ "every",
541
+ "summarize",
542
+ "eval",
543
+ "case",
544
+ "event_type",
545
+ "event_count",
546
+ "aggr_field",
547
+ "ts",
548
+ "to_lower",
549
+ "ends_with",
550
+ "starts_with",
551
+ "match_regex",
552
+ "has",
553
+ "contains",
554
+ "count_distinct",
555
+ "distinct",
556
+ "round",
557
+ "time",
558
+ "date_trunc",
559
+ "length",
560
+ }
561
+ )
562
+
563
+ @classmethod
564
+ def _add_optional_chaining(cls, query: str) -> str:
565
+ """
566
+ Transforms field path dotted notation to optional-chaining TQL2 syntax by
567
+ inserting '?' after each field segment in a dotted path.
568
+
569
+ Rules:
570
+ - A dot preceded by a word character (field segment) becomes '?.' so that
571
+ 'a.b.c' → 'a?.b?.c?'.
572
+ - Dots preceded by ')' (end of method call) are left unchanged so that
573
+ 'to_lower().ends_with(...)' stays as-is.
574
+ - A trailing '?' is appended to the last field segment of a path when it
575
+ is not immediately followed by '(' (i.e. it is a plain field reference,
576
+ not a method call).
577
+ - TQL2 keywords and built-in method names are never modified.
578
+ - Substitutions are only performed outside of double-quoted string literals
579
+ to avoid corrupting values.
580
+ """
581
+
582
+ def transform_segment(text: str) -> str:
583
+ # Step 1: replace field-to-field dots: word.word → word?.word
584
+ # Only when the left-hand token is not a TQL2 keyword/method.
585
+ def dot_repl(m: re.Match) -> str:
586
+ token = m.group(1)
587
+ if token in cls._TQLKW or re.fullmatch(r"\d+", token):
588
+ return f"{token}."
589
+ return f"{token}?."
590
+
591
+ result = re.sub(r"(\w+)\.(?=\w)", dot_repl, text)
592
+
593
+ # Step 2: add trailing '?' to a word token that is a field reference –
594
+ # i.e. the last segment of a dotted path. We recognise field references
595
+ # as tokens that were the target of a '?.' substitution in step 1 (so
596
+ # they are now preceded by '?.') OR tokens that stand alone as field
597
+ # names (preceded by 'where ', ' and ', ' or ', 'not ', '(').
598
+ # A token is NOT a field reference if it is a keyword, a number, or is
599
+ # immediately followed by '(' (method call).
600
+ def trail_repl(m: re.Match) -> str:
601
+ token = m.group(1)
602
+ if token in cls._TQLKW:
603
+ return token
604
+ if re.fullmatch(r"\d+", token):
605
+ return token
606
+ return f"{token}?"
607
+
608
+ # Match word tokens (including hyphenated names) NOT already ending in
609
+ # '?' and NOT followed by '(' – preceded by '?.' means last field segment
610
+ result = re.sub(r"(?<=[?.])(\w[\w-]*)(?![\w.(|?-])", trail_repl, result)
611
+
612
+ # Also handle the very first (or only) segment of a dotted path that
613
+ # was turned into 'token?.' – its trailing '?' was already added in
614
+ # step 1. We still need to handle standalone field names that have NO
615
+ # dot at all (e.g. 'fieldA' in 'where fieldA != null').
616
+ # These appear after: 'where ', 'and ', 'or ', 'not ', '('
617
+ result = re.sub(
618
+ r"(?:(?<=where )|(?<=and )|(?<=or )|(?<=not )|(?<=\())" r"(\w[\w-]*)(?![\w.(|?-])",
619
+ trail_repl,
620
+ result,
621
+ )
622
+ return result
623
+
624
+ # Split the query on double-quoted string literals, transform only the
625
+ # non-quoted parts, then reassemble.
626
+ parts = re.split(r'("[^"]*")', query)
627
+ transformed = []
628
+ for i, part in enumerate(parts):
629
+ if i % 2 == 1:
630
+ # Odd indices are quoted string literals – leave unchanged
631
+ transformed.append(part)
632
+ else:
633
+ transformed.append(transform_segment(part))
634
+ return "".join(transformed)
635
+
636
+ @classmethod
637
+ def _add_optional_chaining_to_field(cls, field: str) -> str:
638
+ """
639
+ Add optional-chaining '?' suffix to field path segments.
640
+ Transforms dotted field paths to use '?.' between segments and trailing '?'.
641
+
642
+ Examples:
643
+ 'process.cmd_line' → 'process?.cmd_line?'
644
+ 'process.file.path' → 'process?.file?.path?'
645
+ 'type_uid' → 'type_uid?'
646
+ """
647
+ parts = field.split(".")
648
+ if len(parts) == 1:
649
+ return f"{parts[0]}?"
650
+
651
+ return "".join(f"{part}?." for part in parts[:-1]) + f"{parts[-1]}?"
652
+
653
+ @staticmethod
654
+ def _make_to_lower_alias(field_expr: str) -> str:
655
+ """
656
+ Derive a flat alias name from an optional-chaining field expression ending in
657
+ '.to_lower()'. E.g.:
658
+ 'fieldA?.to_lower()' -> 'fieldA_lower'
659
+ 'http_request?.url?.hostname?.to_lower()' -> 'http_request.url.hostname_lower'
660
+ """
661
+ # Strip the trailing .to_lower() (and optional preceding '?')
662
+ path = re.sub(r"[?]?\.to_lower\(\)$", "", field_expr)
663
+ # Normalise optional-chaining dots to plain dots
664
+ path = path.replace("?.", ".")
665
+ # Strip any remaining trailing '?' (bare field reference)
666
+ path = path.rstrip("?")
667
+ # Append _lower to the last segment
668
+ if "." in path:
669
+ prefix, _, last = path.rpartition(".")
670
+ return f"{prefix}.{last}_lower"
671
+ return f"{path}_lower"
672
+
673
+ def finalize_query_default(
674
+ self, rule: SigmaRule, query: str, index: int, state: ConversionState
675
+ ) -> str:
676
+ # Build the query parts
677
+ null_check_lines = []
678
+
679
+ # If field null checks are enabled, build null check lines
680
+ if self.add_field_null_check:
681
+ null_checks = [
682
+ f"{self._add_optional_chaining_to_field(field)} != null"
683
+ for field in sorted(self._null_checked_fields(state))
684
+ ]
685
+ if null_checks:
686
+ null_check_condition = " and ".join(null_checks)
687
+ null_check_lines = [f"where {null_check_condition}"]
688
+
689
+ # Build the main query with optional chaining
690
+ main_query = self._add_optional_chaining(f"where {query}")
691
+
692
+ # Hoist every X?.to_lower() call into a named alias for performance.
693
+ # Pattern matches an optional-chaining field path ending in .to_lower().
694
+ to_lower_pattern = re.compile(r"[\w]+(?:[?]\.\w+)*[?]?\.to_lower\(\)")
695
+ seen: dict[str, str] = {} # field_expr -> alias (ordered by first appearance)
696
+ for m in to_lower_pattern.finditer(main_query):
697
+ expr = m.group(0)
698
+ if expr not in seen:
699
+ seen[expr] = self._make_to_lower_alias(expr)
700
+
701
+ # Build preamble assignment lines (lhs uses plain dotted path, rhs the original expr)
702
+ assignment_lines = []
703
+ if seen:
704
+ assignment_lines = [f"{alias} = {expr}" for expr, alias in seen.items()]
705
+
706
+ # Replace every occurrence of each to_lower() expression in the query.
707
+ # Longer expressions first to avoid partial replacements.
708
+ rewritten = main_query
709
+ for expr in sorted(seen, key=len, reverse=True):
710
+ alias = seen[expr]
711
+ rewritten = rewritten.replace(expr, alias)
712
+
713
+ # Build drop line
714
+ drop_line = ""
715
+ if seen:
716
+ drop_fields = ", ".join(seen.values())
717
+ drop_line = f"drop {drop_fields}"
718
+
719
+ # Assemble final query: null_checks → assignments → query → drop
720
+ # The null checks come first so to_lower() is never evaluated on null fields.
721
+ result_lines = null_check_lines + assignment_lines + [rewritten]
722
+ if drop_line:
723
+ result_lines.append(drop_line)
724
+
725
+ return "\n".join(result_lines)
726
+
727
+ def convert_condition_field_eq_val_num(
728
+ self, cond: ConditionFieldEqualsValueExpression, state: ConversionState
729
+ ) -> str | DeferredQueryExpression:
730
+ """Conversion of field = number value expressions with field null check tracking"""
731
+ original_field = cond.field
732
+ value = super().convert_condition_field_eq_val_num(cond, state)
733
+ self._track_field_for_null_check(original_field, state)
734
+ return value
735
+
736
+ def convert_condition_field_eq_val_bool(
737
+ self, cond: ConditionFieldEqualsValueExpression, state: ConversionState
738
+ ) -> str | DeferredQueryExpression:
739
+ """Conversion of field = bool value expressions with field null check tracking"""
740
+ original_field = cond.field
741
+ value = super().convert_condition_field_eq_val_bool(cond, state)
742
+ self._track_field_for_null_check(original_field, state)
743
+ return value
744
+
745
+ def convert_condition_field_eq_val_re(
746
+ self, cond: ConditionFieldEqualsValueExpression, state: ConversionState
747
+ ) -> str | DeferredQueryExpression:
748
+ """Conversion of field matches regex expressions with field null check tracking"""
749
+ original_field = cond.field
750
+ value = super().convert_condition_field_eq_val_re(cond, state)
751
+ self._track_field_for_null_check(original_field, state)
752
+ return value
753
+
754
+ def convert_condition_field_eq_val_cidr(
755
+ self, cond: ConditionFieldEqualsValueExpression, state: ConversionState
756
+ ) -> str | DeferredQueryExpression:
757
+ """Conversion of field CIDR match expressions with field null check tracking"""
758
+ original_field = cond.field
759
+ value = super().convert_condition_field_eq_val_cidr(cond, state)
760
+ self._track_field_for_null_check(original_field, state)
761
+ return value
762
+
763
+ def convert_condition_field_compare_op_val(
764
+ self, cond: ConditionFieldEqualsValueExpression, state: ConversionState
765
+ ) -> str | DeferredQueryExpression:
766
+ """Conversion of field compare operator expressions with field null check tracking"""
767
+ original_field = cond.field
768
+ value = super().convert_condition_field_compare_op_val(cond, state)
769
+ self._track_field_for_null_check(original_field, state)
770
+ return value
771
+
772
+ def finalize_output_default(self, queries: list[Any]) -> Any:
773
+ return list(queries)
@@ -0,0 +1,9 @@
1
+ # DCSO - pySigma-backend-tenzir
2
+ # Copyright (c) 2024-2026 DCSO GmbH
3
+
4
+ # from .tenzir import tenzir_pipeline
5
+ # TODO: add all pipelines that should be exposed to the user of your backend in the import statement above.
6
+
7
+ pipelines = {
8
+ # "tenzir_pipeline": tenzir_pipeline, # TODO: adapt identifier to something approproiate
9
+ }
@@ -0,0 +1,68 @@
1
+ # DCSO - pySigma-backend-tenzir
2
+ # Copyright (c) 2024-2026 DCSO GmbH
3
+
4
+ from sigma.pipelines.base import Pipeline
5
+ from sigma.pipelines.common import logsource_windows, windows_logsource_mapping
6
+ from sigma.processing.conditions import (
7
+ ExcludeFieldCondition,
8
+ IncludeFieldCondition,
9
+ LogsourceCondition,
10
+ RuleProcessingItemAppliedCondition,
11
+ )
12
+ from sigma.processing.pipeline import (
13
+ ProcessingItem,
14
+ ProcessingPipeline,
15
+ QueryPostprocessingItem,
16
+ )
17
+ from sigma.processing.postprocessing import (
18
+ EmbedQueryTransformation,
19
+ )
20
+ from sigma.processing.finalization import ConcatenateQueriesFinalizer
21
+ from sigma.processing.transformations import (
22
+ AddConditionTransformation,
23
+ DetectionItemFailureTransformation,
24
+ FieldMappingTransformation,
25
+ RuleFailureTransformation,
26
+ SetStateTransformation,
27
+ )
28
+
29
+ # TODO: the following code is just an example extend/adapt as required.
30
+ # See https://sigmahq-pysigma.readthedocs.io/en/latest/Processing_Pipelines.html for further documentation.
31
+
32
+
33
+ @Pipeline
34
+ def tenzir_pipeline() -> (
35
+ ProcessingPipeline
36
+ ): # Processing pipelines should be defined as functions that return a ProcessingPipeline object.
37
+ return ProcessingPipeline(
38
+ name="tenzir example pipeline",
39
+ allowed_backends=frozenset(), # Set of identifiers of backends (from the backends mapping) that are allowed to use this processing pipeline. This can be used by frontends like Sigma CLI to warn the user about inappropriate usage.
40
+ priority=20, # The priority defines the order pipelines are applied. See documentation for common values.
41
+ items=[
42
+ ProcessingItem( # This is an example for processing items generated from the mapping above.
43
+ identifier=f"tenzir_windows_{service}",
44
+ transformation=AddConditionTransformation({"source": source}),
45
+ rule_conditions=[logsource_windows(service)],
46
+ )
47
+ for service, source in windows_logsource_mapping.items()
48
+ ]
49
+ + [
50
+ ProcessingItem( # Field mappings
51
+ identifier="tenzir_field_mapping",
52
+ transformation=FieldMappingTransformation(
53
+ {
54
+ "EventID": "event_id", # TODO: define your own field mappings
55
+ }
56
+ ),
57
+ )
58
+ ],
59
+ postprocessing_items=[
60
+ QueryPostprocessingItem(
61
+ transformation=EmbedQueryTransformation(prefix="...", suffix="..."),
62
+ rule_condition_linking=any,
63
+ rule_conditions=[],
64
+ identifier="example",
65
+ )
66
+ ],
67
+ finalizers=[ConcatenateQueriesFinalizer()],
68
+ )