pySigma-backend-sqlite 2.1.0__tar.gz → 2.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pysigma_backend_sqlite-2.2.0/PKG-INFO +233 -0
- pysigma_backend_sqlite-2.2.0/README.md +214 -0
- {pysigma_backend_sqlite-2.1.0 → pysigma_backend_sqlite-2.2.0}/pyproject.toml +11 -8
- pysigma_backend_sqlite-2.2.0/sigma/backends/sqlite/cidr.py +52 -0
- pysigma_backend_sqlite-2.2.0/sigma/backends/sqlite/correlation.py +991 -0
- pysigma_backend_sqlite-2.2.0/sigma/backends/sqlite/modifiers.py +132 -0
- pysigma_backend_sqlite-2.2.0/sigma/backends/sqlite/runtime.py +311 -0
- pysigma_backend_sqlite-2.2.0/sigma/backends/sqlite/sqlite.py +1218 -0
- pysigma_backend_sqlite-2.2.0/sigma/backends/sqlite/strict.py +221 -0
- pysigma_backend_sqlite-2.1.0/PKG-INFO +0 -176
- pysigma_backend_sqlite-2.1.0/README.md +0 -157
- pysigma_backend_sqlite-2.1.0/sigma/backends/sqlite/correlation.py +0 -634
- pysigma_backend_sqlite-2.1.0/sigma/backends/sqlite/runtime.py +0 -176
- pysigma_backend_sqlite-2.1.0/sigma/backends/sqlite/sqlite.py +0 -1008
- {pysigma_backend_sqlite-2.1.0 → pysigma_backend_sqlite-2.2.0}/LICENSE +0 -0
- {pysigma_backend_sqlite-2.1.0 → pysigma_backend_sqlite-2.2.0}/sigma/backends/sqlite/__init__.py +0 -0
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pySigma-backend-sqlite
|
|
3
|
+
Version: 2.2.0
|
|
4
|
+
Summary: pySigma sqlite backend
|
|
5
|
+
License-Expression: LGPL-3.0-only
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Author: wagga
|
|
8
|
+
Requires-Python: >=3.11,<4.0
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
15
|
+
Requires-Dist: pysigma (>=2.1.0,<3.0)
|
|
16
|
+
Project-URL: Repository, https://github.com/SigmaHQ/pySigma-backend-sqlite
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+

|
|
20
|
+

