pySigma-backend-athena 0.2.0__py3-none-any.whl
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.
- pysigma_backend_athena-0.2.0.dist-info/METADATA +300 -0
- pysigma_backend_athena-0.2.0.dist-info/RECORD +9 -0
- pysigma_backend_athena-0.2.0.dist-info/WHEEL +4 -0
- pysigma_backend_athena-0.2.0.dist-info/licenses/LICENSE +8 -0
- sigma/backends/athena/__init__.py +3 -0
- sigma/backends/athena/base.py +403 -0
- sigma/backends/athena/correlations.py +267 -0
- sigma/pipelines/athena/__init__.py +3 -0
- sigma/pipelines/athena/athena.py +106 -0
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pySigma-backend-athena
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: pySigma athena backend
|
|
5
|
+
License: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Keywords: sigma,pySigma,athena,aws
|
|
8
|
+
Author: Neil Smith
|
|
9
|
+
Author-email: neil@nsmith.net
|
|
10
|
+
Requires-Python: >=3.11,<4.0
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Programming Language :: Python
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
21
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
22
|
+
Requires-Dist: pysigma (>=2.2.0,<3.0.0)
|
|
23
|
+
Project-URL: Documentation, https://github.com/nsmithuk/pySigma-backend-athena#readme
|
|
24
|
+
Project-URL: Homepage, https://github.com/nsmithuk/pySigma-backend-athena
|
|
25
|
+
Project-URL: Issues, https://github.com/nsmithuk/pySigma-backend-athena/issues
|
|
26
|
+
Project-URL: Source, https://github.com/nsmithuk/pySigma-backend-athena
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+

|
|
30
|
+

|
|
31
|
+

