pySigma-backend-elasticsearch 1.0.6__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,166 @@
1
+
2
+ GNU LESSER GENERAL PUBLIC LICENSE
3
+ Version 3, 29 June 2007
4
+
5
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
6
+ Everyone is permitted to copy and distribute verbatim copies
7
+ of this license document, but changing it is not allowed.
8
+
9
+
10
+ This version of the GNU Lesser General Public License incorporates
11
+ the terms and conditions of version 3 of the GNU General Public
12
+ License, supplemented by the additional permissions listed below.
13
+
14
+ 0. Additional Definitions.
15
+
16
+ As used herein, "this License" refers to version 3 of the GNU Lesser
17
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
18
+ General Public License.
19
+
20
+ "The Library" refers to a covered work governed by this License,
21
+ other than an Application or a Combined Work as defined below.
22
+
23
+ An "Application" is any work that makes use of an interface provided
24
+ by the Library, but which is not otherwise based on the Library.
25
+ Defining a subclass of a class defined by the Library is deemed a mode
26
+ of using an interface provided by the Library.
27
+
28
+ A "Combined Work" is a work produced by combining or linking an
29
+ Application with the Library. The particular version of the Library
30
+ with which the Combined Work was made is also called the "Linked
31
+ Version".
32
+
33
+ The "Minimal Corresponding Source" for a Combined Work means the
34
+ Corresponding Source for the Combined Work, excluding any source code
35
+ for portions of the Combined Work that, considered in isolation, are
36
+ based on the Application, and not on the Linked Version.
37
+
38
+ The "Corresponding Application Code" for a Combined Work means the
39
+ object code and/or source code for the Application, including any data
40
+ and utility programs needed for reproducing the Combined Work from the
41
+ Application, but excluding the System Libraries of the Combined Work.
42
+
43
+ 1. Exception to Section 3 of the GNU GPL.
44
+
45
+ You may convey a covered work under sections 3 and 4 of this License
46
+ without being bound by section 3 of the GNU GPL.
47
+
48
+ 2. Conveying Modified Versions.
49
+
50
+ If you modify a copy of the Library, and, in your modifications, a
51
+ facility refers to a function or data to be supplied by an Application
52
+ that uses the facility (other than as an argument passed when the
53
+ facility is invoked), then you may convey a copy of the modified
54
+ version:
55
+
56
+ a) under this License, provided that you make a good faith effort to
57
+ ensure that, in the event an Application does not supply the
58
+ function or data, the facility still operates, and performs
59
+ whatever part of its purpose remains meaningful, or
60
+
61
+ b) under the GNU GPL, with none of the additional permissions of
62
+ this License applicable to that copy.
63
+
64
+ 3. Object Code Incorporating Material from Library Header Files.
65
+
66
+ The object code form of an Application may incorporate material from
67
+ a header file that is part of the Library. You may convey such object
68
+ code under terms of your choice, provided that, if the incorporated
69
+ material is not limited to numerical parameters, data structure
70
+ layouts and accessors, or small macros, inline functions and templates
71
+ (ten or fewer lines in length), you do both of the following:
72
+
73
+ a) Give prominent notice with each copy of the object code that the
74
+ Library is used in it and that the Library and its use are
75
+ covered by this License.
76
+
77
+ b) Accompany the object code with a copy of the GNU GPL and this license
78
+ document.
79
+
80
+ 4. Combined Works.
81
+
82
+ You may convey a Combined Work under terms of your choice that,
83
+ taken together, effectively do not restrict modification of the
84
+ portions of the Library contained in the Combined Work and reverse
85
+ engineering for debugging such modifications, if you also do each of
86
+ the following:
87
+
88
+ a) Give prominent notice with each copy of the Combined Work that
89
+ the Library is used in it and that the Library and its use are
90
+ covered by this License.
91
+
92
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
93
+ document.
94
+
95
+ c) For a Combined Work that displays copyright notices during
96
+ execution, include the copyright notice for the Library among
97
+ these notices, as well as a reference directing the user to the
98
+ copies of the GNU GPL and this license document.
99
+
100
+ d) Do one of the following:
101
+
102
+ 0) Convey the Minimal Corresponding Source under the terms of this
103
+ License, and the Corresponding Application Code in a form
104
+ suitable for, and under terms that permit, the user to
105
+ recombine or relink the Application with a modified version of
106
+ the Linked Version to produce a modified Combined Work, in the
107
+ manner specified by section 6 of the GNU GPL for conveying
108
+ Corresponding Source.
109
+
110
+ 1) Use a suitable shared library mechanism for linking with the
111
+ Library. A suitable mechanism is one that (a) uses at run time
112
+ a copy of the Library already present on the user's computer
113
+ system, and (b) will operate properly with a modified version
114
+ of the Library that is interface-compatible with the Linked
115
+ Version.
116
+
117
+ e) Provide Installation Information, but only if you would otherwise
118
+ be required to provide such information under section 6 of the
119
+ GNU GPL, and only to the extent that such information is
120
+ necessary to install and execute a modified version of the
121
+ Combined Work produced by recombining or relinking the
122
+ Application with a modified version of the Linked Version. (If
123
+ you use option 4d0, the Installation Information must accompany
124
+ the Minimal Corresponding Source and Corresponding Application
125
+ Code. If you use option 4d1, you must provide the Installation
126
+ Information in the manner specified by section 6 of the GNU GPL
127
+ for conveying Corresponding Source.)
128
+
129
+ 5. Combined Libraries.
130
+
131
+ You may place library facilities that are a work based on the
132
+ Library side by side in a single library together with other library
133
+ facilities that are not Applications and are not covered by this
134
+ License, and convey such a combined library under terms of your
135
+ choice, if you do both of the following:
136
+
137
+ a) Accompany the combined library with a copy of the same work based
138
+ on the Library, uncombined with any other library facilities,
139
+ conveyed under the terms of this License.
140
+
141
+ b) Give prominent notice with the combined library that part of it
142
+ is a work based on the Library, and explaining where to find the
143
+ accompanying uncombined form of the same work.
144
+
145
+ 6. Revised Versions of the GNU Lesser General Public License.
146
+
147
+ The Free Software Foundation may publish revised and/or new versions
148
+ of the GNU Lesser General Public License from time to time. Such new
149
+ versions will be similar in spirit to the present version, but may
150
+ differ in detail to address new problems or concerns.
151
+
152
+ Each version is given a distinguishing version number. If the
153
+ Library as you received it specifies that a certain numbered version
154
+ of the GNU Lesser General Public License "or any later version"
155
+ applies to it, you have the option of following the terms and
156
+ conditions either of that published version or of any later version
157
+ published by the Free Software Foundation. If the Library as you
158
+ received it does not specify a version number of the GNU Lesser
159
+ General Public License, you may choose any version of the GNU Lesser
160
+ General Public License ever published by the Free Software Foundation.
161
+
162
+ If the Library as you received it specifies that a proxy can decide
163
+ whether future versions of the GNU Lesser General Public License shall
164
+ apply, that proxy's public statement of acceptance of any version is
165
+ permanent authorization for you to choose that version for the
166
+ Library.
@@ -0,0 +1,49 @@
1
+ Metadata-Version: 2.1
2
+ Name: pySigma-backend-elasticsearch
3
+ Version: 1.0.6
4
+ Summary: pySigma Elasticsearch backend
5
+ Home-page: https://github.com/SigmaHQ/pySigma-backend-elasticsearch
6
+ License: LGPL-3.0-only
7
+ Author: Thomas Patzke
8
+ Author-email: thomas@patzke.org
9
+ Requires-Python: >=3.8,<4.0
10
+ Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.8
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Requires-Dist: pysigma (>=0.10.2,<0.11.0)
17
+ Project-URL: Repository, https://github.com/SigmaHQ/pySigma-backend-elasticsearch
18
+ Description-Content-Type: text/markdown
19
+
20
+ ![Tests](https://github.com/SigmaHQ/pySigma-backend-elasticsearch/actions/workflows/test.yml/badge.svg)
21
+ ![Coverage
22
+ Badge](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/thomaspatzke/3c445ef26310e9f2d2ca09c697db1c71/raw/SigmaHQ-pySigma-backend-elasticsearch.json)
23
+ ![Status](https://img.shields.io/badge/Status-release-green)
24
+
25
+ # pySigma Elasticsearch Backend
26
+
27
+ This is the Elasticsearch backend for pySigma. It provides the package `sigma.backends.elasticsearch` with the `LuceneBackend` class.
28
+
29
+ It supports the following output formats:
30
+
31
+ * default: Lucene queries.
32
+ * dsl_lucene: DSL with embedded Lucene queries.
33
+ * kibana_ndjson: Kibana NDJSON with Lucene queries.
34
+
35
+ Further, it contains the following processing pipelines in `sigma.pipelines.elasticsearch`:
36
+
37
+ * ecs_windows in windows submodule: ECS mapping for Windows event logs ingested with Winlogbeat.
38
+ * ecs_windows_old in windows submodule: ECS mapping for Windows event logs ingested with Winlogbeat <= 6.x.
39
+ * ecs_zeek_beats in zeek submodule: Zeek ECS mapping from Elastic.
40
+ * ecs_zeek_corelight in zeek submodule: Zeek ECS mapping from Corelight.
41
+ * zeek_raw in zeek submodule: Zeek raw JSON log field naming.
42
+
43
+ This backend is currently maintained by:
44
+
45
+ * [Thomas Patzke](https://github.com/SigmaHQ/)
46
+ * [Hendrik Bäcker](https://github.com/andurin)
47
+
48
+ Further maintainers required! Send a message to [Thomas](mailto:thomas@patzke.org) if you want to co-maintain this
49
+ backend.
@@ -0,0 +1,30 @@
1
+ ![Tests](https://github.com/SigmaHQ/pySigma-backend-elasticsearch/actions/workflows/test.yml/badge.svg)
2
+ ![Coverage
3
+ Badge](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/thomaspatzke/3c445ef26310e9f2d2ca09c697db1c71/raw/SigmaHQ-pySigma-backend-elasticsearch.json)
4
+ ![Status](https://img.shields.io/badge/Status-release-green)
5
+
6
+ # pySigma Elasticsearch Backend
7
+
8
+ This is the Elasticsearch backend for pySigma. It provides the package `sigma.backends.elasticsearch` with the `LuceneBackend` class.
9
+
10
+ It supports the following output formats:
11
+
12
+ * default: Lucene queries.
13
+ * dsl_lucene: DSL with embedded Lucene queries.
14
+ * kibana_ndjson: Kibana NDJSON with Lucene queries.
15
+
16
+ Further, it contains the following processing pipelines in `sigma.pipelines.elasticsearch`:
17
+
18
+ * ecs_windows in windows submodule: ECS mapping for Windows event logs ingested with Winlogbeat.
19
+ * ecs_windows_old in windows submodule: ECS mapping for Windows event logs ingested with Winlogbeat <= 6.x.
20
+ * ecs_zeek_beats in zeek submodule: Zeek ECS mapping from Elastic.
21
+ * ecs_zeek_corelight in zeek submodule: Zeek ECS mapping from Corelight.
22
+ * zeek_raw in zeek submodule: Zeek raw JSON log field naming.
23
+
24
+ This backend is currently maintained by:
25
+
26
+ * [Thomas Patzke](https://github.com/SigmaHQ/)
27
+ * [Hendrik Bäcker](https://github.com/andurin)
28
+
29
+ Further maintainers required! Send a message to [Thomas](mailto:thomas@patzke.org) if you want to co-maintain this
30
+ backend.
@@ -0,0 +1,38 @@
1
+ [tool.poetry]
2
+ name = "pySigma-backend-elasticsearch"
3
+ version = "1.0.6"
4
+ description = "pySigma Elasticsearch backend"
5
+ readme = "README.md"
6
+ authors = ["Thomas Patzke <thomas@patzke.org>", "Hendrik Baecker <hb@process-zero.de>"]
7
+ license = "LGPL-3.0-only"
8
+ repository = "https://github.com/SigmaHQ/pySigma-backend-elasticsearch"
9
+ packages = [
10
+ { include = "sigma" }
11
+ ]
12
+
13
+ [tool.poetry.dependencies]
14
+ python = "^3.8"
15
+ pysigma = "^0.10.2"
16
+
17
+ [tool.poetry.group.dev.dependencies]
18
+ pytest = "^7.3.0"
19
+ pytest-cov = "^4.0.0"
20
+ coverage = "^6.4.1"
21
+ requests = "^2.28.1"
22
+ autopep8 = "^2.0.2"
23
+ pylint = "^2.17.2"
24
+
25
+ [build-system]
26
+ requires = ["poetry-core>=1.0.0"]
27
+ build-backend = "poetry.core.masonry.api"
28
+
29
+ [tool.pylint.'MESSAGES CONTROL']
30
+ disable = "missing-function-docstring,missing-module-docstring,line-too-long,too-many-lines"
31
+
32
+ [tool.pytest.ini_options]
33
+ minversion = "6.0"
34
+ python_files = "test_*.py"
35
+ addopts = "-vv --cov=sigma --cov-report term --cov-report xml:cov.xml"
36
+ testpaths = [
37
+ "tests",
38
+ ]
@@ -0,0 +1,5 @@
1
+ from .elasticsearch import LuceneBackend
2
+
3
+ backends = {
4
+ "elasticsearch": LuceneBackend,
5
+ }
@@ -0,0 +1,391 @@
1
+ import re
2
+ import json
3
+ from typing import ClassVar, Dict, List, Optional, Pattern, Tuple, Union
4
+
5
+ from sigma.conversion.state import ConversionState
6
+ from sigma.rule import SigmaRule
7
+ from sigma.conversion.base import TextQueryBackend
8
+ from sigma.conversion.deferred import DeferredQueryExpression
9
+ from sigma.conditions import ConditionItem, ConditionAND, ConditionOR, ConditionNOT, ConditionFieldEqualsValueExpression
10
+ from sigma.types import SigmaCompareExpression, SigmaNull
11
+ import sigma
12
+
13
+
14
+ class LuceneBackend(TextQueryBackend):
15
+ """
16
+ Elasticsearch query string backend. Generates query strings described here in the
17
+ Elasticsearch documentation:
18
+
19
+ https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html#query-string-syntax
20
+ """
21
+ # A descriptive name of the backend
22
+ name: ClassVar[str] = "Elasticsearch Lucene"
23
+ # Output formats provided by the backend as name -> description mapping.
24
+ # The name should match to finalize_output_<name>.
25
+ formats: ClassVar[Dict[str, str]] = {
26
+ "default": "Plain Elasticsearch Lucene queries",
27
+ "kibana_ndjson": "Kibana NDJSON import file with Lucene queries",
28
+ "dsl_lucene": "Elasticsearch query DSL with embedded Lucene queries",
29
+ "siem_rule": "Elasticsearch query DSL as SIEM Rules in JSON Format",
30
+ "siem_rule_ndjson": "Elasticsearch query DSL as SIEM Rules in NDJSON Format",
31
+ }
32
+ # Does the backend requires that a processing pipeline is provided?
33
+ requires_pipeline: ClassVar[bool] = True
34
+
35
+ # Operator precedence: tuple of Condition{AND,OR,NOT} in order of precedence.
36
+ # The backend generates grouping if required
37
+ precedence: ClassVar[Tuple[ConditionItem, ConditionItem, ConditionItem]] = (
38
+ ConditionNOT, ConditionOR, ConditionAND)
39
+ # Expression for precedence override grouping as format string with {expr} placeholder
40
+ group_expression: ClassVar[str] = "({expr})"
41
+ parenthesize: bool = True
42
+
43
+ # Generated query tokens
44
+ token_separator: str = " " # separator inserted between all boolean operators
45
+ or_token: ClassVar[str] = "OR"
46
+ and_token: ClassVar[str] = "AND"
47
+ not_token: ClassVar[str] = "NOT"
48
+ # Token inserted between field and value (without separator)
49
+ eq_token: ClassVar[str] = ":"
50
+
51
+ # String output
52
+ # Fields
53
+ # No quoting of field names
54
+ # Escaping
55
+ # Character to escape particular parts defined in field_escape_pattern.
56
+ field_escape: ClassVar[str] = "\\"
57
+ # All matches of this pattern are prepended with the string contained in field_escape.
58
+ field_escape_pattern: ClassVar[Pattern] = re.compile("[\\s*]")
59
+
60
+ # Values
61
+ # string quoting character (added as escaping character)
62
+ str_quote: ClassVar[str] = '"'
63
+ str_quote_pattern: ClassVar[Pattern] = re.compile(r"^$|.*\s.*")
64
+ str_quote_pattern_negation: ClassVar[bool] = False
65
+ # Escaping character for special characrers inside string
66
+ escape_char: ClassVar[str] = "\\"
67
+ # Character used as multi-character wildcard
68
+ wildcard_multi: ClassVar[str] = "*"
69
+ # Character used as single-character wildcard
70
+ wildcard_single: ClassVar[str] = "?"
71
+ # Characters quoted in addition to wildcards and string quote
72
+ add_escaped: ClassVar[str] = '+-=&|!(){}[]<>^"~*?:\\/ '
73
+ bool_values: ClassVar[Dict[bool, str]] = { # Values to which boolean values are mapped.
74
+ True: "true",
75
+ False: "false",
76
+ }
77
+
78
+ # Regular expressions
79
+ # Regular expression query as format string with placeholders {field} and {regex}
80
+ re_expression: ClassVar[str] = "{field}:/{regex}/"
81
+ # Character used for escaping in regular expressions
82
+ re_escape_char: ClassVar[str] = "\\"
83
+ re_escape: ClassVar[Tuple[str]] = ("/",)
84
+ # Don't escape the escape char
85
+ re_escape_escape_char: ClassVar[bool] = False
86
+
87
+ # cidr expressions
88
+ # CIDR expression query as format string with placeholders {field} = {value}
89
+ cidr_expression: ClassVar[str] = "{field}:{network}\\/{prefixlen}"
90
+
91
+ # Numeric comparison operators
92
+ # Compare operation query as format string with placeholders {field}, {operator} and {value}
93
+ compare_op_expression: ClassVar[str] = "{field}:{operator}{value}"
94
+ # Mapping between CompareOperators elements and strings used as replacement
95
+ # for {operator} in compare_op_expression
96
+ compare_operators: ClassVar[Dict[SigmaCompareExpression.CompareOperators, str]] = {
97
+ SigmaCompareExpression.CompareOperators.LT: "<",
98
+ SigmaCompareExpression.CompareOperators.LTE: "<=",
99
+ SigmaCompareExpression.CompareOperators.GT: ">",
100
+ SigmaCompareExpression.CompareOperators.GTE: ">=",
101
+ }
102
+
103
+ # Null/None expressions
104
+ # Expression for field has null value as format string with {field} placeholder for field name
105
+ field_null_expression: ClassVar[str] = "NOT _exists_:{field}"
106
+
107
+ # Field value in list, e.g. "field in (value list)" or "field containsall (value list)"
108
+ # Convert OR as in-expression
109
+ convert_or_as_in: ClassVar[bool] = True
110
+ # Convert AND as in-expression
111
+ convert_and_as_in: ClassVar[bool] = False
112
+ # Values in list can contain wildcards. If set to False (default)
113
+ # only plain values are converted into in-expressions.
114
+ in_expressions_allow_wildcards: ClassVar[bool] = True
115
+ # Expression for field in list of values as format string with
116
+ # placeholders {field}, {op} and {list}
117
+ field_in_list_expression: ClassVar[str] = "{field}{op}({list})"
118
+ # Operator used to convert OR into in-expressions. Must be set if convert_or_as_in is set
119
+ or_in_operator: ClassVar[str] = ":"
120
+ # List element separator
121
+ list_separator: ClassVar[str] = " OR "
122
+
123
+ # Value not bound to a field
124
+ # Expression for string value not bound to a field as format string with placeholder {value}
125
+ unbound_value_str_expression: ClassVar[str] = '"{value}"'
126
+ # Expression for number value not bound to a field as format string with placeholder {value}
127
+ unbound_value_num_expression: ClassVar[str] = '{value}'
128
+
129
+ def __init__(
130
+ self,
131
+ processing_pipeline: Optional["sigma.processing.pipeline.ProcessingPipeline"] = None,
132
+ collect_errors: bool = False,
133
+ index_names: List = [
134
+ "apm-*-transaction*",
135
+ "auditbeat-*",
136
+ "endgame-*",
137
+ "filebeat-*",
138
+ "logs-*",
139
+ "packetbeat-*",
140
+ "traces-apm*",
141
+ "winlogbeat-*",
142
+ "-*elastic-cloud-logs-*"
143
+ ],
144
+ schedule_interval: int = 5,
145
+ schedule_interval_unit: str = "m",
146
+ **kwargs):
147
+
148
+ super().__init__(processing_pipeline, collect_errors, **kwargs)
149
+ self.index_names = index_names or [
150
+ "apm-*-transaction*",
151
+ "auditbeat-*",
152
+ "endgame-*",
153
+ "filebeat-*",
154
+ "logs-*",
155
+ "packetbeat-*",
156
+ "traces-apm*",
157
+ "winlogbeat-*",
158
+ "-*elastic-cloud-logs-*"
159
+ ]
160
+ self.schedule_interval = schedule_interval or 5
161
+ self.schedule_interval_unit = schedule_interval_unit or "m"
162
+ self.severity_risk_mapping = {
163
+ "INFORMATIONAL": 1,
164
+ "LOW": 21,
165
+ "MEDIUM": 47,
166
+ "HIGH": 73,
167
+ "CRITICAL": 99
168
+ }
169
+
170
+ @staticmethod
171
+ def _is_field_null_condition(cond : ConditionItem) -> bool:
172
+ return isinstance(cond, ConditionFieldEqualsValueExpression) and isinstance(cond.value, SigmaNull)
173
+
174
+ def convert_condition_not(self, cond : ConditionNOT, state : ConversionState) -> Union[str, DeferredQueryExpression]:
175
+ """When checking if a field is not null, convert "NOT NOT _exists_:field" to "_exists_:field"."""
176
+ if LuceneBackend._is_field_null_condition(cond.args[0]):
177
+ return f"_exists_:{cond.args[0].field}"
178
+
179
+ return super().convert_condition_not(cond, state)
180
+
181
+ def compare_precedence(self, outer : ConditionItem, inner : ConditionItem) -> bool:
182
+ """Override precedence check for null field conditions."""
183
+ if isinstance(inner, ConditionNOT) and LuceneBackend._is_field_null_condition(inner.args[0]):
184
+ # inner will turn into "_exists_:field", no parentheses needed
185
+ return True
186
+
187
+ if LuceneBackend._is_field_null_condition(inner):
188
+ # inner will turn into "NOT _exists_:field", force parentheses
189
+ return False
190
+
191
+ return super().compare_precedence(outer, inner)
192
+
193
+ def finalize_query_dsl_lucene(
194
+ self,
195
+ rule: SigmaRule,
196
+ query: str,
197
+ index: int,
198
+ state: ConversionState) -> Dict:
199
+
200
+ return {
201
+ "query": {
202
+ "bool": {
203
+ "must": [
204
+ {
205
+ "query_string": {
206
+ "query": query,
207
+ "analyze_wildcard": True
208
+ }
209
+ }
210
+ ]
211
+ }
212
+ }
213
+ }
214
+
215
+ def finalize_output_dsl_lucene(self, queries: List[Dict]) -> Dict:
216
+ return list(queries)
217
+
218
+ def finalize_query_kibana_ndjson(
219
+ self,
220
+ rule: SigmaRule,
221
+ query: str,
222
+ index: int,
223
+ state: ConversionState
224
+ ) -> Dict:
225
+
226
+ # TODO: implement the per-query output for the output format kibana here. Usually, the
227
+ # generated query is embedded into a template, e.g. a JSON format with additional
228
+ # information from the Sigma rule.
229
+ columns = []
230
+ index = "beats-*"
231
+ ndjson = {
232
+ "id": str(rule.id),
233
+ "type": "search",
234
+ "attributes": {
235
+ "title": f"SIGMA - {rule.title}",
236
+ "description": rule.description,
237
+ "hits": 0,
238
+ "columns": columns,
239
+ "sort": ["@timestamp", "desc"],
240
+ "version": 1,
241
+ "kibanaSavedObjectMeta": {
242
+ "searchSourceJSON": str(json.dumps({
243
+ "index": index,
244
+ "filter": [],
245
+ "highlight": {
246
+ "pre_tags": ["@kibana-highlighted-field@"],
247
+ "post_tags": ["@/kibana-highlighted-field@"],
248
+ "fields": {"*": {}},
249
+ "require_field_match": False,
250
+ "fragment_size": 2147483647
251
+ },
252
+ "query": {
253
+ "query_string": {
254
+ "query": query,
255
+ "analyze_wildcard": True
256
+ }
257
+ }
258
+ })
259
+ )
260
+ }
261
+ },
262
+ "references": [
263
+ {
264
+ "id": index,
265
+ "name": "kibanaSavedObjectMeta.searchSourceJSON.index",
266
+ "type": "index-pattern"
267
+ }
268
+ ]
269
+ }
270
+ return ndjson
271
+
272
+ def finalize_output_kibana_ndjson(self, queries: List[str]) -> List[Dict]:
273
+ # TODO: implement the output finalization for all generated queries for the format kibana
274
+ # here. Usually, the single generated queries are embedded into a structure, e.g. some
275
+ # JSON or XML that can be imported into the SIEM.
276
+ return list(queries)
277
+
278
+ def finalize_query_siem_rule(
279
+ self,
280
+ rule: SigmaRule,
281
+ query: str,
282
+ index: int,
283
+ state: ConversionState
284
+ ) -> Dict:
285
+ """
286
+ Create SIEM Rules in JSON Format. These rules could be imported into Kibana using the
287
+ Create Rule API https://www.elastic.co/guide/en/kibana/8.6/create-rule-api.html
288
+ This API (and generated data) is NOT the same like importing Detection Rules via:
289
+ Kibana -> Security -> Alerts -> Manage Rules -> Import
290
+ If you want to have a nice importable NDJSON File for the Security Rule importer
291
+ use pySigma Format 'siem_rule_ndjson' instead.
292
+ """
293
+
294
+ siem_rule = {
295
+ "name": f"SIGMA - {rule.title}",
296
+ "tags": [f"{n.namespace}-{n.name}" for n in rule.tags],
297
+ "consumer": "siem",
298
+ "enabled": True,
299
+ "throttle": None,
300
+ "schedule": {
301
+ "interval": f"{self.schedule_interval}{self.schedule_interval_unit}"
302
+ },
303
+ "params": {
304
+ "author": [rule.author] if rule.author is not None else [],
305
+ "description": rule.description if rule.description is not None else "No description",
306
+ "ruleId": str(rule.id),
307
+ "falsePositives": rule.falsepositives,
308
+ "from": f"now-{self.schedule_interval}{self.schedule_interval_unit}",
309
+ "immutable": False,
310
+ "license": "DRL",
311
+ "outputIndex": "",
312
+ "meta": {
313
+ "from": "1m",
314
+ },
315
+ "maxSignals": 100,
316
+ "riskScore": self.severity_risk_mapping[rule.level.name] if rule.level is not None else 21,
317
+ "riskScoreMapping": [],
318
+ "severity": str(rule.level.name).lower() if rule.level is not None else "low",
319
+ "severityMapping": [],
320
+ "threat": [],
321
+ "to": "now",
322
+ "references": rule.references,
323
+ "version": 1,
324
+ "exceptionsList": [],
325
+ "relatedIntegrations": [],
326
+ "requiredFields": [],
327
+ "setup": "",
328
+ "type": "query",
329
+ "language": "lucene",
330
+ "index": self.index_names,
331
+ "query": query,
332
+ "filters": []
333
+ },
334
+ "rule_type_id": "siem.queryRule",
335
+ "notify_when": "onActiveAlert",
336
+ "actions": []
337
+ }
338
+ return siem_rule
339
+
340
+ def finalize_output_siem_rule(self, queries: List[Dict]) -> Dict:
341
+ return list(queries)
342
+
343
+ def finalize_query_siem_rule_ndjson(self, rule: SigmaRule, query: str, index: int, state: ConversionState) -> Dict:
344
+ """
345
+ Generating SIEM/Detection Rules in NDJSON Format. Compatible with
346
+
347
+ https://www.elastic.co/guide/en/security/8.6/rules-ui-management.html#import-export-rules-ui
348
+ """
349
+
350
+ siem_rule = {
351
+ "id": str(rule.id),
352
+ "name": f"SIGMA - {rule.title}",
353
+ "tags": [f"{n.namespace}-{n.name}" for n in rule.tags],
354
+ "enabled": True,
355
+ "throttle": "no_actions",
356
+ "interval": f"{self.schedule_interval}{self.schedule_interval_unit}",
357
+ "author": [rule.author] if rule.author is not None else [],
358
+ "description": rule.description if rule.description is not None else "No description",
359
+ "rule_id": str(rule.id),
360
+ "false_positives": rule.falsepositives,
361
+ "from": f"now-{self.schedule_interval}{self.schedule_interval_unit}",
362
+ "immutable": False,
363
+ "license": "DRL",
364
+ "output_index": "",
365
+ "meta": {
366
+ "from": "1m",
367
+ },
368
+ "max_signals": 100,
369
+ "risk_score": self.severity_risk_mapping[rule.level.name] if rule.level is not None else 21,
370
+ "risk_score_mapping": [],
371
+ "severity": str(rule.level.name).lower() if rule.level is not None else "low",
372
+ "severity_mapping": [],
373
+ "threat": [],
374
+ "to": "now",
375
+ "references": rule.references,
376
+ "version": 1,
377
+ "exceptions_list": [],
378
+ "related_integrations": [],
379
+ "required_fields": [],
380
+ "setup": "",
381
+ "type": "query",
382
+ "language": "lucene",
383
+ "index": self.index_names,
384
+ "query": query,
385
+ "filters": [],
386
+ "actions": []
387
+ }
388
+ return siem_rule
389
+
390
+ def finalize_output_siem_rule_ndjson(self, queries: List[Dict]) -> Dict:
391
+ return list(queries)