pySigma-backend-sqlite 2.1.1__tar.gz → 2.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,234 @@
1
+ Metadata-Version: 2.4
2
+ Name: pySigma-backend-sqlite
3
+ Version: 2.3.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.2,<3.0)
16
+ Project-URL: Repository, https://github.com/SigmaHQ/pySigma-backend-sqlite
17
+ Description-Content-Type: text/markdown
18
+
19
+ ![Tests](https://github.com/wagga40/pySigma-backend-sqlite/actions/workflows/test.yml/badge.svg)
20
+ ![Upstream coverage](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/wagga40/2ec45ded898fa11f2c42bcb9d2b163cf/raw/test.json)
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.2 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
+ | `presence_representation` | `field-names-v1` | Use `null-field-names-v1` when `presence_field` lists only the fields stored as NULL |
102
+ | `sum_mode` | `portable` | Use `exact` to preserve integer window totals beyond SQLite's signed 64-bit range |
103
+ | `week_mode` | `iso` | ISO week of year (1–53). Use `legacy` for SQLite's Monday-based week 0–53 |
104
+ | `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 |
105
+ | `max_flat_operands` | `100` | Longer AND/OR chains are nested to stay under SQLite's expression depth limit |
106
+ | `cidr_mode` | `expanded` | Use portable prefix matching or opt into exact network membership with `exact` |
107
+ | `fulltext_field` | none | Column of searchable event text; enables [keyword search](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/keyword-search.md) |
108
+ | `timestamp_field` | `timestamp` | Event time column used by correlations |
109
+ | `timestamp_format` | `iso` | `iso`, `unix`, `unix_ms` or `unix_us` |
110
+ | `timestamp_seconds_expression` | ISO parser | SQL turning `{field}` into Unix seconds; overrides `timestamp_format` |
111
+ | `event_id_field` | `rowid` | Non-NULL, per-table unique event identifier for correlation evidence |
112
+ | `observation_end` | latest event | Unix seconds up to which absence windows can expire |
113
+
114
+ The optional Unicode, presence and exact-sum contracts require a consumer that
115
+ understands schema 5. The table below describes the portable settings.
116
+ [Sigma 2.1 feature support and parser compatibility](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/sigma-conformance.md)
117
+
118
+ ## Generated SQL
119
+
120
+ | Modifier | SQL |
121
+ |---|---|
122
+ | `contains`, `startswith`, `endswith` | `LIKE '%value%' ESCAPE '\'` and its prefix/suffix forms |
123
+ | `all` | `AND` of the values |
124
+ | `re` | `REGEXP` (needs a registered function, see [Limitations](#limitations)) |
125
+ | `cidr` | Expanded mode uses `=` or `LIKE`. Exact mode uses equality for IPv4 `/32` and a registered membership function for other networks |
126
+ | `cased` | `GLOB`; literal `*`, `?`, `[` become `[*]`, `[?]`, `[[]` |
127
+ | `fieldref` | `field1=field2`, or `LIKE` with the second field's `%` and `_` escaped |
128
+ | `exists` | `IS NOT NULL` / `IS NULL` |
129
+ | `gt`, `gte`, `lt`, `lte` | Compare finite numbers and numeric text numerically |
130
+ | `neq` | Negated equality |
131
+ | `minute`, `hour`, `day`, `week`, `month`, `year` | Calendar part of an ISO-8601 timestamp |
132
+ | `base64`, `base64offset`, `wide`, `utf16be`, `utf16`, `windash` | Expanded into text predicates. Follow byte encodings with a Base64 modifier |
133
+
134
+ Generated SQL handles the following cases.
135
+
136
+ - **Negation.** Sigma reads a condition on a missing field as false; SQLite reads
137
+ it as `NULL`, and `NOT NULL` drops the row. Every `NOT` therefore wraps its
138
+ operand: `EventID=1 AND (NOT COALESCE((CommandLine LIKE '%foo%' ESCAPE '\'), 0))`.
139
+ - **Case.** `LIKE` ignores case; `=` does only on `NOCASE` columns (Zircolite's
140
+ layout), otherwise set `collate_nocase`.
141
+ - **Booleans.** `Flag: true` matches text or integer storage: `(Flag='true' OR Flag=1)`.
142
+ - **Field names.** SQLite keywords and names with characters other than letters,
143
+ digits and `_` are quoted with backticks. `field: null` becomes `field IS NULL`.
144
+ - **Numeric comparisons.** `gt`, `gte`, `lt` and `lte` validate and convert the
145
+ stored value before comparison. A plain index on that column cannot supply a
146
+ range lookup for this predicate, even on an `INTEGER` column. Detections read
147
+ `+11`, `11.` and `011` as eleven. Numeric correlation statistics accept text
148
+ in JSON number syntax and skip all three spellings.
149
+
150
+ ## Correlations
151
+
152
+ All Sigma correlation types run in SQLite, including chains, aliases and extended
153
+ temporal conditions. See [correlations](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/correlations.md)
154
+ for their semantics and the [migration guide](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/migration-v2.md)
155
+ for upgrading from backend 1.x.
156
+
157
+ ## CIDR matching
158
+
159
+ The default `cidr_mode="expanded"` uses portable SQL. It checks the spelling of
160
+ an address and can use SQLite prefix indexes. Exact mode parses the event value
161
+ and tests membership in the network. For example, SQL generated for these inputs
162
+ has the following behavior.
163
+
164
+ | CIDR | Event value | Expanded | Exact |
165
+ |---|---|---|---|
166
+ | `10.0.0.0/8` | `10.1.2.300` | match | no match |
167
+ | `10.0.0.0/8` | `10.1.2.3` followed by a space | match | no match |
168
+ | `2001:db8::/32` | `2001:0db8:0:0::1` | no match | match |
169
+ | `10.0.0.0/8` | `::ffff:10.0.0.5` (IPv4-mapped IPv6) | no match | no match |
170
+ | `0.0.0.0/0` | `::ffff:10.0.0.5` | match | no match |
171
+ | `::/0` | `10.0.0.5` | match | no match |
172
+ | Either `/0` | `unknown` | match | no match |
173
+
174
+ Both expanded `/0` networks compile to `LIKE '%'` and match every non-NULL
175
+ text value. Exact mode parses the address and respects its IP family.
176
+
177
+ ```python
178
+ from sigma.backends.sqlite.runtime import register_cidr
179
+
180
+ register_cidr(connection)
181
+ query = sqliteBackend(cidr_mode="exact").convert(rules)[0]
182
+ rows = connection.execute(query).fetchall()
183
+ ```
184
+
185
+ For sigma-cli, pass `-O cidr_mode=exact` and register the function on the connection
186
+ that executes the SQL. IPv4 ranges with at least one fixed octet can use a prefix
187
+ or equality index. When an IPv6 network fixes a nonzero first group of 16 bits,
188
+ SQLite checks that group before parsing the address, allowing any valid letter
189
+ case or leading zeros. This check can use a compatible index. Other IPv6
190
+ networks skip values without a colon before parsing.
191
+ Exact IPv4 `/32` uses a built-in SQLite comparison. Zircolite 4.7.1 can run
192
+ these entries without registering a function. Entries that use the CIDR
193
+ function require a schema-4 consumer. [Original CIDR report](https://github.com/SigmaHQ/pySigma-backend-sqlite/issues/17)
194
+
195
+ ## Keyword search
196
+
197
+ Keyword (fieldless) rules need `fulltext_field`, a column holding each event's
198
+ searchable text. See [keyword search](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/keyword-search.md).
199
+
200
+ ## Limitations
201
+
202
+ - **REGEXP.** SQLite has no built-in `REGEXP`. Register one that is false for `NULL`:
203
+ `connection.create_function("regexp", 2, lambda p, v: v is not None and re.search(p, str(v)) is not None)`.
204
+ pySigma validates `|re` with RE2 by default, rejecting lookarounds and
205
+ backreferences. For trusted rules, pass `policy=TrustedPolicy` (from
206
+ `sigma.policy.profiles`) to `SigmaCollection.from_yaml()`; the patterns must then
207
+ suit Python's `re`.
208
+ - **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.
209
+ - **Timestamp parts** use `strftime()` and need ISO-8601 text; a numeric epoch is
210
+ read as a Julian day. ISO week 53 occurs in some years. Only `week_mode="legacy"` can produce week 0.
211
+ - **Field existence.** The default uses SQL NULL as a proxy for absence. With `presence_field`, `exists` also counts an explicitly null field. The column lists every field of the source event, or only the fields stored as NULL with `presence_representation="null-field-names-v1"`. That mode reads the field's own column first and matches listed names ASCII case-insensitively.
212
+ - **Multi-field `value_count`** counts distinct complete tuples in each window. A NULL component excludes that tuple from the count.
213
+ - **Unknown columns.** A query naming a column the table lacks fails to prepare.
214
+ Add missing columns as `NULL` first; see [output format](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/output-format.md).
215
+
216
+ ## Development
217
+
218
+ ```shell
219
+ poetry install
220
+ poetry run pytest
221
+ SQLITE_MIN_BINARY=/path/to/sqlite-3.38 poetry run pytest tests/test_sqlite_minimum.py
222
+ ```
223
+
224
+ `tools/audit_corpus.py` converts and prepares a SigmaHQ checkout per profile (see
225
+ [coverage](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/keyword-search.md#coverage)).
226
+ `tools/benchmark_correlations.py` times sparse and dense correlation windows.
227
+ `tools/benchmark_cidr.py` compares expanded and exact event queries and
228
+ materialized correlations over indexed and unindexed IPv4 and IPv6 data.
229
+ It checks event and evidence identities and records SQLite query plans.
230
+
231
+ ```shell
232
+ poetry run python tools/benchmark_cidr.py --size 100000 --iterations 5 --output cidr.json
233
+ ```
234
+
@@ -0,0 +1,215 @@
1
+ ![Tests](https://github.com/wagga40/pySigma-backend-sqlite/actions/workflows/test.yml/badge.svg)
2
+ ![Upstream coverage](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/wagga40/2ec45ded898fa11f2c42bcb9d2b163cf/raw/test.json)
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.2 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
+ | `presence_representation` | `field-names-v1` | Use `null-field-names-v1` when `presence_field` lists only the fields stored as NULL |
84
+ | `sum_mode` | `portable` | Use `exact` to preserve integer window totals beyond SQLite's signed 64-bit range |
85
+ | `week_mode` | `iso` | ISO week of year (1–53). Use `legacy` for SQLite's Monday-based week 0–53 |
86
+ | `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 |
87
+ | `max_flat_operands` | `100` | Longer AND/OR chains are nested to stay under SQLite's expression depth limit |
88
+ | `cidr_mode` | `expanded` | Use portable prefix matching or opt into exact network membership with `exact` |
89
+ | `fulltext_field` | none | Column of searchable event text; enables [keyword search](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/keyword-search.md) |
90
+ | `timestamp_field` | `timestamp` | Event time column used by correlations |
91
+ | `timestamp_format` | `iso` | `iso`, `unix`, `unix_ms` or `unix_us` |
92
+ | `timestamp_seconds_expression` | ISO parser | SQL turning `{field}` into Unix seconds; overrides `timestamp_format` |
93
+ | `event_id_field` | `rowid` | Non-NULL, per-table unique event identifier for correlation evidence |
94
+ | `observation_end` | latest event | Unix seconds up to which absence windows can expire |
95
+
96
+ The optional Unicode, presence and exact-sum contracts require a consumer that
97
+ understands schema 5. The table below describes the portable settings.
98
+ [Sigma 2.1 feature support and parser compatibility](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/sigma-conformance.md)
99
+
100
+ ## Generated SQL
101
+
102
+ | Modifier | SQL |
103
+ |---|---|
104
+ | `contains`, `startswith`, `endswith` | `LIKE '%value%' ESCAPE '\'` and its prefix/suffix forms |
105
+ | `all` | `AND` of the values |
106
+ | `re` | `REGEXP` (needs a registered function, see [Limitations](#limitations)) |
107
+ | `cidr` | Expanded mode uses `=` or `LIKE`. Exact mode uses equality for IPv4 `/32` and a registered membership function for other networks |
108
+ | `cased` | `GLOB`; literal `*`, `?`, `[` become `[*]`, `[?]`, `[[]` |
109
+ | `fieldref` | `field1=field2`, or `LIKE` with the second field's `%` and `_` escaped |
110
+ | `exists` | `IS NOT NULL` / `IS NULL` |
111
+ | `gt`, `gte`, `lt`, `lte` | Compare finite numbers and numeric text numerically |
112
+ | `neq` | Negated equality |
113
+ | `minute`, `hour`, `day`, `week`, `month`, `year` | Calendar part of an ISO-8601 timestamp |
114
+ | `base64`, `base64offset`, `wide`, `utf16be`, `utf16`, `windash` | Expanded into text predicates. Follow byte encodings with a Base64 modifier |
115
+
116
+ Generated SQL handles the following cases.
117
+
118
+ - **Negation.** Sigma reads a condition on a missing field as false; SQLite reads
119
+ it as `NULL`, and `NOT NULL` drops the row. Every `NOT` therefore wraps its
120
+ operand: `EventID=1 AND (NOT COALESCE((CommandLine LIKE '%foo%' ESCAPE '\'), 0))`.
121
+ - **Case.** `LIKE` ignores case; `=` does only on `NOCASE` columns (Zircolite's
122
+ layout), otherwise set `collate_nocase`.
123
+ - **Booleans.** `Flag: true` matches text or integer storage: `(Flag='true' OR Flag=1)`.
124
+ - **Field names.** SQLite keywords and names with characters other than letters,
125
+ digits and `_` are quoted with backticks. `field: null` becomes `field IS NULL`.
126
+ - **Numeric comparisons.** `gt`, `gte`, `lt` and `lte` validate and convert the
127
+ stored value before comparison. A plain index on that column cannot supply a
128
+ range lookup for this predicate, even on an `INTEGER` column. Detections read
129
+ `+11`, `11.` and `011` as eleven. Numeric correlation statistics accept text
130
+ in JSON number syntax and skip all three spellings.
131
+
132
+ ## Correlations
133
+
134
+ All Sigma correlation types run in SQLite, including chains, aliases and extended
135
+ temporal conditions. See [correlations](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/correlations.md)
136
+ for their semantics and the [migration guide](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/migration-v2.md)
137
+ for upgrading from backend 1.x.
138
+
139
+ ## CIDR matching
140
+
141
+ The default `cidr_mode="expanded"` uses portable SQL. It checks the spelling of
142
+ an address and can use SQLite prefix indexes. Exact mode parses the event value
143
+ and tests membership in the network. For example, SQL generated for these inputs
144
+ has the following behavior.
145
+
146
+ | CIDR | Event value | Expanded | Exact |
147
+ |---|---|---|---|
148
+ | `10.0.0.0/8` | `10.1.2.300` | match | no match |
149
+ | `10.0.0.0/8` | `10.1.2.3` followed by a space | match | no match |
150
+ | `2001:db8::/32` | `2001:0db8:0:0::1` | no match | match |
151
+ | `10.0.0.0/8` | `::ffff:10.0.0.5` (IPv4-mapped IPv6) | no match | no match |
152
+ | `0.0.0.0/0` | `::ffff:10.0.0.5` | match | no match |
153
+ | `::/0` | `10.0.0.5` | match | no match |
154
+ | Either `/0` | `unknown` | match | no match |
155
+
156
+ Both expanded `/0` networks compile to `LIKE '%'` and match every non-NULL
157
+ text value. Exact mode parses the address and respects its IP family.
158
+
159
+ ```python
160
+ from sigma.backends.sqlite.runtime import register_cidr
161
+
162
+ register_cidr(connection)
163
+ query = sqliteBackend(cidr_mode="exact").convert(rules)[0]
164
+ rows = connection.execute(query).fetchall()
165
+ ```
166
+
167
+ For sigma-cli, pass `-O cidr_mode=exact` and register the function on the connection
168
+ that executes the SQL. IPv4 ranges with at least one fixed octet can use a prefix
169
+ or equality index. When an IPv6 network fixes a nonzero first group of 16 bits,
170
+ SQLite checks that group before parsing the address, allowing any valid letter
171
+ case or leading zeros. This check can use a compatible index. Other IPv6
172
+ networks skip values without a colon before parsing.
173
+ Exact IPv4 `/32` uses a built-in SQLite comparison. Zircolite 4.7.1 can run
174
+ these entries without registering a function. Entries that use the CIDR
175
+ function require a schema-4 consumer. [Original CIDR report](https://github.com/SigmaHQ/pySigma-backend-sqlite/issues/17)
176
+
177
+ ## Keyword search
178
+
179
+ Keyword (fieldless) rules need `fulltext_field`, a column holding each event's
180
+ searchable text. See [keyword search](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/keyword-search.md).
181
+
182
+ ## Limitations
183
+
184
+ - **REGEXP.** SQLite has no built-in `REGEXP`. Register one that is false for `NULL`:
185
+ `connection.create_function("regexp", 2, lambda p, v: v is not None and re.search(p, str(v)) is not None)`.
186
+ pySigma validates `|re` with RE2 by default, rejecting lookarounds and
187
+ backreferences. For trusted rules, pass `policy=TrustedPolicy` (from
188
+ `sigma.policy.profiles`) to `SigmaCollection.from_yaml()`; the patterns must then
189
+ suit Python's `re`.
190
+ - **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.
191
+ - **Timestamp parts** use `strftime()` and need ISO-8601 text; a numeric epoch is
192
+ read as a Julian day. ISO week 53 occurs in some years. Only `week_mode="legacy"` can produce week 0.
193
+ - **Field existence.** The default uses SQL NULL as a proxy for absence. With `presence_field`, `exists` also counts an explicitly null field. The column lists every field of the source event, or only the fields stored as NULL with `presence_representation="null-field-names-v1"`. That mode reads the field's own column first and matches listed names ASCII case-insensitively.
194
+ - **Multi-field `value_count`** counts distinct complete tuples in each window. A NULL component excludes that tuple from the count.
195
+ - **Unknown columns.** A query naming a column the table lacks fails to prepare.
196
+ Add missing columns as `NULL` first; see [output format](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/output-format.md).
197
+
198
+ ## Development
199
+
200
+ ```shell
201
+ poetry install
202
+ poetry run pytest
203
+ SQLITE_MIN_BINARY=/path/to/sqlite-3.38 poetry run pytest tests/test_sqlite_minimum.py
204
+ ```
205
+
206
+ `tools/audit_corpus.py` converts and prepares a SigmaHQ checkout per profile (see
207
+ [coverage](https://github.com/wagga40/pySigma-backend-sqlite/blob/main/docs/keyword-search.md#coverage)).
208
+ `tools/benchmark_correlations.py` times sparse and dense correlation windows.
209
+ `tools/benchmark_cidr.py` compares expanded and exact event queries and
210
+ materialized correlations over indexed and unindexed IPv4 and IPv6 data.
211
+ It checks event and evidence identities and records SQLite query plans.
212
+
213
+ ```shell
214
+ poetry run python tools/benchmark_cidr.py --size 100000 --iterations 5 --output cidr.json
215
+ ```
@@ -1,8 +1,8 @@
1
1
  [project]
2
2
  name = "pySigma-backend-sqlite"
3
- version = "2.1.1"
3
+ version = "2.3.0"
4
4
  requires-python = ">=3.11,<4.0"
5
- dependencies = ["pysigma>=2.0.1,<3.0"]
5
+ dependencies = ["pysigma>=2.1.2,<3.0"]
6
6
  description = "pySigma sqlite backend"
7
7
  readme = "README.md"
8
8
  authors = [
@@ -17,6 +17,7 @@ packages = [
17
17
 
18
18
  [tool.poetry.group.dev.dependencies]
19
19
  pytest = "^8.0"
20
+ typing-extensions = "^4.0"
20
21
  pytest-cov = "^7.1"
21
22
  coverage = "^7.4"
22
23
  ruff = "^0.16.10"
@@ -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)