pySigma-backend-databricks 0.1.4__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,8 @@
1
+
2
+ Copyright 2022 Alex Ott
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,123 @@
1
+ Metadata-Version: 2.4
2
+ Name: pySigma-backend-databricks
3
+ Version: 0.1.4
4
+ Summary: pySigma backend for Apache Spark/Databricks
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Keywords: cybersecurity,apache spark,spark,sigma,databricks
8
+ Author: Alex Ott
9
+ Author-email: alexott@gmail.com
10
+ Requires-Python: >=3.10,<=3.14
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Requires-Dist: inflection (>=0.5.1,<0.6.0)
18
+ Requires-Dist: pysigma (>=1.0.2,<2.0.0)
19
+ Project-URL: Homepage, https://github.com/alexott/cyber-spark-data-connectors
20
+ Project-URL: Issues, https://github.com/alexott/cyber-spark-data-connectors/issues
21
+ Description-Content-Type: text/markdown
22
+
23
+ ![Tests](https://github.com/alexott/databricks-sigma-backend/actions/workflows/test.yml/badge.svg)
24
+ ![Coverage Badge](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/alexott/GitHub Gist identifier containing coverage badge JSON expected by shields.io./raw/alexott-databricks-sigma-backend.json)
25
+ ![Status](https://img.shields.io/badge/Status-pre--release-orange)
26
+
27
+ Status: **experimental**, work in progress:
28
+
29
+ * Although `cidrmatch` is generated, you still need to provide corresponding function as UDF (I'll add example later)
30
+ * Requires more testing
31
+
32
+ # pySigma Databricks Backend
33
+
34
+ This is the Databricks backend for pySigma. It provides the package `sigma.backends.databricks` with the `DatabricksBackend` class.
35
+ Further, it contains the following processing pipelines in `sigma.pipelines.databricks`:
36
+
37
+ * `snake_case`: convert column names into snake case format
38
+
39
+ It supports the following output formats:
40
+
41
+ * default: plain Databricks/Apache Spark SQL queries
42
+ * dbsql: Databricks SQL queries with rules metadata (title, status) embedded as comment
43
+ * detection_yaml: Yaml markup for my own detection framework
44
+
45
+ ## Unbound Keyword Search
46
+
47
+ The backend supports Sigma rules with unbound keywords (values without field names). These keywords search the raw log line.
48
+
49
+ ### Configuration
50
+
51
+ By default, the backend looks for keywords in a field named `raw`. You can customize this:
52
+
53
+ **Command Line:**
54
+ ```bash
55
+ sigma convert -t databricks -O raw_log_field=message rule.yml
56
+ ```
57
+
58
+ **Programmatic:**
59
+ ```python
60
+ from sigma.backends.databricks import DatabricksBackend
61
+
62
+ backend = DatabricksBackend(raw_log_field="event_data")
63
+ ```
64
+
65
+ ### Examples
66
+
67
+ **Simple Keywords (OR logic):**
68
+ ```yaml
69
+ detection:
70
+ keywords:
71
+ - 'EVILSERVICE'
72
+ - 'svchost.exe -n evil'
73
+ condition: keywords
74
+ ```
75
+ Generates: `contains(lower(raw), lower('EVILSERVICE')) OR contains(lower(raw), lower('svchost.exe -n evil'))`
76
+
77
+ **Keywords with |all (AND logic):**
78
+ ```yaml
79
+ detection:
80
+ keywords:
81
+ '|all':
82
+ - 'Remove-MailboxExportRequest'
83
+ - ' -Identity '
84
+ condition: keywords
85
+ ```
86
+ Generates: `contains(lower(raw), lower('Remove-MailboxExportRequest')) AND contains(lower(raw), lower(' -Identity '))`
87
+
88
+ **Mixed with Field Conditions:**
89
+ ```yaml
90
+ detection:
91
+ selection:
92
+ EventID: 4688
93
+ keywords:
94
+ - 'mimikatz'
95
+ condition: selection and keywords
96
+ ```
97
+ Generates: `EventID = 4688 AND contains(lower(raw), lower('mimikatz'))`
98
+
99
+ **Wildcards in Keywords:**
100
+ ```yaml
101
+ detection:
102
+ keywords:
103
+ - '*malware*' # uses contains()
104
+ - 'cmd.exe*' # uses startswith()
105
+ - '*.dll' # uses endswith()
106
+ condition: keywords
107
+ ```
108
+
109
+ **Regex Patterns:**
110
+ ```yaml
111
+ detection:
112
+ keywords:
113
+ - '|re': '.*evil(cmd|powershell).*'
114
+ condition: keywords
115
+ ```
116
+ Generates: `raw rlike '.*evil(cmd|powershell).*'`
117
+
118
+ ## Maintainer
119
+
120
+ This backend is currently maintained by:
121
+
122
+ * [Alex Ott](https://github.com/alexott/)
123
+
@@ -0,0 +1,100 @@
1
+ ![Tests](https://github.com/alexott/databricks-sigma-backend/actions/workflows/test.yml/badge.svg)
2
+ ![Coverage Badge](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/alexott/GitHub Gist identifier containing coverage badge JSON expected by shields.io./raw/alexott-databricks-sigma-backend.json)
3
+ ![Status](https://img.shields.io/badge/Status-pre--release-orange)
4
+
5
+ Status: **experimental**, work in progress:
6
+
7
+ * Although `cidrmatch` is generated, you still need to provide corresponding function as UDF (I'll add example later)
8
+ * Requires more testing
9
+
10
+ # pySigma Databricks Backend
11
+
12
+ This is the Databricks backend for pySigma. It provides the package `sigma.backends.databricks` with the `DatabricksBackend` class.
13
+ Further, it contains the following processing pipelines in `sigma.pipelines.databricks`:
14
+
15
+ * `snake_case`: convert column names into snake case format
16
+
17
+ It supports the following output formats:
18
+
19
+ * default: plain Databricks/Apache Spark SQL queries
20
+ * dbsql: Databricks SQL queries with rules metadata (title, status) embedded as comment
21
+ * detection_yaml: Yaml markup for my own detection framework
22
+
23
+ ## Unbound Keyword Search
24
+
25
+ The backend supports Sigma rules with unbound keywords (values without field names). These keywords search the raw log line.
26
+
27
+ ### Configuration
28
+
29
+ By default, the backend looks for keywords in a field named `raw`. You can customize this:
30
+
31
+ **Command Line:**
32
+ ```bash
33
+ sigma convert -t databricks -O raw_log_field=message rule.yml
34
+ ```
35
+
36
+ **Programmatic:**
37
+ ```python
38
+ from sigma.backends.databricks import DatabricksBackend
39
+
40
+ backend = DatabricksBackend(raw_log_field="event_data")
41
+ ```
42
+
43
+ ### Examples
44
+
45
+ **Simple Keywords (OR logic):**
46
+ ```yaml
47
+ detection:
48
+ keywords:
49
+ - 'EVILSERVICE'
50
+ - 'svchost.exe -n evil'
51
+ condition: keywords
52
+ ```
53
+ Generates: `contains(lower(raw), lower('EVILSERVICE')) OR contains(lower(raw), lower('svchost.exe -n evil'))`
54
+
55
+ **Keywords with |all (AND logic):**
56
+ ```yaml
57
+ detection:
58
+ keywords:
59
+ '|all':
60
+ - 'Remove-MailboxExportRequest'
61
+ - ' -Identity '
62
+ condition: keywords
63
+ ```
64
+ Generates: `contains(lower(raw), lower('Remove-MailboxExportRequest')) AND contains(lower(raw), lower(' -Identity '))`
65
+
66
+ **Mixed with Field Conditions:**
67
+ ```yaml
68
+ detection:
69
+ selection:
70
+ EventID: 4688
71
+ keywords:
72
+ - 'mimikatz'
73
+ condition: selection and keywords
74
+ ```
75
+ Generates: `EventID = 4688 AND contains(lower(raw), lower('mimikatz'))`
76
+
77
+ **Wildcards in Keywords:**
78
+ ```yaml
79
+ detection:
80
+ keywords:
81
+ - '*malware*' # uses contains()
82
+ - 'cmd.exe*' # uses startswith()
83
+ - '*.dll' # uses endswith()
84
+ condition: keywords
85
+ ```
86
+
87
+ **Regex Patterns:**
88
+ ```yaml
89
+ detection:
90
+ keywords:
91
+ - '|re': '.*evil(cmd|powershell).*'
92
+ condition: keywords
93
+ ```
94
+ Generates: `raw rlike '.*evil(cmd|powershell).*'`
95
+
96
+ ## Maintainer
97
+
98
+ This backend is currently maintained by:
99
+
100
+ * [Alex Ott](https://github.com/alexott/)
@@ -0,0 +1,147 @@
1
+ [tool.poetry]
2
+ name = "pySigma-backend-databricks"
3
+ version = "0.1.4"
4
+ description = "pySigma backend for Apache Spark/Databricks"
5
+ authors = ["Alex Ott <alexott@gmail.com>"]
6
+ license = "MIT"
7
+ repository = "https://github.com/alexott/pySigma-backend-databricks"
8
+ packages = [
9
+ { include = "sigma" }
10
+ ]
11
+ readme = "README.md"
12
+ keywords = ["cybersecurity", "apache spark", "spark", "sigma", "databricks"]
13
+
14
+ [project]
15
+ name = "pySigma-backend-databricks"
16
+ license = "Apache-2.0"
17
+ license-files = ["LICEN[CS]E*"]
18
+
19
+ [project.urls]
20
+ Homepage = "https://github.com/alexott/cyber-spark-data-connectors"
21
+ Issues = "https://github.com/alexott/cyber-spark-data-connectors/issues"
22
+
23
+ [tool.poetry.dependencies]
24
+ python = ">=3.10,<=3.14"
25
+ pysigma = "^1.0.2"
26
+ inflection = "^0.5.1"
27
+
28
+ [tool.poetry.group.test.dependencies]
29
+ pytest = "^9.0.2"
30
+ pytest-cov = "^7.0.0"
31
+
32
+ [tool.poetry.group.dev.dependencies]
33
+ autopep8 = "^2.3.2"
34
+ pylint = "^4.0.4"
35
+ sigma-cli = "^2.0.0"
36
+ mypy = "^1.19.1"
37
+ ruff = "^0.14.9"
38
+ types-pyyaml = "^6.0.12.20250915"
39
+ pyright = "^1.1.407"
40
+
41
+ [build-system]
42
+ requires = ["poetry-core>=1.3.0"]
43
+ build-backend = "poetry.core.masonry.api"
44
+
45
+ [tool.pylint.'MESSAGES CONTROL']
46
+ disable = "missing-function-docstring,missing-module-docstring,line-too-long,too-many-lines"
47
+
48
+ [tool.pytest.ini_options]
49
+ minversion = "6.0"
50
+ python_files = "test_*.py"
51
+ addopts = "-vv --cov=sigma --cov-report term --cov-report xml:cov.xml"
52
+ testpaths = [
53
+ "tests",
54
+ ]
55
+
56
+ [tool.ruff]
57
+ # Exclude a variety of commonly ignored directories.
58
+ exclude = [
59
+ ".bzr",
60
+ ".direnv",
61
+ ".eggs",
62
+ ".git",
63
+ ".git-rewrite",
64
+ ".hg",
65
+ ".ipynb_checkpoints",
66
+ ".mypy_cache",
67
+ ".nox",
68
+ ".pants.d",
69
+ ".pyenv",
70
+ ".pytest_cache",
71
+ ".pytype",
72
+ ".ruff_cache",
73
+ ".svn",
74
+ ".tox",
75
+ ".venv",
76
+ ".vscode",
77
+ "__pypackages__",
78
+ "_build",
79
+ "buck-out",
80
+ "build",
81
+ "dist",
82
+ "node_modules",
83
+ "site-packages",
84
+ "venv",
85
+ "notebooks",
86
+ ]
87
+
88
+ # Same as Black.
89
+ line-length = 120
90
+ indent-width = 4
91
+
92
+ # Assume Python 3.8
93
+ target-version = "py38"
94
+
95
+ [tool.ruff.lint]
96
+ # Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default.
97
+ # Unlike Flake8, Ruff doesn't enable pycodestyle warnings (`W`) or
98
+ # McCabe complexity (`C901`) by default.
99
+ select = [
100
+ "E", # pycodestyle errors
101
+ "W", # pycodestyle warnings
102
+ "F", # pyflakes
103
+ "I", # isort
104
+ "B", # flake8-bugbear
105
+ "C4", # flake8-comprehensions
106
+ "N", # PEP8 naming convetions
107
+ "D" # pydocstyle
108
+ ]
109
+ ignore = [
110
+ "D103", # No docstring in public function
111
+ "N812", # Lowercase `functions` imported as non-lowercase `F`
112
+ "F405", # `assert_df_equality` may be undefined, or defined from star imports
113
+ ]
114
+
115
+ # Allow fix for all enabled rules (when `--fix`) is provided.
116
+ fixable = ["ALL"]
117
+ unfixable = []
118
+
119
+ # Allow unused variables when underscore-prefixed.
120
+ dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
121
+
122
+ [tool.ruff.format]
123
+ # Like Black, use double quotes for strings.
124
+ quote-style = "double"
125
+
126
+ # Like Black, indent with spaces, rather than tabs.
127
+ indent-style = "space"
128
+
129
+ # Like Black, respect magic trailing commas.
130
+ skip-magic-trailing-comma = false
131
+
132
+ # Like Black, automatically detect the appropriate line ending.
133
+ line-ending = "auto"
134
+
135
+ # Enable auto-formatting of code examples in docstrings. Markdown,
136
+ # reStructuredText code/literal blocks and doctests are all supported.
137
+ #
138
+ # This is currently disabled by default, but it is planned for this
139
+ # to be opt-out in the future.
140
+ docstring-code-format = false
141
+
142
+ # Set the line length limit used when formatting code snippets in
143
+ # docstrings.
144
+ #
145
+ # This only has an effect when the `docstring-code-format` setting is
146
+ # enabled.
147
+ docstring-code-line-length = "dynamic"
@@ -0,0 +1,8 @@
1
+ from .databricks import DatabricksBackend
2
+ # TODO: add all backend classes that should be exposed to the user of your backend in the import statement above.
3
+
4
+ # Mapping between backend identifiers and classes. This is used by the pySigma plugin system to recognize backends and
5
+ # expose them with the identifier.
6
+ backends = {
7
+ "databricks": DatabricksBackend,
8
+ }
@@ -0,0 +1,465 @@
1
+ import json
2
+ import re
3
+ from typing import Optional, Pattern, Union, ClassVar, Tuple, List, Dict, Any, Type
4
+
5
+ import yaml
6
+ from sigma.conditions import ConditionItem, ConditionOR, ConditionAND, ConditionNOT, \
7
+ ConditionFieldEqualsValueExpression
8
+ from sigma.conversion.base import TextQueryBackend
9
+ from sigma.conversion.deferred import DeferredQueryExpression
10
+ from sigma.conversion.state import ConversionState
11
+ from sigma.rule import SigmaRule, SigmaLevel
12
+ from sigma.types import SigmaCompareExpression, SigmaString, SigmaRegularExpression, CompareOperators
13
+ from sigma.types import SpecialChars
14
+
15
+
16
+ class DatabricksBackend(TextQueryBackend):
17
+ """Databricks backend for PySigma."""
18
+ # See the pySigma documentation for further infromation:
19
+ # https://sigmahq-pysigma.readthedocs.io/en/latest/Backends.html
20
+
21
+ name: ClassVar[str] = "databricks"
22
+ formats: ClassVar[Dict[str, str]] = {
23
+ "default": "Plain Databricks SQL queries",
24
+ "dbsql": "Databricks SQL queries with additional metadata as comments",
25
+ "detection_yaml": "Yaml markup for Alex's own detection framework",
26
+ }
27
+ # TODO: does the backend requires that a processing pipeline is provided? This information can be used by user
28
+ # interface programs like Sigma CLI to warn users about inappropriate usage of the backend.
29
+ requires_pipeline: ClassVar[bool] = False
30
+
31
+ # Operator precedence: tuple of Condition{AND,OR,NOT} in order of precedence.
32
+ # The backend generates grouping if required
33
+ precedence: ClassVar[Tuple[Type[ConditionItem], Type[ConditionItem], Type[ConditionItem]]] = (
34
+ ConditionNOT, ConditionAND, ConditionOR
35
+ )
36
+ # Expression for precedence override grouping as format string with {expr} placeholder
37
+ group_expression: ClassVar[Optional[str]] = "({expr})"
38
+
39
+ # Generated query tokens
40
+ token_separator: str = " " # separator inserted between all boolean operators
41
+ or_token: ClassVar[Optional[str]] = "OR"
42
+ and_token: ClassVar[Optional[str]] = "AND"
43
+ not_token: ClassVar[Optional[str]] = "NOT"
44
+ eq_token: ClassVar[Optional[str]] = " = " # Token inserted between field and value (without separator)
45
+
46
+ # String output
47
+ ## Fields
48
+ ### Quoting
49
+ # Character used to quote field characters if field_quote_pattern matches (or not, depending on
50
+ # field_quote_pattern_negation). No field name quoting is done if not set.
51
+ field_quote: ClassVar[Optional[str]] = "`"
52
+ # Quote field names if this pattern (doesn't) matches, depending on field_quote_pattern_negation. Field name is
53
+ # always quoted if pattern is not set.
54
+ field_quote_pattern: ClassVar[Optional[Pattern]] = re.compile("^(\\w|\\.)+$")
55
+ # Negate field_quote_pattern result. Field name is quoted if pattern doesn't match if set to True (default).
56
+ field_quote_pattern_negation: ClassVar[bool] = True
57
+
58
+ # Escaping
59
+ # Character to escape particular parts defined in field_escape_pattern.
60
+ field_escape: ClassVar[Optional[str]] = ""
61
+ # Escape quote string defined in field_quote
62
+ field_escape_quote: ClassVar[bool] = True
63
+ # All matches of this pattern are prepended with the string contained in field_escape.
64
+ field_escape_pattern: ClassVar[Optional[Pattern]] = re.compile("\\s")
65
+
66
+ ## Values
67
+ str_quote: ClassVar[str] = "'" # string quoting character (added as escaping character)
68
+ escape_char: ClassVar[Optional[str]] = "\\" # Escaping character for special characters inside string
69
+ wildcard_multi: ClassVar[Optional[str]] = ".*" # Character used as multi-character wildcard
70
+ wildcard_single: ClassVar[Optional[str]] = "." # Character used as single-character wildcard
71
+ add_escaped: ClassVar[str] = "\\'" # Characters quoted in addition to wildcards and string quote
72
+ filter_chars: ClassVar[str] = "" # Characters filtered
73
+ bool_values: ClassVar[Dict[bool, Optional[str]]] = { # Values to which boolean values are mapped.
74
+ True: "true",
75
+ False: "false",
76
+ }
77
+
78
+ # String matching operators. if none is appropriate eq_token is used.
79
+ startswith_expression: ClassVar[Optional[str]] = "startswith(lower({field}), lower({value}))"
80
+ endswith_expression: ClassVar[Optional[str]] = "endswith(lower({field}), lower({value}))"
81
+ contains_expression: ClassVar[Optional[str]] = "contains(lower({field}), lower({value}))"
82
+ # Special expression if wildcards can't be matched with the eq_token operator
83
+ wildcard_match_expression: ClassVar[Optional[str]] = "lower({field}) regexp {value}"
84
+
85
+ # Regular expressions
86
+ # Regular expression query as format string with placeholders {field} and {regex}
87
+ re_expression: ClassVar[Optional[str]] = "{field} rlike '{regex}'"
88
+ # Character used for escaping in regular expressions
89
+ re_escape_char: ClassVar[Optional[str]] = "\\"
90
+ # List of strings that are escaped
91
+ re_escape: ClassVar[Tuple[str]] = ("{}[]()\\+",)
92
+ # Regular expression flags. We rely on the default implementation of the backend to handle them.
93
+ re_flag_prefix: bool = True
94
+
95
+ # cidr expressions
96
+ # TODO: fix that
97
+ cidr_wildcard: ClassVar[Optional[str]] = "*" # Character used as single wildcard
98
+ # CIDR expression query as format string with placeholders {field} = {value}
99
+ cidr_expression: ClassVar[Optional[str]] = "cidrmatch({field}, '{value}')"
100
+ # CIDR expression query as format string with placeholders {field} = in({list})
101
+ cidr_in_list_expression: ClassVar[Optional[str]] = "{field} in ({value})"
102
+
103
+ # Numeric comparison operators
104
+ # Compare operation query as format string with placeholders {field}, {operator} and {value}
105
+ compare_op_expression: ClassVar[Optional[str]] = "{field} {operator} {value}"
106
+ # Mapping between CompareOperators elements and strings used as replacement for {operator} in compare_op_expression
107
+ compare_operators: ClassVar[Optional[Dict[CompareOperators, str]]] = {
108
+ CompareOperators.LT: "<",
109
+ CompareOperators.LTE: "<=",
110
+ CompareOperators.GT: ">",
111
+ CompareOperators.GTE: ">=",
112
+ }
113
+
114
+ # Null/None expressions
115
+ # Expression for field has null value as format string with {field} placeholder for field name
116
+ field_null_expression: ClassVar[Optional[str]] = "{field} is null"
117
+
118
+ # Field value in list, e.g. "field in (value list)" or "field containsall (value list)"
119
+ # Convert OR as in-expression
120
+ convert_or_as_in: ClassVar[bool] = False
121
+ # Convert AND as in-expression
122
+ convert_and_as_in: ClassVar[bool] = False
123
+ # Values in list can contain wildcards. If set to False (default) only plain values are converted
124
+ # into in-expressions.
125
+ in_expressions_allow_wildcards: ClassVar[bool] = False
126
+ # Expression for field in list of values as format string with placeholders {field}, {op} and {list}
127
+ field_in_list_expression: ClassVar[Optional[str]] = "lower({field}) {op} ({list})"
128
+ # Operator used to convert OR into in-expressions. Must be set if convert_or_as_in is set
129
+ or_in_operator: ClassVar[Optional[str]] = "in"
130
+ # Operator used to convert AND into in-expressions. Must be set if convert_and_as_in is set
131
+ and_in_operator: ClassVar[Optional[str]] = "contains-all"
132
+ # List element separator
133
+ list_separator: ClassVar[Optional[str]] = ", "
134
+
135
+ # Field equals field comparison expression
136
+ # Expression for field to field comparison as format string with placeholders {field1} and {field2}
137
+ field_equals_field_expression: ClassVar[Optional[str]] = "{field1} = {field2}"
138
+
139
+ # OR optimization: Convert repeated OR operations with contains/startswith/endswith into regex
140
+ # Enable optimization of OR conditions as regex expressions
141
+ optimize_or_as_regex: ClassVar[bool] = True
142
+ # Minimum number of OR terms required to trigger regex optimization (set to 3 to avoid micro-optimizations)
143
+ min_or_terms_for_optimization: ClassVar[int] = 3
144
+
145
+ # TODO: think how to handle them? We really can't match them without field...
146
+ # Value not bound to a field
147
+ # Expression for string value not bound to a field as format string with placeholder {value}
148
+ unbound_value_str_expression: ClassVar[Optional[str]] = "{value}"
149
+ # Expression for number value not bound to a field as format string with placeholder {value}
150
+ unbound_value_num_expression: ClassVar[Optional[str]] = '{value}'
151
+ # Expression for regular expression not bound to a field as format string with placeholder {value}
152
+ unbound_value_re_expression: ClassVar[Optional[str]] = '_=~{value}'
153
+
154
+ # Field name containing the raw/full log line for unbound keyword searches
155
+ raw_log_field: str = "raw"
156
+
157
+ # Query finalization: appending and concatenating deferred query part
158
+ # String used as separator between main query and deferred parts
159
+ deferred_start: ClassVar[Optional[str]] = "\n| "
160
+ # String used to join multiple deferred query parts
161
+ deferred_separator: ClassVar[Optional[str]] = "\n| "
162
+ # String used as query if final query only contains deferred expression
163
+ deferred_only_query: ClassVar[Optional[str]] = "*"
164
+
165
+ def __init__(self, processing_pipeline=None, collect_errors=False, raw_log_field: Optional[str] = None, **kwargs):
166
+ """Initialize Databricks backend with optional raw log field configuration."""
167
+ super().__init__(processing_pipeline, collect_errors, **kwargs)
168
+ if raw_log_field:
169
+ self.raw_log_field = raw_log_field
170
+
171
+ def make_sql_string(self, s: SigmaString):
172
+ converted = s.convert(
173
+ self.escape_char,
174
+ None,
175
+ None,
176
+ (self.str_quote or "") + self.add_escaped,
177
+ self.filter_chars,
178
+ )
179
+ return self.quote_string(converted)
180
+
181
+ def convert_condition_field_eq_val_str(self, cond: ConditionFieldEqualsValueExpression,
182
+ state: ConversionState) -> Union[str, DeferredQueryExpression]:
183
+ """Conversion of field = string value expressions"""
184
+ if not isinstance(cond.value, SigmaString):
185
+ raise TypeError(f"cond.value type isn't SigmaString: {type(cond.value)}")
186
+
187
+ # Type narrowing for Pylance
188
+ sigma_value: SigmaString = cond.value
189
+
190
+ try:
191
+ if ( # Check conditions for usage of 'startswith' operator
192
+ self.startswith_expression is not None # 'startswith' operator is defined in backend
193
+ and sigma_value.endswith(SpecialChars.WILDCARD_MULTI) # String ends with wildcard
194
+ and not sigma_value[:-1].contains_special() # Remainder of string doesn't contain special characters
195
+ ):
196
+ expr = self.startswith_expression # If all conditions are fulfilled, use 'startswith' operator
197
+ # instead of equal token
198
+ value = self.make_sql_string(sigma_value[:-1])
199
+ elif (
200
+ # Same as above but for 'endswith' operator: string starts with wildcard and doesn't contain further
201
+ # special characters
202
+ self.endswith_expression is not None
203
+ and sigma_value.startswith(SpecialChars.WILDCARD_MULTI)
204
+ and not sigma_value[1:].contains_special()
205
+ ):
206
+ expr = self.endswith_expression
207
+ value = self.make_sql_string(sigma_value[1:])
208
+ elif ( # contains: string starts and ends with wildcard
209
+ self.contains_expression is not None
210
+ and sigma_value.startswith(SpecialChars.WILDCARD_MULTI)
211
+ and sigma_value.endswith(SpecialChars.WILDCARD_MULTI)
212
+ and not sigma_value[1:-1].contains_special()
213
+ ):
214
+ expr = self.contains_expression
215
+ value = self.make_sql_string(sigma_value[1:-1])
216
+ elif ( # wildcard match expression: string contains wildcard
217
+ self.wildcard_match_expression is not None
218
+ and sigma_value.contains_special()
219
+ ):
220
+ expr = self.wildcard_match_expression
221
+ value = self.convert_value_str(sigma_value, state)
222
+ else: # We have just plain string
223
+ expr = "lower({field}) = lower({value})"
224
+ value = self.make_sql_string(sigma_value)
225
+
226
+ return expr.format(field=self.escape_and_quote_field(cond.field),
227
+ value=value)
228
+ except TypeError: # pragma: no cover
229
+ raise NotImplementedError("Field equals string value expressions with strings are not supported by the "
230
+ "backend.")
231
+
232
+ def convert_condition_val_str(self, cond, state: ConversionState) -> Union[str, DeferredQueryExpression]:
233
+ """Conversion of unbound string values (keywords without field names)"""
234
+ if not self.raw_log_field:
235
+ raise ValueError("Unbound keyword search requires raw_log_field to be configured")
236
+
237
+ # Use raw log field for keyword search
238
+ field = self.escape_and_quote_field(self.raw_log_field)
239
+ value = cond.value
240
+
241
+ # Type narrowing: ensure value is SigmaString
242
+ if not isinstance(value, SigmaString):
243
+ raise TypeError(f"Expected SigmaString, got {type(value)}")
244
+
245
+ # Handle wildcards similar to field-based logic
246
+ if (self.contains_expression is not None
247
+ and value.startswith(SpecialChars.WILDCARD_MULTI)
248
+ and value.endswith(SpecialChars.WILDCARD_MULTI)
249
+ and not value[1:-1].contains_special()):
250
+ # *keyword* -> contains()
251
+ val_str = self.make_sql_string(value[1:-1])
252
+ return self.contains_expression.format(field=field, value=val_str)
253
+ elif (self.startswith_expression is not None
254
+ and value.endswith(SpecialChars.WILDCARD_MULTI)
255
+ and not value[:-1].contains_special()):
256
+ # keyword* -> startswith()
257
+ val_str = self.make_sql_string(value[:-1])
258
+ return self.startswith_expression.format(field=field, value=val_str)
259
+ elif (self.endswith_expression is not None
260
+ and value.startswith(SpecialChars.WILDCARD_MULTI)
261
+ and not value[1:].contains_special()):
262
+ # *keyword -> endswith()
263
+ val_str = self.make_sql_string(value[1:])
264
+ return self.endswith_expression.format(field=field, value=val_str)
265
+ elif (self.wildcard_match_expression is not None
266
+ and value.contains_special()):
267
+ # Complex wildcards -> regexp
268
+ val_str = self.convert_value_str(value, state)
269
+ return self.wildcard_match_expression.format(field=field, value=val_str)
270
+ else:
271
+ # Plain keyword -> contains() (most common case)
272
+ val_str = self.make_sql_string(value)
273
+ if self.contains_expression:
274
+ return self.contains_expression.format(field=field, value=val_str)
275
+ raise ValueError("contains_expression is not defined")
276
+
277
+ def convert_condition_val_re(self, cond, state: ConversionState) -> Union[str, DeferredQueryExpression]:
278
+ """Conversion of unbound regex values"""
279
+ if not self.raw_log_field:
280
+ raise ValueError("Unbound regex search requires raw_log_field to be configured")
281
+
282
+ # Type narrowing: ensure value is SigmaRegularExpression
283
+ if not isinstance(cond.value, SigmaRegularExpression):
284
+ raise TypeError(f"Expected SigmaRegularExpression, got {type(cond.value)}")
285
+
286
+ field = self.escape_and_quote_field(self.raw_log_field)
287
+ if self.re_expression:
288
+ return self.re_expression.format(field=field, regex=cond.value.regexp)
289
+ raise ValueError("re_expression is not defined")
290
+
291
+ def convert_condition_val_num(self, cond, state: ConversionState) -> Union[str, DeferredQueryExpression]:
292
+ """Conversion of unbound numeric values"""
293
+ if not self.raw_log_field:
294
+ raise ValueError("Unbound numeric search requires raw_log_field to be configured")
295
+
296
+ # Convert number to string search in raw log
297
+ field = self.escape_and_quote_field(self.raw_log_field)
298
+ value = self.make_sql_string(SigmaString(str(cond.value)))
299
+ if self.contains_expression:
300
+ return self.contains_expression.format(field=field, value=value)
301
+ raise ValueError("contains_expression is not defined")
302
+
303
+ def _analyze_or_for_regex_optimization(
304
+ self, cond: ConditionOR
305
+ ) -> Optional[Tuple[str, str, List[str]]]:
306
+ """
307
+ Analyze an OR condition to determine if it can be optimized as a regex expression.
308
+
309
+ Returns a tuple of (field_name, pattern_type, values) if optimization is possible,
310
+ where pattern_type is one of: 'contains', 'startswith', 'endswith'.
311
+ Returns None if optimization is not applicable.
312
+ """
313
+ if not self.optimize_or_as_regex:
314
+ return None
315
+
316
+ # Check if we have enough terms to optimize
317
+ if len(cond.args) < self.min_or_terms_for_optimization:
318
+ return None
319
+
320
+ # All args must be ConditionFieldEqualsValueExpression
321
+ if not all(isinstance(arg, ConditionFieldEqualsValueExpression) for arg in cond.args):
322
+ return None
323
+
324
+ # Extract field names and check they're all the same
325
+ # Type narrowing: at this point we know all args are ConditionFieldEqualsValueExpression
326
+ field_exprs = [arg for arg in cond.args if isinstance(arg, ConditionFieldEqualsValueExpression)]
327
+ fields = [arg.field for arg in field_exprs]
328
+ if len(set(fields)) != 1:
329
+ return None # Different fields, can't optimize
330
+
331
+ field_name = fields[0]
332
+
333
+ # Check all values are SigmaString and determine pattern type
334
+ pattern_type: Optional[str] = None
335
+ values: List[str] = []
336
+
337
+ for arg in field_exprs:
338
+ if not isinstance(arg.value, SigmaString):
339
+ return None # Not a string value, can't optimize
340
+
341
+ value = arg.value
342
+
343
+ # Determine the pattern type based on wildcards
344
+ if value.startswith(SpecialChars.WILDCARD_MULTI) and value.endswith(SpecialChars.WILDCARD_MULTI):
345
+ # Contains pattern: *value*
346
+ current_pattern = 'contains'
347
+ # Extract the actual value without wildcards
348
+ actual_value = str(value)[1:-1]
349
+ elif value.startswith(SpecialChars.WILDCARD_MULTI):
350
+ # Endswith pattern: *value
351
+ current_pattern = 'endswith'
352
+ actual_value = str(value)[1:]
353
+ elif value.endswith(SpecialChars.WILDCARD_MULTI):
354
+ # Startswith pattern: value*
355
+ current_pattern = 'startswith'
356
+ actual_value = str(value)[:-1]
357
+ else:
358
+ # No wildcards, can't optimize as regex
359
+ return None
360
+
361
+ # Check if pattern type is consistent
362
+ if pattern_type is None:
363
+ pattern_type = current_pattern
364
+ elif pattern_type != current_pattern:
365
+ # Mixed patterns, can't optimize into single regex
366
+ return None
367
+
368
+ values.append(actual_value)
369
+
370
+ # Ensure pattern_type is not None before returning
371
+ if pattern_type is None:
372
+ return None
373
+
374
+ return (field_name, pattern_type, values)
375
+
376
+ def _build_regex_pattern(self, pattern_type: str, values: List[str]) -> str:
377
+ """
378
+ Build a case-insensitive regex pattern for the given pattern type and values.
379
+
380
+ Uses (?i) flag for case-insensitivity (Java regex compatible).
381
+ """
382
+ # Escape each value for use in regex (Java regex compatible)
383
+ escaped_values = [re.escape(str(v)) for v in values]
384
+
385
+ # Join values with pipe (OR in regex)
386
+ alternatives = '|'.join(escaped_values)
387
+
388
+ # Build pattern based on type
389
+ if pattern_type == 'contains':
390
+ return f'(?i).*({alternatives}).*'
391
+ elif pattern_type == 'startswith':
392
+ return f'(?i)({alternatives}).*'
393
+ elif pattern_type == 'endswith':
394
+ return f'(?i).*({alternatives})'
395
+ else:
396
+ raise ValueError(f"Unknown pattern type: {pattern_type}")
397
+
398
+ def convert_condition_or(
399
+ self, cond: ConditionOR, state: ConversionState
400
+ ) -> Union[str, DeferredQueryExpression]:
401
+ """
402
+ Conversion of OR conditions with optimization for repeated string matching patterns.
403
+
404
+ If multiple OR conditions match the same field with the same pattern type
405
+ (contains/startswith/endswith), they are optimized into a single regex expression.
406
+ """
407
+ # Try to optimize as regex
408
+ optimization = self._analyze_or_for_regex_optimization(cond)
409
+
410
+ if optimization:
411
+ field_name, pattern_type, values = optimization
412
+
413
+ # Build the optimized regex pattern
414
+ regex_pattern = self._build_regex_pattern(pattern_type, values)
415
+
416
+ # Use the re_expression format with escaped field name
417
+ field = self.escape_and_quote_field(field_name)
418
+ if self.re_expression:
419
+ return self.re_expression.format(field=field, regex=regex_pattern)
420
+ raise ValueError("re_expression is not defined")
421
+
422
+ # Fall back to default OR conversion
423
+ return super().convert_condition_or(cond, state)
424
+
425
+ # TODO: implement custom methods for query elements not covered by the default backend base.
426
+ # Documentation: https://sigmahq-pysigma.readthedocs.io/en/latest/Backends.html
427
+
428
+ @staticmethod
429
+ def finalize_query_dbsql(rule: SigmaRule, query: str, index: int, state: ConversionState) -> Any:
430
+ rule_status = (rule.status.name if rule.status else "test").lower()
431
+ title = rule.title.replace('\n', ' ')
432
+ return f"-- title: \"{title}\". status: {rule_status}\n{query}"
433
+
434
+ @staticmethod
435
+ def finalize_output_dbsql(queries: List[str]) -> Any:
436
+ return "\n\n".join(queries)
437
+
438
+ @staticmethod
439
+ def finalize_query_detection_yaml(rule: SigmaRule, query: str, index: int, state: ConversionState) -> Any:
440
+ statuses = {"experimental": "test", "stable": "release"}
441
+ levels = {SigmaLevel.INFORMATIONAL.name: 0, SigmaLevel.LOW.name: 10, SigmaLevel.MEDIUM.name: 30,
442
+ SigmaLevel.HIGH.name: 50, SigmaLevel.CRITICAL.name: 90}
443
+ rule_status = (rule.status.name if rule.status else "test").lower()
444
+ d: Dict[str, Any] = {"name": rule.title,
445
+ "sql": query,
446
+ "status": statuses.get(rule_status, rule_status),
447
+ "template": rule.title,
448
+ }
449
+ if rule.level:
450
+ level = levels.get(rule.level.name)
451
+ if level:
452
+ d["severity"] = level
453
+ return json.dumps(d)
454
+
455
+ @staticmethod
456
+ def finalize_output_detection_yaml(queries: List[str]) -> Any:
457
+ data: Dict[str, Any] = {"description": "Detections generated from Sigma rules"}
458
+ detections: List[Any] = []
459
+ for query in queries:
460
+ d = json.loads(query)
461
+ if d["status"] == "deprecated" or d["status"] == "unsupported" or d["sql"] == "":
462
+ continue
463
+ detections.append(d)
464
+ data["detections"] = detections
465
+ return yaml.dump(data, default_flow_style=False)
@@ -0,0 +1 @@
1
+ from .snake_case import snake_case
@@ -0,0 +1,20 @@
1
+ from dataclasses import dataclass, field
2
+ from typing import Union, List, Dict, Callable
3
+
4
+ import inflection
5
+ from sigma.processing.pipeline import ProcessingItem, ProcessingPipeline
6
+ from sigma.processing.transformations import FieldFunctionTransformation
7
+
8
+
9
+ # Processing pipelines should be defined as functions that return a ProcessingPipeline object.
10
+ def snake_case() -> ProcessingPipeline:
11
+ return ProcessingPipeline(
12
+ name="Snake case names conversion pipeline",
13
+ priority=20, # The priority defines the order pipelines are applied. See documentation for common values.
14
+ items=[
15
+ ProcessingItem( # Field mappings
16
+ identifier="snake_case",
17
+ transformation=FieldFunctionTransformation({}, inflection.underscore),
18
+ )
19
+ ],
20
+ )