|
|
32
|
+
|
|
33
|
+
# pySigma Athena Backend
|
|
34
|
+
|
|
35
|
+
An AWS Athena backend for pySigma that converts Sigma detection rules into Athena-compatible SQL queries.
|
|
36
|
+
|
|
37
|
+
While designed for AWS Athena, it likely works with any Trino-based SQL engine.
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## Features
|
|
42
|
+
|
|
43
|
+
Most standard Sigma rule features are supported, including logical and comparison operators,
|
|
44
|
+
wildcards, regular expressions, CIDR matching, field reference matching, existence checks and case-sensitive matching.
|
|
45
|
+
A handful of operations—like full-text value-only expressions and distinct-count window
|
|
46
|
+
functions—aren't implemented; see the Limitations section below.
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
## Limitations
|
|
50
|
+
|
|
51
|
+
- Full-text searches (value-only expressions) are not supported.
|
|
52
|
+
- At present, only the `event_count` correlation rule type is supported.
|
|
53
|
+
|
|
54
|
+
---
|
|
55
|
+
|
|
56
|
+
[//]: # (## Installation)
|
|
57
|
+
|
|
58
|
+
[//]: # ()
|
|
59
|
+
[//]: # (Install via pip:)
|
|
60
|
+
|
|
61
|
+
[//]: # ()
|
|
62
|
+
[//]: # (```bash)
|
|
63
|
+
|
|
64
|
+
[//]: # (pip install pySigma-backend-athena)
|
|
65
|
+
|
|
66
|
+
[//]: # (```)
|
|
67
|
+
|
|
68
|
+
[//]: # ()
|
|
69
|
+
[//]: # (Or with Poetry:)
|
|
70
|
+
|
|
71
|
+
[//]: # ()
|
|
72
|
+
[//]: # (```bash)
|
|
73
|
+
|
|
74
|
+
[//]: # (poetry add pySigma-backend-athena)
|
|
75
|
+
|
|
76
|
+
[//]: # (```)
|
|
77
|
+
|
|
78
|
+
[//]: # ()
|
|
79
|
+
[//]: # (---)
|
|
80
|
+
|
|
81
|
+
## Usage
|
|
82
|
+
|
|
83
|
+
From the CLI:
|
|
84
|
+
```shell
|
|
85
|
+
sigma convert -t athena rules/cloud/aws/cloudtrail/
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
From Python:
|
|
89
|
+
```python
|
|
90
|
+
from sigma.backends.athena import athenaBackend
|
|
91
|
+
from sigma.collection import SigmaCollection
|
|
92
|
+
|
|
93
|
+
# Initialize the backend, optionally specifying table, fields, and time field
|
|
94
|
+
backend = athenaBackend()
|
|
95
|
+
|
|
96
|
+
# Load your Sigma rule collection
|
|
97
|
+
collection = SigmaCollection.from_yaml("...")
|
|
98
|
+
|
|
99
|
+
# Convert to Athena SQL
|
|
100
|
+
queries = backend.convert(collection)
|
|
101
|
+
for q in queries:
|
|
102
|
+
print(q)
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
### Set Table Name
|
|
106
|
+
|
|
107
|
+
There are a few ways of setting the table name that will appear in the SQL.
|
|
108
|
+
|
|
109
|
+
If all of your rules use the same table name, regardless of the `logsource` set, you can pass a backend-option of `table`.
|
|
110
|
+
|
|
111
|
+
For example:
|
|
112
|
+
```python
|
|
113
|
+
athena_backend = athenaBackend(table="events")
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Will result in:
|
|
117
|
+
```sql
|
|
118
|
+
SELECT * FROM events WHERE ...
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
If you need to set your table name based on the `logsource` seen, you can use a pipeline. The backend will look for a
|
|
122
|
+
processing state value of `table_name` and, if set, will use this table name.
|
|
123
|
+
|
|
124
|
+
For example:
|
|
125
|
+
```yaml
|
|
126
|
+
name: AWS Security Lake Table Mapping
|
|
127
|
+
priority: 100
|
|
128
|
+
|
|
129
|
+
vars:
|
|
130
|
+
region: eu_west_2
|
|
131
|
+
|
|
132
|
+
transformations:
|
|
133
|
+
- id: cloudtrail_mgmt_table
|
|
134
|
+
type: set_state
|
|
135
|
+
key: table_name
|
|
136
|
+
val: "amazon_security_lake_table_{region}_cloud_trail_mgmt_2_0"
|
|
137
|
+
rule_conditions:
|
|
138
|
+
- type: logsource
|
|
139
|
+
product: aws
|
|
140
|
+
service: cloudtrail
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
### Set Table Name with AWS Security Lake
|
|
144
|
+
|
|
145
|
+
If you are using this backend with AWS Security Lake, a helper plugin is also provided for setting the correct table name.
|
|
146
|
+
|
|
147
|
+
For example, the following will map an AWS CloudTrail source to `amazon_security_lake_table_eu_west_2_cloud_trail_mgmt_2_0`.
|
|
148
|
+
|
|
149
|
+
```python
|
|
150
|
+
from sigma.pipelines.athena import athena_pipeline_security_lake_table_name
|
|
151
|
+
from sigma.backends.athena import athenaBackend
|
|
152
|
+
from sigma.collection import SigmaCollection
|
|
153
|
+
|
|
154
|
+
pipeline = athena_pipeline_security_lake_table_name()
|
|
155
|
+
backend = athenaBackend(
|
|
156
|
+
aws_table_region="eu-west-2", # Replace with your AWS region
|
|
157
|
+
processing_pipeline=pipeline,
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
rules = SigmaCollection.load_ruleset("path/to/rules/")
|
|
161
|
+
queries = backend.convert(rules)
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
This supports the following log sources:
|
|
165
|
+
* product: `aws`, service: `cloudtrail`
|
|
166
|
+
* product: `aws`, service: `cloudtrail_s3`
|
|
167
|
+
* product: `aws`, service: `cloudtrail_lambda`
|
|
168
|
+
* product: `aws`, service: `route53`
|
|
169
|
+
* product: `aws`, service: `security_hub`
|
|
170
|
+
* product: `aws`, service: `vpc_flow_logs`
|
|
171
|
+
* product: `aws`, service: `waf`
|
|
172
|
+
* product: `aws`, service: `eks_audit`
|
|
173
|
+
|
|
174
|
+
You can also use this pipeline from the CLI:
|
|
175
|
+
```shell
|
|
176
|
+
sigma convert -t athena -O aws_table_region=eu-west-2 -p athena_security_lake_table_name rules/cloud/aws/cloudtrail/
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
### Select Column Names
|
|
180
|
+
|
|
181
|
+
The backend supports the [fields](https://sigmahq.io/sigma-specification/specification/sigma-rules-specification.html#fields) attribute in Sigma rules.
|
|
182
|
+
If a Sigma rule specifies a list of fields, the generated Athena SQL query will SELECT only those specified fields instead of using `SELECT *`.
|
|
183
|
+
|
|
184
|
+
This is useful for optimising queries by retrieving only necessary data.
|
|
185
|
+
|
|
186
|
+
For example, if your Sigma rule includes:
|
|
187
|
+
```yaml
|
|
188
|
+
fields:
|
|
189
|
+
- uid
|
|
190
|
+
- time_dt
|
|
191
|
+
- process.command_line as command_line
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
The generated query will start with:
|
|
195
|
+
```sql
|
|
196
|
+
SELECT uid, time_dt, process.command_line as command_line FROM ...
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
If no `fields` are specified in the rule, the query defaults to `SELECT *`.
|
|
200
|
+
|
|
201
|
+
This feature is automatically applied when converting rules with the backend.
|
|
202
|
+
|
|
203
|
+
---
|
|
204
|
+
|
|
205
|
+
## Supported Correlation Rules
|
|
206
|
+
|
|
207
|
+
The Athena backend currently supports **event\_count** correlation rules. Other types (`value_count`, `temporal`, `temporal_ordered`) are not implemented and will raise `NotImplementedError`.
|
|
208
|
+
|
|
209
|
+
### event\_count
|
|
210
|
+
|
|
211
|
+
- **Type**: `event_count`
|
|
212
|
+
- **Parameters**:
|
|
213
|
+
- `rules`: List of Sigma rules to correlate
|
|
214
|
+
- `group-by`: Fields to partition by
|
|
215
|
+
- `timespan`: Window duration (e.g. `15m`, `1h`)
|
|
216
|
+
- `condition`: Comparison operator and threshold (e.g. `gte: 10`)
|
|
217
|
+
|
|
218
|
+
Generates a sliding time window-function query that counts matching events within the specified timeframe.
|
|
219
|
+
|
|
220
|
+
#### Example
|
|
221
|
+
|
|
222
|
+
```yaml
|
|
223
|
+
title: Windows Failed Logon
|
|
224
|
+
id: dc9f1a2e-7d3b-4f1c-b8f4-1e23eadf4567
|
|
225
|
+
status: stable
|
|
226
|
+
logsource:
|
|
227
|
+
product: windows
|
|
228
|
+
service: security
|
|
229
|
+
detection:
|
|
230
|
+
selection:
|
|
231
|
+
EventID: 4625
|
|
232
|
+
condition: selection
|
|
233
|
+
---
|
|
234
|
+
title: Possible Brute-Force Attack via Repeated Logon Failures
|
|
235
|
+
id: e8b2c3d4-5f6a-7b8c-9d0e-f1a2b3c4d5e6
|
|
236
|
+
status: stable
|
|
237
|
+
description: Detects more than 5 failed Windows logon attempts from the same source IP within 10 minutes.
|
|
238
|
+
correlation:
|
|
239
|
+
type: event_count
|
|
240
|
+
rules:
|
|
241
|
+
- dc9f1a2e-7d3b-4f1c-b8f4-1e23eadf4567
|
|
242
|
+
group-by:
|
|
243
|
+
- SourceIp
|
|
244
|
+
timespan: 10m
|
|
245
|
+
condition:
|
|
246
|
+
gte: 5
|
|
247
|
+
```
|
|
248
|
+
Gives:
|
|
249
|
+
```sql
|
|
250
|
+
WITH combined_events AS (
|
|
251
|
+
SELECT *
|
|
252
|
+
FROM <TABLE>
|
|
253
|
+
WHERE EventID = 4625
|
|
254
|
+
),
|
|
255
|
+
event_counts AS (
|
|
256
|
+
SELECT *,
|
|
257
|
+
COUNT(*) OVER (
|
|
258
|
+
PARTITION BY SourceIp
|
|
259
|
+
ORDER BY time
|
|
260
|
+
RANGE BETWEEN INTERVAL '600' SECOND PRECEDING AND CURRENT ROW
|
|
261
|
+
) AS correlation_event_count
|
|
262
|
+
FROM combined_events
|
|
263
|
+
)
|
|
264
|
+
SELECT *
|
|
265
|
+
FROM event_counts
|
|
266
|
+
WHERE correlation_event_count >= 5;
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
### Specifying the DateTime column to use for the time window
|
|
270
|
+
|
|
271
|
+
By default, the `time` column is used for the rule's sliding time window. This can be changed by setting the
|
|
272
|
+
`time_field` backend-option.
|
|
273
|
+
|
|
274
|
+
For example:
|
|
275
|
+
```python
|
|
276
|
+
athena_backend = athenaBackend(time_field="time_dt")
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
---
|
|
280
|
+
|
|
281
|
+
## Testing
|
|
282
|
+
|
|
283
|
+
Run the test suite:
|
|
284
|
+
|
|
285
|
+
```bash
|
|
286
|
+
pytest
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
---
|
|
290
|
+
|
|
291
|
+
## Maintainers
|
|
292
|
+
|
|
293
|
+
- [Neil Smith](https://github.com/nsmithuk/)
|
|
294
|
+
|
|
295
|
+
---
|
|
296
|
+
|
|
297
|
+
## License
|
|
298
|
+
|
|
299
|
+
Licensed under the [MIT License](LICENSE).
|
|
300
|
+
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
sigma/backends/athena/__init__.py,sha256=jxIIwBcd2quTemxQoYkVGjApNgfSQdDGzFgQ1rk7cxQ,69
|
|
2
|
+
sigma/backends/athena/base.py,sha256=Ix223CTZZxhvny_QYTbORmyoStWocyxXumq-61IU1yQ,16324
|
|
3
|
+
sigma/backends/athena/correlations.py,sha256=zFv6jZR4Zg1_E-NIif2duuGT9OD4-h_M3IThVJHeVpc,13254
|
|
4
|
+
sigma/pipelines/athena/__init__.py,sha256=CX97XNmNrKVLsy41C7MqsuePui-wCErxO5tG47mSTtM,117
|
|
5
|
+
sigma/pipelines/athena/athena.py,sha256=f93oKcfQkrh-1ZhZn_--k4KEzjMTGvSh2KfwpEcbVPg,4054
|
|
6
|
+
pysigma_backend_athena-0.2.0.dist-info/METADATA,sha256=SwlztFIvs8q_Ry0-FjULgvFi1TTrFVzZRHzaVX5zP5k,8203
|
|
7
|
+
pysigma_backend_athena-0.2.0.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
|
|
8
|
+
pysigma_backend_athena-0.2.0.dist-info/licenses/LICENSE,sha256=RL9fWb0FNvnl0vaSo9kp7bY5Mux62RKL8Ow2av3Z2ic,1059
|
|
9
|
+
pysigma_backend_athena-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
|
|
2
|
+
Copyright 2025 Neil Smith
|
|
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,403 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from typing import Any, ClassVar, Dict, Optional, Pattern, Tuple, Union
|
|
3
|
+
|
|
4
|
+
from sigma.conditions import (
|
|
5
|
+
ConditionAND,
|
|
6
|
+
ConditionFieldEqualsValueExpression,
|
|
7
|
+
ConditionItem,
|
|
8
|
+
ConditionNOT,
|
|
9
|
+
ConditionOR,
|
|
10
|
+
ConditionValueExpression,
|
|
11
|
+
)
|
|
12
|
+
from sigma.conversion.base import TextQueryBackend
|
|
13
|
+
from sigma.conversion.deferred import DeferredQueryExpression
|
|
14
|
+
from sigma.conversion.state import ConversionState
|
|
15
|
+
from sigma.modifiers import SigmaCaseSensitiveModifier
|
|
16
|
+
from sigma.processing.pipeline import ProcessingPipeline
|
|
17
|
+
from sigma.rule import SigmaRule
|
|
18
|
+
from sigma.types import (
|
|
19
|
+
SigmaCasedString,
|
|
20
|
+
SigmaCompareExpression,
|
|
21
|
+
SigmaFieldReference,
|
|
22
|
+
SigmaString,
|
|
23
|
+
SpecialChars,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class athenaBaseBackend(TextQueryBackend):
|
|
28
|
+
"""
|
|
29
|
+
Athena backend for converting Sigma rules into Athena-compatible SQL queries.
|
|
30
|
+
|
|
31
|
+
This backend transforms Sigma rules into queries suitable for AWS Athena, handling field
|
|
32
|
+
and value conversions, correlation rules, and query formatting. It supports case-insensitive
|
|
33
|
+
matching, wildcards, and specific correlation types like event_count and value_count.
|
|
34
|
+
|
|
35
|
+
See the pySigma documentation for further details:
|
|
36
|
+
https://sigmahq-pysigma.readthedocs.io/en/latest/Backends.html
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
def __init__(
|
|
40
|
+
self,
|
|
41
|
+
processing_pipeline: Optional[ProcessingPipeline] = None,
|
|
42
|
+
collect_errors: bool = False,
|
|
43
|
+
**backend_options: Dict,
|
|
44
|
+
):
|
|
45
|
+
"""
|
|
46
|
+
Initialize the Athena backend.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
processing_pipeline: Optional processing pipeline to apply transformations to Sigma rules.
|
|
50
|
+
collect_errors: If True, collect errors during conversion instead of raising them.
|
|
51
|
+
table: Optional, the name of the table to include in the SQL statement.
|
|
52
|
+
fields: Optional, the name of the fields to select in the SQL statement. Defaults to *.
|
|
53
|
+
**backend_options: Additional backend-specific options.
|
|
54
|
+
"""
|
|
55
|
+
super().__init__(processing_pipeline, collect_errors, **backend_options)
|
|
56
|
+
|
|
57
|
+
self._default_table_name: str = backend_options.get("table") or "<TABLE>"
|
|
58
|
+
|
|
59
|
+
self._element_at_fields: list[str] = (
|
|
60
|
+
backend_options.get("element_at_fields") or []
|
|
61
|
+
)
|
|
62
|
+
if isinstance(self._element_at_fields, str):
|
|
63
|
+
self._element_at_fields = [
|
|
64
|
+
e.strip() for e in self._element_at_fields.split(",")
|
|
65
|
+
]
|
|
66
|
+
|
|
67
|
+
# ----------------------------------------------------------------------------------------------------------
|
|
68
|
+
# General Setup
|
|
69
|
+
|
|
70
|
+
name: ClassVar[str] = "athena backend"
|
|
71
|
+
formats: ClassVar[Dict[str, str]] = {
|
|
72
|
+
"default": "Plain athena queries",
|
|
73
|
+
}
|
|
74
|
+
requires_pipeline: ClassVar[bool] = (
|
|
75
|
+
False # Backend does not require a processing pipeline.
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
# Operator precedence for boolean conditions
|
|
79
|
+
precedence: ClassVar[Tuple[ConditionItem, ConditionItem, ConditionItem]] = (
|
|
80
|
+
ConditionNOT,
|
|
81
|
+
ConditionAND,
|
|
82
|
+
ConditionOR,
|
|
83
|
+
)
|
|
84
|
+
group_expression: ClassVar[str] = "({expr})" # Grouping for precedence override
|
|
85
|
+
|
|
86
|
+
# Query tokens
|
|
87
|
+
token_separator: str = " " # Separator between boolean operators
|
|
88
|
+
or_token: ClassVar[str] = "OR"
|
|
89
|
+
and_token: ClassVar[str] = "AND"
|
|
90
|
+
not_token: ClassVar[str] = "NOT"
|
|
91
|
+
eq_token: ClassVar[str] = " = " # Token for field-value equality
|
|
92
|
+
eq_expression: ClassVar[str] = "LOWER({field}){backend.eq_token}{value}"
|
|
93
|
+
|
|
94
|
+
# Field quoting and escaping
|
|
95
|
+
field_quote: ClassVar[str] = '"' # Character to quote field names
|
|
96
|
+
field_quote_pattern: ClassVar[Pattern] = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")
|
|
97
|
+
field_quote_pattern_negation: ClassVar[bool] = (
|
|
98
|
+
True # Quote fields that don't match the pattern
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
# String value handling
|
|
102
|
+
str_quote: ClassVar[str] = "'" # String quoting character
|
|
103
|
+
escape_char: ClassVar[str] = "\\" # Escaping character for strings
|
|
104
|
+
wildcard_multi: ClassVar[str] = "%" # Multi-character wildcard
|
|
105
|
+
wildcard_single: ClassVar[str] = "_" # Single-character wildcard
|
|
106
|
+
add_escaped: ClassVar[str] = "\\" # Additional characters to escape
|
|
107
|
+
filter_chars: ClassVar[str] = "" # Characters to filter out
|
|
108
|
+
bool_values: ClassVar[Dict[bool, str]] = {True: "true", False: "false"}
|
|
109
|
+
|
|
110
|
+
# String matching expressions
|
|
111
|
+
startswith_expression: ClassVar[str] = r"LOWER({field}) LIKE '{value}%' ESCAPE '\'"
|
|
112
|
+
endswith_expression: ClassVar[str] = r"LOWER({field}) LIKE '%{value}' ESCAPE '\'"
|
|
113
|
+
contains_expression: ClassVar[str] = r"LOWER({field}) LIKE '%{value}%' ESCAPE '\'"
|
|
114
|
+
wildcard_match_expression: ClassVar[str] = r"LOWER({field}) LIKE {value} ESCAPE '\'"
|
|
115
|
+
|
|
116
|
+
# Regular expression handling
|
|
117
|
+
re_expression: ClassVar[str] = "REGEXP_LIKE({field}, '{regex}')"
|
|
118
|
+
re_escape_char: ClassVar[str] = "\\"
|
|
119
|
+
re_escape: ClassVar[Tuple[str]] = ()
|
|
120
|
+
re_escape_escape_char: bool = True
|
|
121
|
+
re_flag_prefix: bool = False
|
|
122
|
+
|
|
123
|
+
# Case-sensitive string matching
|
|
124
|
+
case_sensitive_match_expression: ClassVar[str] = "{field} = {value}"
|
|
125
|
+
case_sensitive_startswith_expression: ClassVar[str] = (
|
|
126
|
+
r"{field} LIKE '{value}%' ESCAPE '\'"
|
|
127
|
+
)
|
|
128
|
+
case_sensitive_endswith_expression: ClassVar[str] = (
|
|
129
|
+
r"{field} LIKE '%{value}' ESCAPE '\'"
|
|
130
|
+
)
|
|
131
|
+
case_sensitive_contains_expression: ClassVar[str] = (
|
|
132
|
+
r"{field} LIKE '%{value}%' ESCAPE '\'"
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
# Numeric comparison operators
|
|
136
|
+
compare_op_expression: ClassVar[str] = "{field} {operator} {value}"
|
|
137
|
+
compare_operators: ClassVar[Dict[SigmaCompareExpression.CompareOperators, str]] = {
|
|
138
|
+
SigmaCompareExpression.CompareOperators.LT: "<",
|
|
139
|
+
SigmaCompareExpression.CompareOperators.LTE: "<=",
|
|
140
|
+
SigmaCompareExpression.CompareOperators.GT: ">",
|
|
141
|
+
SigmaCompareExpression.CompareOperators.GTE: ">=",
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
# Field-to-field comparison
|
|
145
|
+
field_equals_field_expression: ClassVar[Optional[str]] = (
|
|
146
|
+
"LOWER({field1}) = LOWER({field2})"
|
|
147
|
+
)
|
|
148
|
+
field_equals_field_escaping_quoting: Tuple[bool, bool] = (True, True)
|
|
149
|
+
|
|
150
|
+
# Null and existence checks
|
|
151
|
+
field_null_expression: ClassVar[str] = "{field} IS NULL"
|
|
152
|
+
field_exists_expression: ClassVar[str] = "{field} IS NOT NULL"
|
|
153
|
+
field_not_exists_expression: ClassVar[str] = "{field} IS NULL"
|
|
154
|
+
|
|
155
|
+
# IN expressions
|
|
156
|
+
convert_or_as_in: ClassVar[bool] = True
|
|
157
|
+
convert_and_as_in: ClassVar[bool] = False
|
|
158
|
+
in_expressions_allow_wildcards: ClassVar[bool] = False
|
|
159
|
+
field_in_list_expression: ClassVar[str] = "{field} {op} ({list})"
|
|
160
|
+
or_in_operator: ClassVar[str] = "IN"
|
|
161
|
+
list_separator: ClassVar[str] = ", "
|
|
162
|
+
|
|
163
|
+
# Unbound value expressions
|
|
164
|
+
unbound_value_str_expression: ClassVar[str] = "'{value}'"
|
|
165
|
+
unbound_value_num_expression: ClassVar[str] = "{value}"
|
|
166
|
+
unbound_value_re_expression: ClassVar[str] = "_=~{value}"
|
|
167
|
+
|
|
168
|
+
# Deferred query handling
|
|
169
|
+
deferred_start: ClassVar[str] = ""
|
|
170
|
+
deferred_separator: ClassVar[str] = ""
|
|
171
|
+
deferred_only_query: ClassVar[str] = ""
|
|
172
|
+
|
|
173
|
+
# ----------------------------------------------------------------------------------------------------------
|
|
174
|
+
|
|
175
|
+
def convert_condition_field_eq_val_str(
|
|
176
|
+
self, cond: ConditionFieldEqualsValueExpression, state: ConversionState
|
|
177
|
+
) -> Union[str, DeferredQueryExpression]:
|
|
178
|
+
# We track if the string contains special characters here as we need that info in `convert_value_str`,
|
|
179
|
+
# but don't have access to the original string at that point.
|
|
180
|
+
state.processing_state["contains_special"] = (
|
|
181
|
+
isinstance(cond.value, SigmaString) and cond.value.contains_special()
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
result = super().convert_condition_field_eq_val_str(cond, state)
|
|
185
|
+
return self.fix_wildcard_quotes(cond, result)
|
|
186
|
+
|
|
187
|
+
def convert_condition_field_eq_val_str_case_sensitive(
|
|
188
|
+
self, cond: ConditionFieldEqualsValueExpression, state: ConversionState
|
|
189
|
+
) -> Union[str, DeferredQueryExpression]:
|
|
190
|
+
# We track if the string contains special characters here as we need that info in `convert_value_str`,
|
|
191
|
+
# but don't have access to the original string at that point.
|
|
192
|
+
state.processing_state["contains_special"] = (
|
|
193
|
+
isinstance(cond.value, SigmaString) and cond.value.contains_special()
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
result = super().convert_condition_field_eq_val_str_case_sensitive(cond, state)
|
|
197
|
+
return self.fix_wildcard_quotes(cond, result)
|
|
198
|
+
|
|
199
|
+
def fix_wildcard_quotes(
|
|
200
|
+
self, cond: ConditionFieldEqualsValueExpression, value: str
|
|
201
|
+
):
|
|
202
|
+
# We need to deal with the issue that wildcarded values come pre-quoted.
|
|
203
|
+
if cond.value.startswith(SpecialChars.WILDCARD_MULTI) and cond.value.endswith(
|
|
204
|
+
SpecialChars.WILDCARD_MULTI
|
|
205
|
+
):
|
|
206
|
+
# Tidy up: '%'valueB'%'
|
|
207
|
+
return re.sub(r"'%'(.+)'%'", r"'%\1%'", value)
|
|
208
|
+
elif cond.value.startswith(SpecialChars.WILDCARD_MULTI):
|
|
209
|
+
# Tidy up: '%'valueD''
|
|
210
|
+
return value.replace("''", "'").replace("%'", "%")
|
|
211
|
+
elif cond.value.endswith(SpecialChars.WILDCARD_MULTI):
|
|
212
|
+
# Tidy up: ''valueC'%'
|
|
213
|
+
return value.replace("''", "'").replace("'%", "%")
|
|
214
|
+
|
|
215
|
+
return value
|
|
216
|
+
|
|
217
|
+
def escape_and_quote_field(self, field_name: str) -> str:
|
|
218
|
+
"""
|
|
219
|
+
Escape and quote field names, handling hierarchical fields with dots.
|
|
220
|
+
|
|
221
|
+
Args:
|
|
222
|
+
field_name: The field name to escape and quote.
|
|
223
|
+
|
|
224
|
+
Returns:
|
|
225
|
+
The escaped and quoted field name.
|
|
226
|
+
"""
|
|
227
|
+
|
|
228
|
+
# Split on unescaped dots: matches a literal dot (.) only if it is not preceded by a backslash (i.e., not escaped).
|
|
229
|
+
# We need to treat a dot (.) in a field name as an indicator of hierarchy, thus we should escape around each part.
|
|
230
|
+
# e.g actor.us@er.uid -> actor."us@er".uid
|
|
231
|
+
parts = [p.replace(r"\.", ".") for p in re.split(r"(?<!\\)\.", field_name)]
|
|
232
|
+
|
|
233
|
+
# We need to support accessing map<string,string> fields (although we'll only support them at the top level).
|
|
234
|
+
if parts[0] in self._element_at_fields:
|
|
235
|
+
return f"""element_at({parts[0]}, '{".".join(parts[1:])}')"""
|
|
236
|
+
|
|
237
|
+
escaped_and_quoted_parts: list[str] = []
|
|
238
|
+
|
|
239
|
+
for s in parts:
|
|
240
|
+
escaped_and_quoted_parts.append(super().escape_and_quote_field(s))
|
|
241
|
+
|
|
242
|
+
return ".".join(escaped_and_quoted_parts)
|
|
243
|
+
|
|
244
|
+
def convert_value_str(self, s: SigmaString, state: ConversionState) -> str:
|
|
245
|
+
"""
|
|
246
|
+
Convert a string value, applying case-insensitive conversion if needed.
|
|
247
|
+
|
|
248
|
+
Args:
|
|
249
|
+
s: The Sigma string to convert.
|
|
250
|
+
state: Current conversion state.
|
|
251
|
+
|
|
252
|
+
Returns:
|
|
253
|
+
The converted string value.
|
|
254
|
+
"""
|
|
255
|
+
# Check if the SigmaString originally contained special characters.
|
|
256
|
+
# If so we need to escape the wildcard characters
|
|
257
|
+
escape_wildcards = state.processing_state.get("contains_special", False)
|
|
258
|
+
|
|
259
|
+
"""Convert a SigmaString into a plain string which can be used in query."""
|
|
260
|
+
converted = s.convert(
|
|
261
|
+
self.escape_char,
|
|
262
|
+
self.wildcard_multi if escape_wildcards else "",
|
|
263
|
+
self.wildcard_single if escape_wildcards else "",
|
|
264
|
+
self.str_quote + self.add_escaped,
|
|
265
|
+
self.filter_chars,
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
if self.decide_string_quoting(s):
|
|
269
|
+
converted = self.quote_string(converted)
|
|
270
|
+
|
|
271
|
+
if not isinstance(s, SigmaCasedString):
|
|
272
|
+
converted = converted.casefold()
|
|
273
|
+
|
|
274
|
+
return converted
|
|
275
|
+
|
|
276
|
+
def convert_condition_as_in_expression(
|
|
277
|
+
self, cond: Union[ConditionOR, ConditionAND], state: ConversionState
|
|
278
|
+
) -> Union[str, DeferredQueryExpression]:
|
|
279
|
+
"""
|
|
280
|
+
Convert a field-in-value-list condition.
|
|
281
|
+
|
|
282
|
+
Args:
|
|
283
|
+
cond: The OR or AND condition to convert.
|
|
284
|
+
state: Current conversion state.
|
|
285
|
+
|
|
286
|
+
Returns:
|
|
287
|
+
The converted query string or deferred expression.
|
|
288
|
+
"""
|
|
289
|
+
field = self.escape_and_quote_field(cond.args[0].field)
|
|
290
|
+
if not isinstance(cond.args[0].value, SigmaCasedString):
|
|
291
|
+
field = f"LOWER({field})"
|
|
292
|
+
|
|
293
|
+
return self.field_in_list_expression.format(
|
|
294
|
+
field=field,
|
|
295
|
+
op=(
|
|
296
|
+
self.or_in_operator
|
|
297
|
+
if isinstance(cond, ConditionOR)
|
|
298
|
+
else self.and_in_operator
|
|
299
|
+
),
|
|
300
|
+
list=self.list_separator.join(
|
|
301
|
+
[
|
|
302
|
+
(
|
|
303
|
+
self.convert_value_str(arg.value, state)
|
|
304
|
+
if isinstance(arg.value, SigmaString)
|
|
305
|
+
else str(arg.value)
|
|
306
|
+
)
|
|
307
|
+
for arg in cond.args
|
|
308
|
+
]
|
|
309
|
+
),
|
|
310
|
+
)
|
|
311
|
+
|
|
312
|
+
def convert_condition_field_eq_field(
|
|
313
|
+
self, cond: ConditionFieldEqualsValueExpression, state: ConversionState
|
|
314
|
+
) -> Union[str, DeferredQueryExpression]:
|
|
315
|
+
"""Conversion of comparision of two fields."""
|
|
316
|
+
cond_value = cond.value
|
|
317
|
+
if not isinstance(cond_value, SigmaFieldReference):
|
|
318
|
+
raise TypeError(
|
|
319
|
+
"Expected SigmaFieldReference for cond.value, got {type(cond_value)}"
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
if SigmaCaseSensitiveModifier in cond.parent.modifiers:
|
|
323
|
+
raise NotImplementedError(
|
|
324
|
+
"cased is not support with fieldref for this backend at present"
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
return super().convert_condition_field_eq_field(cond, state)
|
|
328
|
+
|
|
329
|
+
def athena_finalize_query_default(
|
|
330
|
+
self, rule: SigmaRule, query: str, state: ConversionState
|
|
331
|
+
) -> Any:
|
|
332
|
+
"""
|
|
333
|
+
Finalize the query by adding SELECT and aggregation clauses.
|
|
334
|
+
|
|
335
|
+
Args:
|
|
336
|
+
rule: The Sigma rule being converted.
|
|
337
|
+
query: The query string to finalize.
|
|
338
|
+
index: Index of the query (for multi-query rules).
|
|
339
|
+
state: Current conversion state.
|
|
340
|
+
|
|
341
|
+
Returns:
|
|
342
|
+
The finalized Athena query string.
|
|
343
|
+
"""
|
|
344
|
+
|
|
345
|
+
table_name = (
|
|
346
|
+
state.processing_state.get("table_name") or self._default_table_name
|
|
347
|
+
)
|
|
348
|
+
|
|
349
|
+
# ---
|
|
350
|
+
|
|
351
|
+
select_fields = rule.fields or ["*"]
|
|
352
|
+
|
|
353
|
+
formatted_select_fields: str = ", ".join(
|
|
354
|
+
[self._format_select_field(s) for s in select_fields]
|
|
355
|
+
)
|
|
356
|
+
|
|
357
|
+
# ---
|
|
358
|
+
|
|
359
|
+
athena_query = (
|
|
360
|
+
f"SELECT {formatted_select_fields} FROM {table_name} WHERE {query}"
|
|
361
|
+
)
|
|
362
|
+
return athena_query
|
|
363
|
+
|
|
364
|
+
def finalize_query_default(
|
|
365
|
+
self, rule: SigmaRule, query: str, index: int, state: ConversionState
|
|
366
|
+
) -> Any:
|
|
367
|
+
return self.athena_finalize_query_default(rule, query, state)
|
|
368
|
+
|
|
369
|
+
# ----------------------------------------------------------------------------------------------------------
|
|
370
|
+
|
|
371
|
+
def _format_select_field(self, field: str) -> str:
|
|
372
|
+
if field == "*":
|
|
373
|
+
return field
|
|
374
|
+
|
|
375
|
+
# If it looks like a function, we leave it alone.
|
|
376
|
+
if "(" in field and ")" in field:
|
|
377
|
+
return field
|
|
378
|
+
|
|
379
|
+
match = re.search(r"\s(as)\s", field, flags=re.IGNORECASE)
|
|
380
|
+
if match:
|
|
381
|
+
start, end = match.span()
|
|
382
|
+
field_name = self.escape_and_quote_field(field[:start])
|
|
383
|
+
seperator = field[start:end]
|
|
384
|
+
field_as = self.escape_and_quote_field(field[end:])
|
|
385
|
+
return field_name + seperator + field_as
|
|
386
|
+
|
|
387
|
+
return self.escape_and_quote_field(field)
|
|
388
|
+
|
|
389
|
+
# ----------------------------------------------------------------------------------------------------------
|
|
390
|
+
|
|
391
|
+
def convert_condition_val_str(
|
|
392
|
+
self, cond: ConditionValueExpression, state: ConversionState
|
|
393
|
+
) -> Union[str, DeferredQueryExpression]:
|
|
394
|
+
raise NotImplementedError(
|
|
395
|
+
"Value-only string expressions (i.e Full Text Search or 'keywords' search) are not supported by the backend."
|
|
396
|
+
)
|
|
397
|
+
|
|
398
|
+
def convert_condition_val_num(
|
|
399
|
+
self, cond: ConditionValueExpression, state: ConversionState
|
|
400
|
+
) -> Union[str, DeferredQueryExpression]:
|
|
401
|
+
raise NotImplementedError(
|
|
402
|
+
"Value-only number expressions (i.e Full Text Search or 'keywords' search) are not supported by the backend."
|
|
403
|
+
)
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
from typing import Any, ClassVar, Dict, Optional
|
|
2
|
+
|
|
3
|
+
from sigma.conversion.state import ConversionState
|
|
4
|
+
from sigma.correlations import (
|
|
5
|
+
SigmaCorrelationRule,
|
|
6
|
+
SigmaCorrelationTypeLiteral,
|
|
7
|
+
)
|
|
8
|
+
from sigma.exceptions import SigmaConversionError
|
|
9
|
+
from sigma.processing.pipeline import ProcessingPipeline
|
|
10
|
+
from sigma.rule import SigmaRule
|
|
11
|
+
|
|
12
|
+
from .base import athenaBaseBackend
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class PartialFormatDict(dict):
|
|
16
|
+
"""A dictionary subclass that handles missing keys by returning the key name in curly braces."""
|
|
17
|
+
|
|
18
|
+
def __missing__(self, key):
|
|
19
|
+
return "{" + key + "}"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class athenaBackend(athenaBaseBackend):
|
|
23
|
+
"""
|
|
24
|
+
With Correlation support
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
processing_pipeline: Optional[ProcessingPipeline] = None,
|
|
30
|
+
collect_errors: bool = False,
|
|
31
|
+
**backend_options: Dict,
|
|
32
|
+
):
|
|
33
|
+
"""
|
|
34
|
+
Initialize the Athena backend.
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
processing_pipeline: Optional processing pipeline to apply transformations to Sigma rules.
|
|
38
|
+
collect_errors: If True, collect errors during conversion instead of raising them.
|
|
39
|
+
table: Optional, the name of the table to include in the SQL statement.
|
|
40
|
+
fields: Optional, the name of the fields to select in the SQL statement. Defaults to *.
|
|
41
|
+
**backend_options: Additional backend-specific options.
|
|
42
|
+
"""
|
|
43
|
+
super().__init__(processing_pipeline, collect_errors, **backend_options)
|
|
44
|
+
|
|
45
|
+
self._time_field: str = backend_options.get("time_field") or "time"
|
|
46
|
+
|
|
47
|
+
# The default field (column) name that contains the row's timestamp.
|
|
48
|
+
default_time_field: ClassVar[str] = "time_dt"
|
|
49
|
+
|
|
50
|
+
correlation_methods: ClassVar[Dict[str, str]] = {
|
|
51
|
+
"default": "Default method",
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
### Correlation rule templates
|
|
55
|
+
## Correlation query frame
|
|
56
|
+
# The correlation query frame is the basic structure of a correlation query for each correlation
|
|
57
|
+
# type. It contains the following placeholders:
|
|
58
|
+
# * {search} is the search expression generated by the correlation query search phase.
|
|
59
|
+
# * {typing} is the event typing expression generated by the correlation query typing phase.
|
|
60
|
+
# * {aggregate} is the aggregation expression generated by the correlation query aggregation
|
|
61
|
+
# phase.
|
|
62
|
+
# * {condition} is the condition expression generated by the correlation query condition phase.
|
|
63
|
+
# If a correlation query template for a specific correlation type is not defined, the default correlation query template is used.
|
|
64
|
+
default_correlation_query: ClassVar[Optional[Dict[str, str]]] = None
|
|
65
|
+
|
|
66
|
+
event_count_correlation_query: ClassVar[Optional[Dict[str, str]]] = {
|
|
67
|
+
"default": "WITH combined_events AS ({search}), event_counts AS ({aggregate}) {condition}"
|
|
68
|
+
# "default": "WITH event_counts AS (SELECT {selectfields}, COUNT(*) OVER ({aggregate}) as event_count FROM {table} WHERE {search} ORDER BY {timefield}) {condition}"
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
value_count_correlation_query: ClassVar[Optional[Dict[str, str]]] = None
|
|
72
|
+
|
|
73
|
+
# Trino does not support COUNT(DISTINCT {field}) with OVER, yet.
|
|
74
|
+
# value_count_correlation_query: ClassVar[Optional[Dict[str, str]]] = {
|
|
75
|
+
# "default": "WITH value_counts AS (SELECT {selectfields}, COUNT(DISTINCT {field}) OVER ({aggregate}) as value_count FROM {table} WHERE {search} ORDER BY {timefield}) {condition}"
|
|
76
|
+
# }
|
|
77
|
+
|
|
78
|
+
temporal_correlation_query: ClassVar[Optional[Dict[str, str]]] = None
|
|
79
|
+
temporal_ordered_correlation_query: ClassVar[Optional[Dict[str, str]]] = None
|
|
80
|
+
|
|
81
|
+
## Correlation query search phase
|
|
82
|
+
# The first step of a correlation query is to match events described by the referred Sigma
|
|
83
|
+
# rules. A main difference is made between single and multiple rule searches.
|
|
84
|
+
# A single rule search expression defines the search expression emitted if only one rule is
|
|
85
|
+
# referred by the correlation rule. It contains the following placeholders:
|
|
86
|
+
# * {rule} is the referred Sigma rule.
|
|
87
|
+
# * {ruleid} is the rule name or if not available the id of the rule.
|
|
88
|
+
# * {query} is the query generated from the referred Sigma rule.
|
|
89
|
+
# * {normalization} is the expression that normalizes the rule field names to unified alias
|
|
90
|
+
# field names that can be later used for aggregation. The expression is defined by
|
|
91
|
+
# correlation_search_field_normalization_expression defined below.
|
|
92
|
+
|
|
93
|
+
# correlation_search_single_rule_expression: ClassVar[str] = "{query}" # We treat one or more rules in the sames way, so we'll always use the 'multi_rule' options.
|
|
94
|
+
|
|
95
|
+
# If no single rule query expression is defined, the multi query template expressions below are
|
|
96
|
+
# used and must be suitable for this purpose.
|
|
97
|
+
|
|
98
|
+
# A multiple rule search expression defines the search expression emitted if multiple rules are
|
|
99
|
+
# referred by the correlation rule. This is split into the expression for the query itself:
|
|
100
|
+
correlation_search_multi_rule_expression: ClassVar[Optional[str]] = "{queries}"
|
|
101
|
+
# This template contains only one placeholder {queries} which contains the queries generated
|
|
102
|
+
# from single queries joined with a query separator:
|
|
103
|
+
# * A query template for each query generated from the referred Sigma rules similar to the
|
|
104
|
+
# search_single_rule_expression defined above:
|
|
105
|
+
correlation_search_multi_rule_query_expression: ClassVar[Optional[str]] = "{query}"
|
|
106
|
+
# Usually the expression must contain some an expression that marks the matched event type as
|
|
107
|
+
# such, e.g. by using the rule name or uuid.
|
|
108
|
+
# * A joiner string that is put between each search_multi_rule_query_expression:
|
|
109
|
+
correlation_search_multi_rule_query_expression_joiner: ClassVar[Optional[str]] = (
|
|
110
|
+
" UNION ALL "
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
## Correlation query aggregation phase
|
|
114
|
+
# All of the following class variables are dictionaries of mappings from
|
|
115
|
+
# correlation_method names to format strings with the following placeholders:
|
|
116
|
+
# * {rule} contains the whole correlation rule object.
|
|
117
|
+
# * {referenced_rules} contains the Sigma rules that are referred by the correlation rule.
|
|
118
|
+
# * {field} contains the field specified in the condition.
|
|
119
|
+
# * {timespan} contains the timespan converted into the target format by the convert_timespan
|
|
120
|
+
# method.
|
|
121
|
+
# * {groupby} contains the group by expression generated by the groupby_* templates below.
|
|
122
|
+
# * {search} contains the search expression generated by the correlation query search phase.
|
|
123
|
+
event_count_aggregation_expression: ClassVar[Optional[Dict[str, str]]] = {
|
|
124
|
+
# "default": "WITH event_counts AS (SELECT {selectfields}, COUNT(*) OVER ({over}) as event_count FROM {table} WHERE {search} ORDER BY {timefield})"
|
|
125
|
+
# "default": "PARTITION BY {groupby} ORDER BY {timefield} RANGE BETWEEN INTERVAL '{timespan}' SECOND PRECEDING AND CURRENT ROW"
|
|
126
|
+
"default": "SELECT *, COUNT(*) OVER (PARTITION BY {groupby} ORDER BY {timefield} RANGE BETWEEN INTERVAL '{timespan}' SECOND PRECEDING AND CURRENT ROW) as correlation_event_count FROM combined_events"
|
|
127
|
+
}
|
|
128
|
+
value_count_aggregation_expression: ClassVar[Optional[Dict[str, str]]] = {
|
|
129
|
+
None # Expression for temporal correlation rules
|
|
130
|
+
}
|
|
131
|
+
temporal_aggregation_expression: ClassVar[Optional[Dict[str, str]]] = (
|
|
132
|
+
None # Expression for temporal correlation rules
|
|
133
|
+
)
|
|
134
|
+
temporal_ordered_aggregation_expression: ClassVar[Optional[Dict[str, str]]] = (
|
|
135
|
+
None # Expression for ordered temporal correlation rules
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
# We'll just convert it to seconds; seems easier.
|
|
139
|
+
timespan_seconds: ClassVar[bool] = (
|
|
140
|
+
True # If True, timespan is converted to seconds instead of using a more readable timespan specification like 5m.
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
# The following class variables defined the templates for the group by expression.
|
|
144
|
+
groupby_expression: ClassVar[Dict[str, str]] = {"default": "{fields}"}
|
|
145
|
+
groupby_field_expression: ClassVar[Dict[str, str]] = {"default": "{field}"}
|
|
146
|
+
groupby_field_expression_joiner: ClassVar[Dict[str, str]] = {"default": ", "}
|
|
147
|
+
|
|
148
|
+
## Correlation query condition phase
|
|
149
|
+
# The final correlation query phase adds a final filter that filters the aggregated events
|
|
150
|
+
# according to the given conditions. The following class variables define the templates for the
|
|
151
|
+
# different correlation rule types and correlation methods (dict keys).
|
|
152
|
+
# Each template gets the following placeholders:
|
|
153
|
+
# * {op} is the condition operator mapped according o correlation_condition_mapping.
|
|
154
|
+
# * {count} is the value specified in the condition.
|
|
155
|
+
# * {field} is the field specified in the condition.
|
|
156
|
+
# * {referenced_rules} contains the Sigma rules that are referred by the correlation rule. This
|
|
157
|
+
# expression is generated by the referenced_rules_expression template in combination with the
|
|
158
|
+
# referenced_rules_expression_joiner defined above.
|
|
159
|
+
event_count_condition_expression: ClassVar[Optional[Dict[str, str]]] = {
|
|
160
|
+
"default": "SELECT * FROM event_counts WHERE correlation_event_count {op} {count}",
|
|
161
|
+
}
|
|
162
|
+
value_count_condition_expression: ClassVar[Optional[Dict[str, str]]] = {
|
|
163
|
+
"default": "SELECT * FROM value_counts WHERE value_count {op} {count}",
|
|
164
|
+
}
|
|
165
|
+
temporal_condition_expression: ClassVar[Optional[Dict[str, str]]] = None
|
|
166
|
+
temporal_ordered_condition_expression: ClassVar[Optional[Dict[str, str]]] = None
|
|
167
|
+
|
|
168
|
+
# Correlation query conversion
|
|
169
|
+
# The following methods are used to convert Sigma correlation rules into queries. The conversion
|
|
170
|
+
# starts with the convert_correlation_rule method that calls correlation type specific methods
|
|
171
|
+
# which itself call convert_correlation_rule_from_template that dispatches to the three
|
|
172
|
+
# correlation query phases: search, aggregation and condition.
|
|
173
|
+
def convert_correlation_rule_from_template(
|
|
174
|
+
self,
|
|
175
|
+
rule: SigmaCorrelationRule,
|
|
176
|
+
correlation_type: SigmaCorrelationTypeLiteral,
|
|
177
|
+
method: str,
|
|
178
|
+
) -> list[str]:
|
|
179
|
+
template = (
|
|
180
|
+
getattr(self, f"{correlation_type}_correlation_query")
|
|
181
|
+
or self.default_correlation_query
|
|
182
|
+
)
|
|
183
|
+
if template is None:
|
|
184
|
+
raise NotImplementedError(
|
|
185
|
+
f"Correlation rule type '{correlation_type}' is not supported by backend."
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
if method not in template:
|
|
189
|
+
raise SigmaConversionError(
|
|
190
|
+
f"Correlation method '{method}' is not supported by backend for correlation type '{correlation_type}'."
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
search = self.convert_correlation_search(rule)
|
|
194
|
+
aggregate = self.convert_correlation_aggregation_from_template(
|
|
195
|
+
rule, correlation_type, method, search
|
|
196
|
+
)
|
|
197
|
+
condition = self.convert_correlation_condition_from_template(
|
|
198
|
+
rule.condition, rule.rules, correlation_type, method
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
query = template[method].format_map(
|
|
202
|
+
PartialFormatDict(
|
|
203
|
+
timefield=self._time_field,
|
|
204
|
+
search=search,
|
|
205
|
+
aggregate=aggregate,
|
|
206
|
+
condition=condition,
|
|
207
|
+
)
|
|
208
|
+
)
|
|
209
|
+
# WITH combined_events AS ({search}), event_counts AS ({aggregate}) {condition}
|
|
210
|
+
|
|
211
|
+
return [query]
|
|
212
|
+
|
|
213
|
+
def convert_correlation_search(
|
|
214
|
+
self,
|
|
215
|
+
rule: SigmaCorrelationRule,
|
|
216
|
+
**kwargs,
|
|
217
|
+
) -> str:
|
|
218
|
+
return self.correlation_search_multi_rule_expression.format(
|
|
219
|
+
queries=self.correlation_search_multi_rule_query_expression_joiner.join(
|
|
220
|
+
(
|
|
221
|
+
self.correlation_search_multi_rule_query_expression.format(
|
|
222
|
+
query=self.athena_finalize_query_default(
|
|
223
|
+
rule_reference.rule,
|
|
224
|
+
query,
|
|
225
|
+
rule_reference.rule.get_conversion_states()[0],
|
|
226
|
+
)
|
|
227
|
+
)
|
|
228
|
+
for rule_reference in rule.rules
|
|
229
|
+
for query in rule_reference.rule.get_conversion_result()
|
|
230
|
+
)
|
|
231
|
+
),
|
|
232
|
+
**kwargs,
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
# Implementation of the aggregation phase of the correlation query.
|
|
236
|
+
def convert_correlation_aggregation_from_template(
|
|
237
|
+
self,
|
|
238
|
+
rule: SigmaCorrelationRule,
|
|
239
|
+
correlation_type: SigmaCorrelationTypeLiteral,
|
|
240
|
+
method: str,
|
|
241
|
+
search: str,
|
|
242
|
+
) -> str:
|
|
243
|
+
templates = getattr(self, f"{correlation_type}_aggregation_expression")
|
|
244
|
+
if templates is None:
|
|
245
|
+
raise NotImplementedError(
|
|
246
|
+
f"Correlation type '{correlation_type}' is not supported by backend."
|
|
247
|
+
)
|
|
248
|
+
template = templates[method]
|
|
249
|
+
|
|
250
|
+
aggregation = template.format(
|
|
251
|
+
timefield=self._time_field,
|
|
252
|
+
groupby=self.convert_correlation_aggregation_groupby_from_template(
|
|
253
|
+
rule.group_by, method
|
|
254
|
+
),
|
|
255
|
+
timespan=self.convert_timespan(rule.timespan, method),
|
|
256
|
+
)
|
|
257
|
+
# "PARTITION BY {groupby} ORDER BY {timefield} RANGE BETWEEN INTERVAL '{timespan}' SECOND PRECEDING AND CURRENT ROW"
|
|
258
|
+
|
|
259
|
+
return aggregation
|
|
260
|
+
|
|
261
|
+
def finalize_query_default(
|
|
262
|
+
self, rule: SigmaRule, query: str, index: int, state: ConversionState
|
|
263
|
+
) -> Any:
|
|
264
|
+
if not isinstance(rule, SigmaCorrelationRule):
|
|
265
|
+
return super().finalize_query_default(rule, query, index, state)
|
|
266
|
+
|
|
267
|
+
return query
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
from dataclasses import dataclass, field
|
|
2
|
+
from typing import Dict
|
|
3
|
+
|
|
4
|
+
from sigma.pipelines.base import Pipeline
|
|
5
|
+
from sigma.processing.conditions import LogsourceCondition
|
|
6
|
+
from sigma.processing.pipeline import (
|
|
7
|
+
PreprocessingTransformation,
|
|
8
|
+
ProcessingItem,
|
|
9
|
+
ProcessingPipeline,
|
|
10
|
+
SigmaRule,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class SetStateFromBackendOptionsTransformation(PreprocessingTransformation):
|
|
16
|
+
key: str
|
|
17
|
+
template: str
|
|
18
|
+
default_values: Dict[str, str] = field(default_factory=dict)
|
|
19
|
+
|
|
20
|
+
def apply(self, rule: SigmaRule) -> None:
|
|
21
|
+
# Call base (no pipeline arg)
|
|
22
|
+
super().apply(rule)
|
|
23
|
+
|
|
24
|
+
# Use the pipeline injected by PySigma
|
|
25
|
+
pipeline = self._pipeline
|
|
26
|
+
|
|
27
|
+
# Merge defaults with backend options/vars
|
|
28
|
+
values = {**self.default_values, **pipeline.vars}
|
|
29
|
+
try:
|
|
30
|
+
pipeline.state[self.key] = self.template.format_map(values)
|
|
31
|
+
except KeyError as e:
|
|
32
|
+
missing_key = e.args[0]
|
|
33
|
+
raise KeyError(
|
|
34
|
+
f"Missing key '{missing_key}' in template substitution for '{self.key}'. "
|
|
35
|
+
f"Available keys: {list(values.keys())}. "
|
|
36
|
+
f"You likely need to set the key '{missing_key}' via 'backend options'."
|
|
37
|
+
) from e
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class SetStateFromBackendOptionsTransformationDashToUnderscore(
|
|
42
|
+
SetStateFromBackendOptionsTransformation
|
|
43
|
+
):
|
|
44
|
+
def apply(self, rule: SigmaRule) -> None:
|
|
45
|
+
# First, compute the value via the parent
|
|
46
|
+
super().apply(rule)
|
|
47
|
+
|
|
48
|
+
# Then normalise dashes to underscores
|
|
49
|
+
pipeline = self._pipeline
|
|
50
|
+
pipeline.state[self.key] = pipeline.state[self.key].replace("-", "_")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@Pipeline
|
|
54
|
+
def athena_pipeline_security_lake_table_name() -> ProcessingPipeline:
|
|
55
|
+
sources = [
|
|
56
|
+
(
|
|
57
|
+
LogsourceCondition(product="aws", service="cloudtrail"),
|
|
58
|
+
"amazon_security_lake_table_{backend_aws_table_region}_cloud_trail_mgmt_{backend_aws_table_version}",
|
|
59
|
+
),
|
|
60
|
+
(
|
|
61
|
+
LogsourceCondition(product="aws", service="cloudtrail_s3"),
|
|
62
|
+
"amazon_security_lake_table_{backend_aws_table_region}_s3_data_{backend_aws_table_version}",
|
|
63
|
+
),
|
|
64
|
+
(
|
|
65
|
+
LogsourceCondition(product="aws", service="cloudtrail_lambda"),
|
|
66
|
+
"amazon_security_lake_table_{backend_aws_table_region}_lambda_execution_{backend_aws_table_version}",
|
|
67
|
+
),
|
|
68
|
+
(
|
|
69
|
+
LogsourceCondition(product="aws", service="route53"),
|
|
70
|
+
"amazon_security_lake_table_{backend_aws_table_region}_route53_{backend_aws_table_version}",
|
|
71
|
+
),
|
|
72
|
+
(
|
|
73
|
+
LogsourceCondition(product="aws", service="security_hub"),
|
|
74
|
+
"amazon_security_lake_table_{backend_aws_table_region}_sh_findings_{backend_aws_table_version}",
|
|
75
|
+
),
|
|
76
|
+
(
|
|
77
|
+
LogsourceCondition(product="aws", service="vpc_flow_logs"),
|
|
78
|
+
"amazon_security_lake_table_{backend_aws_table_region}_vpc_flow_{backend_aws_table_version}",
|
|
79
|
+
),
|
|
80
|
+
(
|
|
81
|
+
LogsourceCondition(product="aws", service="waf"),
|
|
82
|
+
"amazon_security_lake_table_{backend_aws_table_region}_waf_{backend_aws_table_version}",
|
|
83
|
+
),
|
|
84
|
+
(
|
|
85
|
+
LogsourceCondition(product="aws", service="eks_audit"),
|
|
86
|
+
"amazon_security_lake_table_{backend_aws_table_region}_eks_audit_{backend_aws_table_version}",
|
|
87
|
+
),
|
|
88
|
+
]
|
|
89
|
+
|
|
90
|
+
return ProcessingPipeline(
|
|
91
|
+
name="athena map source to table name pipeline",
|
|
92
|
+
allowed_backends=frozenset(["athena"]),
|
|
93
|
+
priority=20,
|
|
94
|
+
items=[
|
|
95
|
+
ProcessingItem(
|
|
96
|
+
identifier=f"table_{name}",
|
|
97
|
+
transformation=SetStateFromBackendOptionsTransformationDashToUnderscore(
|
|
98
|
+
key="table_name",
|
|
99
|
+
template=name,
|
|
100
|
+
default_values={"backend_aws_table_version": "2_0"},
|
|
101
|
+
),
|
|
102
|
+
rule_conditions=[condition],
|
|
103
|
+
)
|
|
104
|
+
for condition, name in sources
|
|
105
|
+
],
|
|
106
|
+
)
|