|
|
21
|
+
|
|
22
|
+
# pySigma SQLite Backend
|
|
23
|
+
|
|
24
|
+
Converts [Sigma](https://github.com/SigmaHQ/sigma) rules into SQLite queries. The
|
|
25
|
+
package `sigma.backends.sqlite` provides `sqliteBackend`, registered as the
|
|
26
|
+
sigma-cli target `sqlite`. It is the converter behind
|
|
27
|
+
[Zircolite](https://github.com/wagga40/Zircolite), and its output runs on any
|
|
28
|
+
SQLite table of flattened events.
|
|
29
|
+
|
|
30
|
+
Maintained by [wagga](https://github.com/wagga40/).
|
|
31
|
+
|
|
32
|
+
## Install
|
|
33
|
+
|
|
34
|
+
```shell
|
|
35
|
+
pip install pysigma-backend-sqlite
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Requires Python 3.11+ and [pySigma](https://github.com/SigmaHQ/pySigma) 2.1.0 or
|
|
39
|
+
newer within the 2.x series. Correlation output needs SQLite 3.38 or newer. Use sigma-cli 4.0 or newer:
|
|
40
|
+
sigma-cli 3.x requires pySigma 1.x, so alongside it pip installs backend 2.0.0,
|
|
41
|
+
which has no keyword search.
|
|
42
|
+
|
|
43
|
+
## Quick start
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from sigma.collection import SigmaCollection
|
|
47
|
+
from sigma.backends.sqlite import sqliteBackend
|
|
48
|
+
|
|
49
|
+
rules = SigmaCollection.from_yaml(r"""
|
|
50
|
+
title: Whoami execution
|
|
51
|
+
status: test
|
|
52
|
+
logsource:
|
|
53
|
+
category: process_creation
|
|
54
|
+
product: windows
|
|
55
|
+
detection:
|
|
56
|
+
selection:
|
|
57
|
+
Image|endswith: '\whoami.exe'
|
|
58
|
+
condition: selection
|
|
59
|
+
""")
|
|
60
|
+
|
|
61
|
+
print(sqliteBackend().convert(rules)[0])
|
|
62
|
+
# SELECT * FROM logs WHERE Image LIKE '%\\whoami.exe' ESCAPE '\'
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Processing pipelines map a logsource to concrete fields. With
|
|
66
|
+
`sqliteBackend(sysmon_pipeline() + windows_logsource_pipeline())` the same rule becomes:
|
|
67
|
+
|
|
68
|
+
```sql
|
|
69
|
+
SELECT * FROM logs WHERE Channel='Microsoft-Windows-Sysmon/Operational' AND (EventID=1 AND Image LIKE '%\\whoami.exe' ESCAPE '\')
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Install the pipelines with `pip install pysigma-pipeline-sysmon pysigma-pipeline-windows`;
|
|
73
|
+
releases 3.0 and newer support pySigma 2. With sigma-cli:
|
|
74
|
+
|
|
75
|
+
```shell
|
|
76
|
+
sigma convert -t sqlite -f zircolite -p sysmon -p windows-logsources rules/
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Output formats
|
|
80
|
+
|
|
81
|
+
| Format | Output |
|
|
82
|
+
|---|---|
|
|
83
|
+
| `default` | One standalone SQL statement per detection condition or correlation |
|
|
84
|
+
| `zircolite` | A JSON list with one entry per converted condition or correlation, including metadata and execution requirements. See [output format](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/output-format.md) |
|
|
85
|
+
|
|
86
|
+
## Options
|
|
87
|
+
|
|
88
|
+
Set options when constructing the backend or with `-O name=value` in sigma-cli.
|
|
89
|
+
Changing attributes after construction is unsupported.
|
|
90
|
+
Table and column names must be nonempty. pySigma also forwards options to the
|
|
91
|
+
processing pipeline as `backend_<name>`. A name resembling a misspelled SQLite
|
|
92
|
+
option produces a warning so you can check which setting took effect.
|
|
93
|
+
|
|
94
|
+
| Option | Default | Purpose |
|
|
95
|
+
|---|---|---|
|
|
96
|
+
| `table` | `logs` | Table to query. A pipeline `setState` on `table` takes precedence |
|
|
97
|
+
| `collate_nocase` | `false` | Emit `field='value' COLLATE NOCASE` for tables without `NOCASE` columns |
|
|
98
|
+
| `prefilter_bounds` | `true` | Emit Channel/EventID allow-lists for Zircolite storage. Set to `false` for custom collations or event ID coercions |
|
|
99
|
+
| `text_mode` | `portable` | Use `unicode` for Unicode case folding in detections, grouping and distinct counts |
|
|
100
|
+
| `presence_field` | none | JSON array column listing the flattened fields present in each source event |
|
|
101
|
+
| `sum_mode` | `portable` | Use `exact` to preserve integer window totals beyond SQLite's signed 64-bit range |
|
|
102
|
+
| `week_mode` | `iso` | ISO week of year (1–53). Use `legacy` for SQLite's Monday-based week 0–53 |
|
|
103
|
+
| `modifier_mode` | `sigma` | `windash` expands every dash position and `re\|startswith`/`re\|endswith` stay within the field. Use `pysigma` for pySigma's own expansion, as in 2.1 |
|
|
104
|
+
| `max_flat_operands` | `100` | Longer AND/OR chains are nested to stay under SQLite's expression depth limit |
|
|
105
|
+
| `cidr_mode` | `expanded` | Use portable prefix matching or opt into exact network membership with `exact` |
|
|
106
|
+
| `fulltext_field` | none | Column of searchable event text; enables [keyword search](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/keyword-search.md) |
|
|
107
|
+
| `timestamp_field` | `timestamp` | Event time column used by correlations |
|
|
108
|
+
| `timestamp_format` | `iso` | `iso`, `unix`, `unix_ms` or `unix_us` |
|
|
109
|
+
| `timestamp_seconds_expression` | ISO parser | SQL turning `{field}` into Unix seconds; overrides `timestamp_format` |
|
|
110
|
+
| `event_id_field` | `rowid` | Non-NULL, per-table unique event identifier for correlation evidence |
|
|
111
|
+
| `observation_end` | latest event | Unix seconds up to which absence windows can expire |
|
|
112
|
+
|
|
113
|
+
The optional Unicode, presence and exact-sum contracts require a consumer that
|
|
114
|
+
understands schema 5. The table below describes the portable settings.
|
|
115
|
+
[Sigma 2.1 feature support and parser compatibility](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/sigma-conformance.md)
|
|
116
|
+
|
|
117
|
+
## Generated SQL
|
|
118
|
+
|
|
119
|
+
| Modifier | SQL |
|
|
120
|
+
|---|---|
|
|
121
|
+
| `contains`, `startswith`, `endswith` | `LIKE '%value%' ESCAPE '\'` and its prefix/suffix forms |
|
|
122
|
+
| `all` | `AND` of the values |
|
|
123
|
+
| `re` | `REGEXP` (needs a registered function, see [Limitations](#limitations)) |
|
|
124
|
+
| `cidr` | Expanded mode uses `=` or `LIKE`. Exact mode uses equality for IPv4 `/32` and a registered membership function for other networks |
|
|
125
|
+
| `cased` | `GLOB`; literal `*`, `?`, `[` become `[*]`, `[?]`, `[[]` |
|
|
126
|
+
| `fieldref` | `field1=field2`, or `LIKE` with the second field's `%` and `_` escaped |
|
|
127
|
+
| `exists` | `IS NOT NULL` / `IS NULL` |
|
|
128
|
+
| `gt`, `gte`, `lt`, `lte` | Compare finite numbers and numeric text numerically |
|
|
129
|
+
| `neq` | Negated equality |
|
|
130
|
+
| `minute`, `hour`, `day`, `week`, `month`, `year` | Calendar part of an ISO-8601 timestamp |
|
|
131
|
+
| `base64`, `base64offset`, `wide`, `utf16be`, `utf16`, `windash` | Expanded into text predicates. Follow byte encodings with a Base64 modifier |
|
|
132
|
+
|
|
133
|
+
Generated SQL handles the following cases.
|
|
134
|
+
|
|
135
|
+
- **Negation.** Sigma reads a condition on a missing field as false; SQLite reads
|
|
136
|
+
it as `NULL`, and `NOT NULL` drops the row. Every `NOT` therefore wraps its
|
|
137
|
+
operand: `EventID=1 AND (NOT COALESCE((CommandLine LIKE '%foo%' ESCAPE '\'), 0))`.
|
|
138
|
+
- **Case.** `LIKE` ignores case; `=` does only on `NOCASE` columns (Zircolite's
|
|
139
|
+
layout), otherwise set `collate_nocase`.
|
|
140
|
+
- **Booleans.** `Flag: true` matches text or integer storage: `(Flag='true' OR Flag=1)`.
|
|
141
|
+
- **Field names.** SQLite keywords and names with characters other than letters,
|
|
142
|
+
digits and `_` are quoted with backticks. `field: null` becomes `field IS NULL`.
|
|
143
|
+
- **Numeric comparisons.** `gt`, `gte`, `lt` and `lte` validate and convert the
|
|
144
|
+
stored value before comparison. A plain index on that column cannot supply a
|
|
145
|
+
range lookup for this predicate, even on an `INTEGER` column. Detections read
|
|
146
|
+
`+11`, `11.` and `011` as eleven. Numeric correlation statistics accept text
|
|
147
|
+
in JSON number syntax and skip all three spellings.
|
|
148
|
+
|
|
149
|
+
## Correlations
|
|
150
|
+
|
|
151
|
+
All Sigma correlation types run in SQLite, including chains, aliases and extended
|
|
152
|
+
temporal conditions. See [correlations](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/correlations.md)
|
|
153
|
+
for their semantics and the [migration guide](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/migration-v2.md)
|
|
154
|
+
for upgrading from backend 1.x.
|
|
155
|
+
|
|
156
|
+
## CIDR matching
|
|
157
|
+
|
|
158
|
+
The default `cidr_mode="expanded"` uses portable SQL. It checks the spelling of
|
|
159
|
+
an address and can use SQLite prefix indexes. Exact mode parses the event value
|
|
160
|
+
and tests membership in the network. For example, SQL generated for these inputs
|
|
161
|
+
has the following behavior.
|
|
162
|
+
|
|
163
|
+
| CIDR | Event value | Expanded | Exact |
|
|
164
|
+
|---|---|---|---|
|
|
165
|
+
| `10.0.0.0/8` | `10.1.2.300` | match | no match |
|
|
166
|
+
| `10.0.0.0/8` | `10.1.2.3` followed by a space | match | no match |
|
|
167
|
+
| `2001:db8::/32` | `2001:0db8:0:0::1` | no match | match |
|
|
168
|
+
| `10.0.0.0/8` | `::ffff:10.0.0.5` (IPv4-mapped IPv6) | no match | no match |
|
|
169
|
+
| `0.0.0.0/0` | `::ffff:10.0.0.5` | match | no match |
|
|
170
|
+
| `::/0` | `10.0.0.5` | match | no match |
|
|
171
|
+
| Either `/0` | `unknown` | match | no match |
|
|
172
|
+
|
|
173
|
+
Both expanded `/0` networks compile to `LIKE '%'` and match every non-NULL
|
|
174
|
+
text value. Exact mode parses the address and respects its IP family.
|
|
175
|
+
|
|
176
|
+
```python
|
|
177
|
+
from sigma.backends.sqlite.runtime import register_cidr
|
|
178
|
+
|
|
179
|
+
register_cidr(connection)
|
|
180
|
+
query = sqliteBackend(cidr_mode="exact").convert(rules)[0]
|
|
181
|
+
rows = connection.execute(query).fetchall()
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
For sigma-cli, pass `-O cidr_mode=exact` and register the function on the connection
|
|
185
|
+
that executes the SQL. IPv4 ranges with at least one fixed octet can use a prefix
|
|
186
|
+
or equality index. When an IPv6 network fixes a nonzero first group of 16 bits,
|
|
187
|
+
SQLite checks that group before parsing the address, allowing any valid letter
|
|
188
|
+
case or leading zeros. This check can use a compatible index. Other IPv6
|
|
189
|
+
networks skip values without a colon before parsing.
|
|
190
|
+
Exact IPv4 `/32` uses a built-in SQLite comparison. Zircolite 4.7.1 can run
|
|
191
|
+
these entries without registering a function. Entries that use the CIDR
|
|
192
|
+
function require a schema-4 consumer. [Original CIDR report](https://github.com/SigmaHQ/pySigma-backend-sqlite/issues/17)
|
|
193
|
+
|
|
194
|
+
## Keyword search
|
|
195
|
+
|
|
196
|
+
Keyword (fieldless) rules need `fulltext_field`, a column holding each event's
|
|
197
|
+
searchable text. See [keyword search](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/keyword-search.md).
|
|
198
|
+
|
|
199
|
+
## Limitations
|
|
200
|
+
|
|
201
|
+
- **REGEXP.** SQLite has no built-in `REGEXP`. Register one that is false for `NULL`:
|
|
202
|
+
`connection.create_function("regexp", 2, lambda p, v: v is not None and re.search(p, str(v)) is not None)`.
|
|
203
|
+
pySigma validates `|re` with RE2 by default, rejecting lookarounds and
|
|
204
|
+
backreferences. For trusted rules, pass `policy=TrustedPolicy` (from
|
|
205
|
+
`sigma.policy.profiles`) to `SigmaCollection.from_yaml()`; the patterns must then
|
|
206
|
+
suit Python's `re`.
|
|
207
|
+
- **Case folding.** Stock BINARY columns compare literal text case-sensitively. SQLite NOCASE columns or `collate_nocase=True` cover ASCII. Set `text_mode="unicode"` and register the runtime helpers for Unicode equality, wildcards, field comparisons and keywords.
|
|
208
|
+
- **Timestamp parts** use `strftime()` and need ISO-8601 text; a numeric epoch is
|
|
209
|
+
read as a Julian day. ISO week 53 occurs in some years. Only `week_mode="legacy"` can produce week 0.
|
|
210
|
+
- **Field existence.** With `presence_field`, `exists` includes an explicitly null field. The default uses SQL NULL as a proxy for absence.
|
|
211
|
+
- **Multi-field `value_count`** counts distinct complete tuples in each window. A NULL component excludes that tuple from the count.
|
|
212
|
+
- **Unknown columns.** A query naming a column the table lacks fails to prepare.
|
|
213
|
+
Add missing columns as `NULL` first; see [output format](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/output-format.md).
|
|
214
|
+
|
|
215
|
+
## Development
|
|
216
|
+
|
|
217
|
+
```shell
|
|
218
|
+
poetry install
|
|
219
|
+
poetry run pytest
|
|
220
|
+
SQLITE_MIN_BINARY=/path/to/sqlite-3.38 poetry run pytest tests/test_sqlite_minimum.py
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
`tools/audit_corpus.py` converts and prepares a SigmaHQ checkout per profile (see
|
|
224
|
+
[coverage](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/keyword-search.md#coverage)).
|
|
225
|
+
`tools/benchmark_correlations.py` times sparse and dense correlation windows.
|
|
226
|
+
`tools/benchmark_cidr.py` compares expanded and exact event queries and
|
|
227
|
+
materialized correlations over indexed and unindexed IPv4 and IPv6 data.
|
|
228
|
+
It checks event and evidence identities and records SQLite query plans.
|
|
229
|
+
|
|
230
|
+
```shell
|
|
231
|
+
poetry run python tools/benchmark_cidr.py --size 100000 --iterations 5 --output cidr.json
|
|
232
|
+
```
|
|
233
|
+
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+

|
|
2
|
+

|
|
3
|
+
|
|
4
|
+
# pySigma SQLite Backend
|
|
5
|
+
|
|
6
|
+
Converts [Sigma](https://github.com/SigmaHQ/sigma) rules into SQLite queries. The
|
|
7
|
+
package `sigma.backends.sqlite` provides `sqliteBackend`, registered as the
|
|
8
|
+
sigma-cli target `sqlite`. It is the converter behind
|
|
9
|
+
[Zircolite](https://github.com/wagga40/Zircolite), and its output runs on any
|
|
10
|
+
SQLite table of flattened events.
|
|
11
|
+
|
|
12
|
+
Maintained by [wagga](https://github.com/wagga40/).
|
|
13
|
+
|
|
14
|
+
## Install
|
|
15
|
+
|
|
16
|
+
```shell
|
|
17
|
+
pip install pysigma-backend-sqlite
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Requires Python 3.11+ and [pySigma](https://github.com/SigmaHQ/pySigma) 2.1.0 or
|
|
21
|
+
newer within the 2.x series. Correlation output needs SQLite 3.38 or newer. Use sigma-cli 4.0 or newer:
|
|
22
|
+
sigma-cli 3.x requires pySigma 1.x, so alongside it pip installs backend 2.0.0,
|
|
23
|
+
which has no keyword search.
|
|
24
|
+
|
|
25
|
+
## Quick start
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
from sigma.collection import SigmaCollection
|
|
29
|
+
from sigma.backends.sqlite import sqliteBackend
|
|
30
|
+
|
|
31
|
+
rules = SigmaCollection.from_yaml(r"""
|
|
32
|
+
title: Whoami execution
|
|
33
|
+
status: test
|
|
34
|
+
logsource:
|
|
35
|
+
category: process_creation
|
|
36
|
+
product: windows
|
|
37
|
+
detection:
|
|
38
|
+
selection:
|
|
39
|
+
Image|endswith: '\whoami.exe'
|
|
40
|
+
condition: selection
|
|
41
|
+
""")
|
|
42
|
+
|
|
43
|
+
print(sqliteBackend().convert(rules)[0])
|
|
44
|
+
# SELECT * FROM logs WHERE Image LIKE '%\\whoami.exe' ESCAPE '\'
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Processing pipelines map a logsource to concrete fields. With
|
|
48
|
+
`sqliteBackend(sysmon_pipeline() + windows_logsource_pipeline())` the same rule becomes:
|
|
49
|
+
|
|
50
|
+
```sql
|
|
51
|
+
SELECT * FROM logs WHERE Channel='Microsoft-Windows-Sysmon/Operational' AND (EventID=1 AND Image LIKE '%\\whoami.exe' ESCAPE '\')
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Install the pipelines with `pip install pysigma-pipeline-sysmon pysigma-pipeline-windows`;
|
|
55
|
+
releases 3.0 and newer support pySigma 2. With sigma-cli:
|
|
56
|
+
|
|
57
|
+
```shell
|
|
58
|
+
sigma convert -t sqlite -f zircolite -p sysmon -p windows-logsources rules/
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Output formats
|
|
62
|
+
|
|
63
|
+
| Format | Output |
|
|
64
|
+
|---|---|
|
|
65
|
+
| `default` | One standalone SQL statement per detection condition or correlation |
|
|
66
|
+
| `zircolite` | A JSON list with one entry per converted condition or correlation, including metadata and execution requirements. See [output format](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/output-format.md) |
|
|
67
|
+
|
|
68
|
+
## Options
|
|
69
|
+
|
|
70
|
+
Set options when constructing the backend or with `-O name=value` in sigma-cli.
|
|
71
|
+
Changing attributes after construction is unsupported.
|
|
72
|
+
Table and column names must be nonempty. pySigma also forwards options to the
|
|
73
|
+
processing pipeline as `backend_<name>`. A name resembling a misspelled SQLite
|
|
74
|
+
option produces a warning so you can check which setting took effect.
|
|
75
|
+
|
|
76
|
+
| Option | Default | Purpose |
|
|
77
|
+
|---|---|---|
|
|
78
|
+
| `table` | `logs` | Table to query. A pipeline `setState` on `table` takes precedence |
|
|
79
|
+
| `collate_nocase` | `false` | Emit `field='value' COLLATE NOCASE` for tables without `NOCASE` columns |
|
|
80
|
+
| `prefilter_bounds` | `true` | Emit Channel/EventID allow-lists for Zircolite storage. Set to `false` for custom collations or event ID coercions |
|
|
81
|
+
| `text_mode` | `portable` | Use `unicode` for Unicode case folding in detections, grouping and distinct counts |
|
|
82
|
+
| `presence_field` | none | JSON array column listing the flattened fields present in each source event |
|
|
83
|
+
| `sum_mode` | `portable` | Use `exact` to preserve integer window totals beyond SQLite's signed 64-bit range |
|
|
84
|
+
| `week_mode` | `iso` | ISO week of year (1–53). Use `legacy` for SQLite's Monday-based week 0–53 |
|
|
85
|
+
| `modifier_mode` | `sigma` | `windash` expands every dash position and `re\|startswith`/`re\|endswith` stay within the field. Use `pysigma` for pySigma's own expansion, as in 2.1 |
|
|
86
|
+
| `max_flat_operands` | `100` | Longer AND/OR chains are nested to stay under SQLite's expression depth limit |
|
|
87
|
+
| `cidr_mode` | `expanded` | Use portable prefix matching or opt into exact network membership with `exact` |
|
|
88
|
+
| `fulltext_field` | none | Column of searchable event text; enables [keyword search](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/keyword-search.md) |
|
|
89
|
+
| `timestamp_field` | `timestamp` | Event time column used by correlations |
|
|
90
|
+
| `timestamp_format` | `iso` | `iso`, `unix`, `unix_ms` or `unix_us` |
|
|
91
|
+
| `timestamp_seconds_expression` | ISO parser | SQL turning `{field}` into Unix seconds; overrides `timestamp_format` |
|
|
92
|
+
| `event_id_field` | `rowid` | Non-NULL, per-table unique event identifier for correlation evidence |
|
|
93
|
+
| `observation_end` | latest event | Unix seconds up to which absence windows can expire |
|
|
94
|
+
|
|
95
|
+
The optional Unicode, presence and exact-sum contracts require a consumer that
|
|
96
|
+
understands schema 5. The table below describes the portable settings.
|
|
97
|
+
[Sigma 2.1 feature support and parser compatibility](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/sigma-conformance.md)
|
|
98
|
+
|
|
99
|
+
## Generated SQL
|
|
100
|
+
|
|
101
|
+
| Modifier | SQL |
|
|
102
|
+
|---|---|
|
|
103
|
+
| `contains`, `startswith`, `endswith` | `LIKE '%value%' ESCAPE '\'` and its prefix/suffix forms |
|
|
104
|
+
| `all` | `AND` of the values |
|
|
105
|
+
| `re` | `REGEXP` (needs a registered function, see [Limitations](#limitations)) |
|
|
106
|
+
| `cidr` | Expanded mode uses `=` or `LIKE`. Exact mode uses equality for IPv4 `/32` and a registered membership function for other networks |
|
|
107
|
+
| `cased` | `GLOB`; literal `*`, `?`, `[` become `[*]`, `[?]`, `[[]` |
|
|
108
|
+
| `fieldref` | `field1=field2`, or `LIKE` with the second field's `%` and `_` escaped |
|
|
109
|
+
| `exists` | `IS NOT NULL` / `IS NULL` |
|
|
110
|
+
| `gt`, `gte`, `lt`, `lte` | Compare finite numbers and numeric text numerically |
|
|
111
|
+
| `neq` | Negated equality |
|
|
112
|
+
| `minute`, `hour`, `day`, `week`, `month`, `year` | Calendar part of an ISO-8601 timestamp |
|
|
113
|
+
| `base64`, `base64offset`, `wide`, `utf16be`, `utf16`, `windash` | Expanded into text predicates. Follow byte encodings with a Base64 modifier |
|
|
114
|
+
|
|
115
|
+
Generated SQL handles the following cases.
|
|
116
|
+
|
|
117
|
+
- **Negation.** Sigma reads a condition on a missing field as false; SQLite reads
|
|
118
|
+
it as `NULL`, and `NOT NULL` drops the row. Every `NOT` therefore wraps its
|
|
119
|
+
operand: `EventID=1 AND (NOT COALESCE((CommandLine LIKE '%foo%' ESCAPE '\'), 0))`.
|
|
120
|
+
- **Case.** `LIKE` ignores case; `=` does only on `NOCASE` columns (Zircolite's
|
|
121
|
+
layout), otherwise set `collate_nocase`.
|
|
122
|
+
- **Booleans.** `Flag: true` matches text or integer storage: `(Flag='true' OR Flag=1)`.
|
|
123
|
+
- **Field names.** SQLite keywords and names with characters other than letters,
|
|
124
|
+
digits and `_` are quoted with backticks. `field: null` becomes `field IS NULL`.
|
|
125
|
+
- **Numeric comparisons.** `gt`, `gte`, `lt` and `lte` validate and convert the
|
|
126
|
+
stored value before comparison. A plain index on that column cannot supply a
|
|
127
|
+
range lookup for this predicate, even on an `INTEGER` column. Detections read
|
|
128
|
+
`+11`, `11.` and `011` as eleven. Numeric correlation statistics accept text
|
|
129
|
+
in JSON number syntax and skip all three spellings.
|
|
130
|
+
|
|
131
|
+
## Correlations
|
|
132
|
+
|
|
133
|
+
All Sigma correlation types run in SQLite, including chains, aliases and extended
|
|
134
|
+
temporal conditions. See [correlations](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/correlations.md)
|
|
135
|
+
for their semantics and the [migration guide](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/migration-v2.md)
|
|
136
|
+
for upgrading from backend 1.x.
|
|
137
|
+
|
|
138
|
+
## CIDR matching
|
|
139
|
+
|
|
140
|
+
The default `cidr_mode="expanded"` uses portable SQL. It checks the spelling of
|
|
141
|
+
an address and can use SQLite prefix indexes. Exact mode parses the event value
|
|
142
|
+
and tests membership in the network. For example, SQL generated for these inputs
|
|
143
|
+
has the following behavior.
|
|
144
|
+
|
|
145
|
+
| CIDR | Event value | Expanded | Exact |
|
|
146
|
+
|---|---|---|---|
|
|
147
|
+
| `10.0.0.0/8` | `10.1.2.300` | match | no match |
|
|
148
|
+
| `10.0.0.0/8` | `10.1.2.3` followed by a space | match | no match |
|
|
149
|
+
| `2001:db8::/32` | `2001:0db8:0:0::1` | no match | match |
|
|
150
|
+
| `10.0.0.0/8` | `::ffff:10.0.0.5` (IPv4-mapped IPv6) | no match | no match |
|
|
151
|
+
| `0.0.0.0/0` | `::ffff:10.0.0.5` | match | no match |
|
|
152
|
+
| `::/0` | `10.0.0.5` | match | no match |
|
|
153
|
+
| Either `/0` | `unknown` | match | no match |
|
|
154
|
+
|
|
155
|
+
Both expanded `/0` networks compile to `LIKE '%'` and match every non-NULL
|
|
156
|
+
text value. Exact mode parses the address and respects its IP family.
|
|
157
|
+
|
|
158
|
+
```python
|
|
159
|
+
from sigma.backends.sqlite.runtime import register_cidr
|
|
160
|
+
|
|
161
|
+
register_cidr(connection)
|
|
162
|
+
query = sqliteBackend(cidr_mode="exact").convert(rules)[0]
|
|
163
|
+
rows = connection.execute(query).fetchall()
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
For sigma-cli, pass `-O cidr_mode=exact` and register the function on the connection
|
|
167
|
+
that executes the SQL. IPv4 ranges with at least one fixed octet can use a prefix
|
|
168
|
+
or equality index. When an IPv6 network fixes a nonzero first group of 16 bits,
|
|
169
|
+
SQLite checks that group before parsing the address, allowing any valid letter
|
|
170
|
+
case or leading zeros. This check can use a compatible index. Other IPv6
|
|
171
|
+
networks skip values without a colon before parsing.
|
|
172
|
+
Exact IPv4 `/32` uses a built-in SQLite comparison. Zircolite 4.7.1 can run
|
|
173
|
+
these entries without registering a function. Entries that use the CIDR
|
|
174
|
+
function require a schema-4 consumer. [Original CIDR report](https://github.com/SigmaHQ/pySigma-backend-sqlite/issues/17)
|
|
175
|
+
|
|
176
|
+
## Keyword search
|
|
177
|
+
|
|
178
|
+
Keyword (fieldless) rules need `fulltext_field`, a column holding each event's
|
|
179
|
+
searchable text. See [keyword search](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/keyword-search.md).
|
|
180
|
+
|
|
181
|
+
## Limitations
|
|
182
|
+
|
|
183
|
+
- **REGEXP.** SQLite has no built-in `REGEXP`. Register one that is false for `NULL`:
|
|
184
|
+
`connection.create_function("regexp", 2, lambda p, v: v is not None and re.search(p, str(v)) is not None)`.
|
|
185
|
+
pySigma validates `|re` with RE2 by default, rejecting lookarounds and
|
|
186
|
+
backreferences. For trusted rules, pass `policy=TrustedPolicy` (from
|
|
187
|
+
`sigma.policy.profiles`) to `SigmaCollection.from_yaml()`; the patterns must then
|
|
188
|
+
suit Python's `re`.
|
|
189
|
+
- **Case folding.** Stock BINARY columns compare literal text case-sensitively. SQLite NOCASE columns or `collate_nocase=True` cover ASCII. Set `text_mode="unicode"` and register the runtime helpers for Unicode equality, wildcards, field comparisons and keywords.
|
|
190
|
+
- **Timestamp parts** use `strftime()` and need ISO-8601 text; a numeric epoch is
|
|
191
|
+
read as a Julian day. ISO week 53 occurs in some years. Only `week_mode="legacy"` can produce week 0.
|
|
192
|
+
- **Field existence.** With `presence_field`, `exists` includes an explicitly null field. The default uses SQL NULL as a proxy for absence.
|
|
193
|
+
- **Multi-field `value_count`** counts distinct complete tuples in each window. A NULL component excludes that tuple from the count.
|
|
194
|
+
- **Unknown columns.** A query naming a column the table lacks fails to prepare.
|
|
195
|
+
Add missing columns as `NULL` first; see [output format](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/output-format.md).
|
|
196
|
+
|
|
197
|
+
## Development
|
|
198
|
+
|
|
199
|
+
```shell
|
|
200
|
+
poetry install
|
|
201
|
+
poetry run pytest
|
|
202
|
+
SQLITE_MIN_BINARY=/path/to/sqlite-3.38 poetry run pytest tests/test_sqlite_minimum.py
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
`tools/audit_corpus.py` converts and prepares a SigmaHQ checkout per profile (see
|
|
206
|
+
[coverage](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/keyword-search.md#coverage)).
|
|
207
|
+
`tools/benchmark_correlations.py` times sparse and dense correlation windows.
|
|
208
|
+
`tools/benchmark_cidr.py` compares expanded and exact event queries and
|
|
209
|
+
materialized correlations over indexed and unindexed IPv4 and IPv6 data.
|
|
210
|
+
It checks event and evidence identities and records SQLite query plans.
|
|
211
|
+
|
|
212
|
+
```shell
|
|
213
|
+
poetry run python tools/benchmark_cidr.py --size 100000 --iterations 5 --output cidr.json
|
|
214
|
+
```
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "pySigma-backend-sqlite"
|
|
3
|
-
version = "2.
|
|
3
|
+
version = "2.2.0"
|
|
4
4
|
requires-python = ">=3.11,<4.0"
|
|
5
|
-
dependencies = ["pysigma>=2.
|
|
5
|
+
dependencies = ["pysigma>=2.1.0,<3.0"]
|
|
6
6
|
description = "pySigma sqlite backend"
|
|
7
7
|
readme = "README.md"
|
|
8
8
|
authors = [
|
|
@@ -16,18 +16,21 @@ packages = [
|
|
|
16
16
|
]
|
|
17
17
|
|
|
18
18
|
[tool.poetry.group.dev.dependencies]
|
|
19
|
-
black = "^24.1"
|
|
20
19
|
pytest = "^8.0"
|
|
21
|
-
|
|
20
|
+
typing-extensions = "^4.0"
|
|
21
|
+
pytest-cov = "^7.1"
|
|
22
22
|
coverage = "^7.4"
|
|
23
|
+
ruff = "^0.16.10"
|
|
23
24
|
|
|
24
25
|
|
|
25
26
|
[tool.pytest.ini_options]
|
|
26
27
|
testpaths = ["tests"]
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
28
|
+
|
|
29
|
+
[tool.ruff]
|
|
30
|
+
target-version = "py311"
|
|
31
|
+
|
|
32
|
+
[tool.ruff.lint]
|
|
33
|
+
select = ["E4", "E7", "E9", "F", "I", "UP"]
|
|
31
34
|
|
|
32
35
|
[build-system]
|
|
33
36
|
requires = ["poetry-core>=2.0.0"]
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Exact CIDR matching for SQLite connections that opt into the function."""
|
|
2
|
+
|
|
3
|
+
from functools import lru_cache
|
|
4
|
+
from ipaddress import ip_address, ip_network
|
|
5
|
+
|
|
6
|
+
CIDR_FUNCTION = "sigma_cidr_contains"
|
|
7
|
+
# Typical IPv6 network literals fit in 50 characters. Scope identifiers and
|
|
8
|
+
# malformed log values may be arbitrarily long; parse those without caching.
|
|
9
|
+
_MAX_CACHE_KEY_LENGTH = 128
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def required_sql_functions(states):
|
|
13
|
+
"""Read the function dependencies recorded while compiling these conditions."""
|
|
14
|
+
if any(getattr(state, "sqlite_uses_cidr", False) for state in states):
|
|
15
|
+
return [CIDR_FUNCTION]
|
|
16
|
+
return []
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def register_cidr(connection):
|
|
20
|
+
"""Register sigma_cidr_contains(address, network) with connection-local caches."""
|
|
21
|
+
|
|
22
|
+
def parse_network(value):
|
|
23
|
+
try:
|
|
24
|
+
return ip_network(value)
|
|
25
|
+
except ValueError:
|
|
26
|
+
return None
|
|
27
|
+
|
|
28
|
+
def parse_address(value):
|
|
29
|
+
try:
|
|
30
|
+
return ip_address(value)
|
|
31
|
+
except ValueError:
|
|
32
|
+
return None
|
|
33
|
+
|
|
34
|
+
cached_network = lru_cache(maxsize=256)(parse_network)
|
|
35
|
+
cached_address = lru_cache(maxsize=4096)(parse_address)
|
|
36
|
+
|
|
37
|
+
def contains(address, network):
|
|
38
|
+
if not isinstance(address, str) or not isinstance(network, str):
|
|
39
|
+
return 0
|
|
40
|
+
net = (
|
|
41
|
+
cached_network(network)
|
|
42
|
+
if len(network) <= _MAX_CACHE_KEY_LENGTH
|
|
43
|
+
else parse_network(network)
|
|
44
|
+
)
|
|
45
|
+
addr = (
|
|
46
|
+
cached_address(address)
|
|
47
|
+
if len(address) <= _MAX_CACHE_KEY_LENGTH
|
|
48
|
+
else parse_address(address)
|
|
49
|
+
)
|
|
50
|
+
return int(net is not None and addr is not None and addr in net)
|
|
51
|
+
|
|
52
|
+
connection.create_function(CIDR_FUNCTION, 2, contains, deterministic=True)
|