sigmux 0.3.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.
sigmux/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """sigmux — convert Sigma detection rules into multiple SIEM query languages."""
2
+
3
+ __version__ = "0.1.0"
sigmux/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
sigmux/ast_nodes.py ADDED
@@ -0,0 +1,36 @@
1
+ """AST node types for a parsed Sigma detection condition.
2
+
3
+ The tree is intentionally tiny: everything Sigma's detection language can
4
+ express reduces to four shapes once selections have been resolved into
5
+ their component field matches.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass, field
10
+ from typing import List
11
+
12
+
13
+ class Node:
14
+ """Base class for all AST nodes."""
15
+
16
+
17
+ @dataclass
18
+ class FieldMatch(Node):
19
+ field: str
20
+ modifier: str # one of: eq, contains, startswith, endswith, re
21
+ value: str
22
+
23
+
24
+ @dataclass
25
+ class And(Node):
26
+ children: List[Node] = field(default_factory=list)
27
+
28
+
29
+ @dataclass
30
+ class Or(Node):
31
+ children: List[Node] = field(default_factory=list)
32
+
33
+
34
+ @dataclass
35
+ class Not(Node):
36
+ child: Node
@@ -0,0 +1,38 @@
1
+ """Backend registry: maps a target name to its converter implementation.
2
+
3
+ Target names match detectl's platform names 1:1 (elastic, crowdstrike,
4
+ sentinel, splunk, qradar, sumologic, chronicle) -- deliberately, so a
5
+ sigmux target and the detectl platform you'd push its output to are always
6
+ the same name. See "Pairs well with detectl" in the README.
7
+ """
8
+ from .base import Backend
9
+ from .chronicle import ChronicleBackend
10
+ from .crowdstrike import CrowdStrikeBackend
11
+ from .elastic import ElasticBackend
12
+ from .qradar import QRadarBackend
13
+ from .sentinel import SentinelBackend
14
+ from .splunk import SplunkBackend
15
+ from .sumologic import SumoLogicBackend
16
+
17
+ REGISTRY = {
18
+ "splunk": SplunkBackend(),
19
+ "elastic": ElasticBackend(),
20
+ "sentinel": SentinelBackend(),
21
+ "crowdstrike": CrowdStrikeBackend(),
22
+ "qradar": QRadarBackend(),
23
+ "chronicle": ChronicleBackend(),
24
+ "sumologic": SumoLogicBackend(),
25
+ }
26
+
27
+
28
+ def get_backend(name: str) -> Backend:
29
+ try:
30
+ return REGISTRY[name]
31
+ except KeyError as exc:
32
+ available = ", ".join(sorted(REGISTRY))
33
+ raise ValueError(
34
+ f"Unknown target '{name}'. Available targets: {available}"
35
+ ) from exc
36
+
37
+
38
+ __all__ = ["Backend", "REGISTRY", "get_backend"]
@@ -0,0 +1,18 @@
1
+ """Shared interface for query-language backends."""
2
+ from __future__ import annotations
3
+
4
+ from abc import ABC, abstractmethod
5
+ from typing import TYPE_CHECKING
6
+
7
+ if TYPE_CHECKING:
8
+ from ..rule import SigmaRule
9
+
10
+
11
+ class Backend(ABC):
12
+ """Turns a parsed Sigma rule's AST into a target query string."""
13
+
14
+ name: str
15
+
16
+ @abstractmethod
17
+ def render(self, rule: "SigmaRule") -> str:
18
+ ...
@@ -0,0 +1,110 @@
1
+ """Google Security Operations (Chronicle) YARA-L 2.0 backend.
2
+
3
+ Unlike the other backends, this doesn't render a bare query expression --
4
+ YARA-L rules are a small structured language of their own (`meta` /
5
+ `events` / `condition` blocks), so this backend builds the whole rule
6
+ skeleton around the same field-match/boolean AST every other backend walks.
7
+
8
+ Two things are deliberately best-effort, in the same spirit as the Sentinel
9
+ backend's logsource->table map:
10
+ - `metadata.event_type` is guessed from the Sigma logsource the same way
11
+ Sentinel guesses its table, defaulting to `GENERIC_EVENT`.
12
+ - Field names are emitted as the raw Sigma field name under the event
13
+ variable (`$e.Image`, ...) rather than mapped onto Chronicle's real UDM
14
+ schema (`$e.target.process.file.full_path`, ...) -- that mapping is
15
+ product/log-source-specific and out of scope here.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import re as _re
20
+ from typing import TYPE_CHECKING, Dict, Optional, Tuple
21
+
22
+ from ..ast_nodes import And, FieldMatch, Node, Not, Or
23
+ from .base import Backend
24
+
25
+ if TYPE_CHECKING:
26
+ from ..rule import SigmaRule
27
+
28
+ _EVENT_TYPE_MAP: Dict[Tuple[Optional[str], Optional[str]], str] = {
29
+ ("process_creation", None): "PROCESS_LAUNCH",
30
+ ("network_connection", None): "NETWORK_CONNECTION",
31
+ ("file_event", None): "FILE_CREATION",
32
+ ("file_change", None): "FILE_MODIFICATION",
33
+ ("registry_event", None): "REGISTRY_MODIFICATION",
34
+ ("registry_add", None): "REGISTRY_CREATION",
35
+ }
36
+ _DEFAULT_EVENT_TYPE = "GENERIC_EVENT"
37
+
38
+
39
+ def _event_type_for(logsource: Dict[str, str]) -> str:
40
+ category = logsource.get("category")
41
+ return _EVENT_TYPE_MAP.get((category, None), _DEFAULT_EVENT_TYPE)
42
+
43
+
44
+ def _quote(value: str) -> str:
45
+ return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
46
+
47
+
48
+ def _rule_name(title: str) -> str:
49
+ name = _re.sub(r"[^A-Za-z0-9_]", "_", title).strip("_")
50
+ if not name:
51
+ name = "sigma_rule"
52
+ if name[0].isdigit():
53
+ name = f"rule_{name}"
54
+ return name
55
+
56
+
57
+ def _match(fm: FieldMatch) -> str:
58
+ if fm.modifier == "eq":
59
+ return f"$e.{fm.field} = {_quote(fm.value)}"
60
+ if fm.modifier == "contains":
61
+ return f"$e.{fm.field} contains {_quote(fm.value)}"
62
+ if fm.modifier == "startswith":
63
+ return f're.regex($e.{fm.field}, {_quote("^" + _re.escape(fm.value))})'
64
+ if fm.modifier == "endswith":
65
+ return f're.regex($e.{fm.field}, {_quote(_re.escape(fm.value) + "$")})'
66
+ if fm.modifier == "re":
67
+ return f"re.regex($e.{fm.field}, {_quote(fm.value)})"
68
+ raise ValueError(f"Unsupported modifier: {fm.modifier}")
69
+
70
+
71
+ def _render(node: Node, top: bool = False) -> str:
72
+ if isinstance(node, FieldMatch):
73
+ return _match(node)
74
+ if isinstance(node, And):
75
+ joined = " and ".join(_render(c) for c in node.children)
76
+ return joined if top else f"({joined})"
77
+ if isinstance(node, Or):
78
+ joined = " or ".join(_render(c) for c in node.children)
79
+ return joined if top else f"({joined})"
80
+ if isinstance(node, Not):
81
+ return f"not ({_render(node.child, top=True)})"
82
+ raise TypeError(f"Unknown node type: {type(node)!r}")
83
+
84
+
85
+ class ChronicleBackend(Backend):
86
+ name = "chronicle"
87
+
88
+ def render(self, rule: "SigmaRule") -> str:
89
+ event_type = _event_type_for(rule.logsource)
90
+ expr = _render(rule.ast, top=True)
91
+
92
+ meta_lines = ['author = "sigmux"']
93
+ if rule.description:
94
+ meta_lines.append(f"description = {_quote(rule.description)}")
95
+ if rule.level:
96
+ meta_lines.append(f'severity = "{rule.level.upper()}"')
97
+ if rule.id:
98
+ meta_lines.append(f'reference = "{rule.id}"')
99
+ meta_block = "\n".join(f" {line}" for line in meta_lines)
100
+
101
+ return (
102
+ f"rule {_rule_name(rule.title)} {{\n"
103
+ f" meta:\n{meta_block}\n\n"
104
+ f" events:\n"
105
+ f' $e.metadata.event_type = "{event_type}"\n'
106
+ f" {expr}\n\n"
107
+ f" condition:\n"
108
+ f" $e\n"
109
+ f"}}"
110
+ )
@@ -0,0 +1,55 @@
1
+ """CrowdStrike Falcon LogScale (LQL) backend.
2
+
3
+ LogScale's query language reads a lot like Splunk's SPL for field matching
4
+ (bare `field = value` terms, wildcards embedded directly in the compared
5
+ string) but uses lowercase boolean keywords and `/pattern/` regex literals
6
+ instead of a separate `regex` pipe stage.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from typing import TYPE_CHECKING
11
+
12
+ from ..ast_nodes import And, FieldMatch, Node, Not, Or
13
+ from .base import Backend
14
+
15
+ if TYPE_CHECKING:
16
+ from ..rule import SigmaRule
17
+
18
+
19
+ def _term(value: str) -> str:
20
+ return f'"{value}"' if (" " in value or value == "") else value
21
+
22
+
23
+ def _match(fm: FieldMatch) -> str:
24
+ if fm.modifier == "eq":
25
+ return f"{fm.field} = {_term(fm.value)}"
26
+ if fm.modifier == "contains":
27
+ return f"{fm.field} = {_term(f'*{fm.value}*')}"
28
+ if fm.modifier == "startswith":
29
+ return f"{fm.field} = {_term(f'{fm.value}*')}"
30
+ if fm.modifier == "endswith":
31
+ return f"{fm.field} = {_term(f'*{fm.value}')}"
32
+ if fm.modifier == "re":
33
+ return f"{fm.field} = /{fm.value}/"
34
+ raise ValueError(f"Unsupported modifier: {fm.modifier}")
35
+
36
+
37
+ def _render(node: Node, top: bool = False) -> str:
38
+ if isinstance(node, FieldMatch):
39
+ return _match(node)
40
+ if isinstance(node, And):
41
+ joined = " and ".join(_render(c) for c in node.children)
42
+ return joined if top else f"({joined})"
43
+ if isinstance(node, Or):
44
+ joined = " or ".join(_render(c) for c in node.children)
45
+ return joined if top else f"({joined})"
46
+ if isinstance(node, Not):
47
+ return f"not ({_render(node.child, top=True)})"
48
+ raise TypeError(f"Unknown node type: {type(node)!r}")
49
+
50
+
51
+ class CrowdStrikeBackend(Backend):
52
+ name = "crowdstrike"
53
+
54
+ def render(self, rule: "SigmaRule") -> str:
55
+ return _render(rule.ast, top=True)
@@ -0,0 +1,49 @@
1
+ """Elasticsearch Query DSL backend (emits real bool-query JSON)."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from typing import TYPE_CHECKING, Any, Dict
6
+
7
+ from ..ast_nodes import And, FieldMatch, Node, Not, Or
8
+ from .base import Backend
9
+
10
+ if TYPE_CHECKING:
11
+ from ..rule import SigmaRule
12
+
13
+
14
+ def _leaf(fm: FieldMatch) -> Dict[str, Any]:
15
+ if fm.modifier == "eq":
16
+ return {"match_phrase": {fm.field: fm.value}}
17
+ if fm.modifier == "contains":
18
+ return {"wildcard": {fm.field: f"*{fm.value}*"}}
19
+ if fm.modifier == "startswith":
20
+ return {"wildcard": {fm.field: f"{fm.value}*"}}
21
+ if fm.modifier == "endswith":
22
+ return {"wildcard": {fm.field: f"*{fm.value}"}}
23
+ if fm.modifier == "re":
24
+ return {"regexp": {fm.field: fm.value}}
25
+ raise ValueError(f"Unsupported modifier: {fm.modifier}")
26
+
27
+
28
+ def _render(node: Node) -> Dict[str, Any]:
29
+ if isinstance(node, FieldMatch):
30
+ return _leaf(node)
31
+ if isinstance(node, And):
32
+ return {"bool": {"must": [_render(c) for c in node.children]}}
33
+ if isinstance(node, Or):
34
+ return {
35
+ "bool": {
36
+ "should": [_render(c) for c in node.children],
37
+ "minimum_should_match": 1,
38
+ }
39
+ }
40
+ if isinstance(node, Not):
41
+ return {"bool": {"must_not": [_render(node.child)]}}
42
+ raise TypeError(f"Unknown node type: {type(node)!r}")
43
+
44
+
45
+ class ElasticBackend(Backend):
46
+ name = "elastic"
47
+
48
+ def render(self, rule: "SigmaRule") -> str:
49
+ return json.dumps({"query": _render(rule.ast)}, indent=2)
@@ -0,0 +1,60 @@
1
+ """IBM QRadar (Ariel Query Language / AQL) backend.
2
+
3
+ AQL is SQL-flavored: a `SELECT ... FROM events WHERE ...` statement rather
4
+ than a bare boolean expression. Field names are emitted as the raw Sigma
5
+ field names -- mapping those onto QRadar's actual AQL property names (or a
6
+ custom QID map) is deployment-specific and out of scope here, same as the
7
+ Sentinel backend's logsource-to-table mapping. Time-window filtering
8
+ (`LAST <n> <unit>`) is likewise left for the caller to add; Sigma's
9
+ `condition` block doesn't carry a timeframe for the non-aggregate rules this
10
+ project supports.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ..ast_nodes import And, FieldMatch, Node, Not, Or
17
+ from .base import Backend
18
+
19
+ if TYPE_CHECKING:
20
+ from ..rule import SigmaRule
21
+
22
+
23
+ def _quote(value: str) -> str:
24
+ return "'" + value.replace("'", "''") + "'"
25
+
26
+
27
+ def _match(fm: FieldMatch) -> str:
28
+ if fm.modifier == "eq":
29
+ return f"{fm.field} = {_quote(fm.value)}"
30
+ if fm.modifier == "contains":
31
+ return f"{fm.field} LIKE {_quote(f'%{fm.value}%')}"
32
+ if fm.modifier == "startswith":
33
+ return f"{fm.field} LIKE {_quote(f'{fm.value}%')}"
34
+ if fm.modifier == "endswith":
35
+ return f"{fm.field} LIKE {_quote(f'%{fm.value}')}"
36
+ if fm.modifier == "re":
37
+ return f"{fm.field} IMATCHES {_quote(fm.value)}"
38
+ raise ValueError(f"Unsupported modifier: {fm.modifier}")
39
+
40
+
41
+ def _render(node: Node, top: bool = False) -> str:
42
+ if isinstance(node, FieldMatch):
43
+ return _match(node)
44
+ if isinstance(node, And):
45
+ joined = " AND ".join(_render(c) for c in node.children)
46
+ return joined if top else f"({joined})"
47
+ if isinstance(node, Or):
48
+ joined = " OR ".join(_render(c) for c in node.children)
49
+ return joined if top else f"({joined})"
50
+ if isinstance(node, Not):
51
+ return f"NOT ({_render(node.child, top=True)})"
52
+ raise TypeError(f"Unknown node type: {type(node)!r}")
53
+
54
+
55
+ class QRadarBackend(Backend):
56
+ name = "qradar"
57
+
58
+ def render(self, rule: "SigmaRule") -> str:
59
+ condition = _render(rule.ast, top=True)
60
+ return f"SELECT UTF8(payload) AS payload FROM events WHERE {condition}"
@@ -0,0 +1,75 @@
1
+ """Microsoft Sentinel (Kusto / KQL) backend."""
2
+ from __future__ import annotations
3
+
4
+ from typing import TYPE_CHECKING, Dict, Optional, Tuple
5
+
6
+ from ..ast_nodes import And, FieldMatch, Node, Not, Or
7
+ from .base import Backend
8
+
9
+ if TYPE_CHECKING:
10
+ from ..rule import SigmaRule
11
+
12
+ # Best-effort logsource -> Sentinel/Defender table mapping. Covers the most
13
+ # common Sigma logsource categories/products out of the box; override per
14
+ # your own table layout for anything more specific.
15
+ _TABLE_MAP: Dict[Tuple[Optional[str], Optional[str]], str] = {
16
+ ("process_creation", None): "DeviceProcessEvents",
17
+ ("network_connection", None): "DeviceNetworkEvents",
18
+ ("file_event", None): "DeviceFileEvents",
19
+ ("registry_event", None): "DeviceRegistryEvents",
20
+ (None, "windows"): "SecurityEvent",
21
+ (None, "azure"): "AzureActivity",
22
+ (None, "aws"): "AWSCloudTrail",
23
+ }
24
+ _DEFAULT_TABLE = "SecurityEvent"
25
+
26
+
27
+ def _table_for(logsource: Dict[str, str]) -> str:
28
+ category = logsource.get("category")
29
+ product = logsource.get("product")
30
+ return (
31
+ _TABLE_MAP.get((category, None))
32
+ or _TABLE_MAP.get((None, product))
33
+ or _DEFAULT_TABLE
34
+ )
35
+
36
+
37
+ def _quote(value: str) -> str:
38
+ return value.replace('"', '\\"')
39
+
40
+
41
+ def _match(fm: FieldMatch) -> str:
42
+ v = _quote(fm.value)
43
+ if fm.modifier == "eq":
44
+ return f'{fm.field} == "{v}"'
45
+ if fm.modifier == "contains":
46
+ return f'{fm.field} has "{v}"'
47
+ if fm.modifier == "startswith":
48
+ return f'{fm.field} startswith "{v}"'
49
+ if fm.modifier == "endswith":
50
+ return f'{fm.field} endswith "{v}"'
51
+ if fm.modifier == "re":
52
+ return f'{fm.field} matches regex "{v}"'
53
+ raise ValueError(f"Unsupported modifier: {fm.modifier}")
54
+
55
+
56
+ def _render(node: Node, top: bool = False) -> str:
57
+ if isinstance(node, FieldMatch):
58
+ return _match(node)
59
+ if isinstance(node, And):
60
+ joined = " and ".join(_render(c) for c in node.children)
61
+ return joined if top else f"({joined})"
62
+ if isinstance(node, Or):
63
+ joined = " or ".join(_render(c) for c in node.children)
64
+ return joined if top else f"({joined})"
65
+ if isinstance(node, Not):
66
+ return f"not ({_render(node.child, top=True)})"
67
+ raise TypeError(f"Unknown node type: {type(node)!r}")
68
+
69
+
70
+ class SentinelBackend(Backend):
71
+ name = "sentinel"
72
+
73
+ def render(self, rule: "SigmaRule") -> str:
74
+ table = _table_for(rule.logsource)
75
+ return f"{table}\n| where {_render(rule.ast, top=True)}"
@@ -0,0 +1,52 @@
1
+ """Splunk SPL backend."""
2
+ from __future__ import annotations
3
+
4
+ from typing import TYPE_CHECKING
5
+
6
+ from ..ast_nodes import And, FieldMatch, Node, Not, Or
7
+ from .base import Backend
8
+
9
+ if TYPE_CHECKING:
10
+ from ..rule import SigmaRule
11
+
12
+
13
+ def _quote(value: str) -> str:
14
+ return f'"{value}"' if (" " in value or value == "") else value
15
+
16
+
17
+ def _match(fm: FieldMatch) -> str:
18
+ if fm.modifier == "eq":
19
+ return f"{fm.field}={_quote(fm.value)}"
20
+ if fm.modifier == "contains":
21
+ return f"{fm.field}=*{fm.value}*"
22
+ if fm.modifier == "startswith":
23
+ return f"{fm.field}={fm.value}*"
24
+ if fm.modifier == "endswith":
25
+ return f"{fm.field}=*{fm.value}"
26
+ if fm.modifier == "re":
27
+ # SPL has no inline regex match operator -- `regex` is a separate
28
+ # pipe stage. Emit the literal and flag it so the limitation is
29
+ # obvious in the output rather than silently wrong.
30
+ return f'{fm.field}="{fm.value}" /* regex: pipe through `| regex {fm.field}="{fm.value}"` */'
31
+ raise ValueError(f"Unsupported modifier: {fm.modifier}")
32
+
33
+
34
+ def _render(node: Node, top: bool = False) -> str:
35
+ if isinstance(node, FieldMatch):
36
+ return _match(node)
37
+ if isinstance(node, And):
38
+ joined = " AND ".join(_render(c) for c in node.children)
39
+ return joined if top else f"({joined})"
40
+ if isinstance(node, Or):
41
+ joined = " OR ".join(_render(c) for c in node.children)
42
+ return joined if top else f"({joined})"
43
+ if isinstance(node, Not):
44
+ return f"NOT {_render(node.child)}"
45
+ raise TypeError(f"Unknown node type: {type(node)!r}")
46
+
47
+
48
+ class SplunkBackend(Backend):
49
+ name = "splunk"
50
+
51
+ def render(self, rule: "SigmaRule") -> str:
52
+ return _render(rule.ast, top=True)
@@ -0,0 +1,57 @@
1
+ """Sumo Logic search query backend.
2
+
3
+ Sumo Logic's search syntax is deliberately close to Splunk's SPL for field
4
+ filtering: bare `field=value` terms with native wildcard support, joined
5
+ with uppercase `AND`/`OR`/`NOT`. It has no inline regex match operator
6
+ either -- regex filtering needs a `| where field matches /pattern/` pipe
7
+ stage, so (like the Splunk backend's `re` handling) that case emits a
8
+ flagged placeholder rather than silently wrong syntax.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ from typing import TYPE_CHECKING
13
+
14
+ from ..ast_nodes import And, FieldMatch, Node, Not, Or
15
+ from .base import Backend
16
+
17
+ if TYPE_CHECKING:
18
+ from ..rule import SigmaRule
19
+
20
+
21
+ def _quote(value: str) -> str:
22
+ return f'"{value}"' if (" " in value or value == "") else value
23
+
24
+
25
+ def _match(fm: FieldMatch) -> str:
26
+ if fm.modifier == "eq":
27
+ return f"{fm.field}={_quote(fm.value)}"
28
+ if fm.modifier == "contains":
29
+ return f"{fm.field}=*{fm.value}*"
30
+ if fm.modifier == "startswith":
31
+ return f"{fm.field}={fm.value}*"
32
+ if fm.modifier == "endswith":
33
+ return f"{fm.field}=*{fm.value}"
34
+ if fm.modifier == "re":
35
+ return f'{fm.field}="{fm.value}" /* regex: pipe through `| where {fm.field} matches /{fm.value}/` */'
36
+ raise ValueError(f"Unsupported modifier: {fm.modifier}")
37
+
38
+
39
+ def _render(node: Node, top: bool = False) -> str:
40
+ if isinstance(node, FieldMatch):
41
+ return _match(node)
42
+ if isinstance(node, And):
43
+ joined = " AND ".join(_render(c) for c in node.children)
44
+ return joined if top else f"({joined})"
45
+ if isinstance(node, Or):
46
+ joined = " OR ".join(_render(c) for c in node.children)
47
+ return joined if top else f"({joined})"
48
+ if isinstance(node, Not):
49
+ return f"NOT {_render(node.child)}"
50
+ raise TypeError(f"Unknown node type: {type(node)!r}")
51
+
52
+
53
+ class SumoLogicBackend(Backend):
54
+ name = "sumologic"
55
+
56
+ def render(self, rule: "SigmaRule") -> str:
57
+ return _render(rule.ast, top=True)
sigmux/cli.py ADDED
@@ -0,0 +1,157 @@
1
+ """Command-line interface for sigmux."""
2
+ from __future__ import annotations
3
+
4
+ import sys
5
+ from pathlib import Path
6
+ from typing import Optional, Tuple
7
+
8
+ import click
9
+ from rich.console import Console
10
+ from rich.panel import Panel
11
+ from rich.syntax import Syntax
12
+ from rich.table import Table
13
+
14
+ from .backends import REGISTRY, get_backend
15
+ from .rule import SigmaRule
16
+
17
+ console = Console()
18
+ err_console = Console(stderr=True)
19
+
20
+ # Display metadata for the CLI only -- purely cosmetic. A new backend works
21
+ # fully (conversion, file output, `targets` listing) with zero entries here;
22
+ # omitting one just falls back to a plain label/extension/color, so adding a
23
+ # SIEM target still only means writing one new backends/*.py file.
24
+ _TARGET_INFO = {
25
+ "splunk": {"label": "Splunk SPL", "ext": "spl", "color": "orange3", "lexer": "text"},
26
+ "elastic": {"label": "Elasticsearch Query DSL", "ext": "json", "color": "gold3", "lexer": "json"},
27
+ "sentinel": {"label": "Microsoft Sentinel (KQL)", "ext": "kql", "color": "deep_sky_blue1", "lexer": "kql"},
28
+ "crowdstrike": {"label": "CrowdStrike Falcon LogScale (LQL)", "ext": "lql", "color": "magenta1", "lexer": "text"},
29
+ "qradar": {"label": "IBM QRadar (AQL)", "ext": "aql", "color": "green3", "lexer": "sql"},
30
+ "chronicle": {"label": "Google Chronicle (YARA-L 2.0)", "ext": "yaral", "color": "cyan1", "lexer": "yara"},
31
+ "sumologic": {"label": "Sumo Logic search query", "ext": "sumo", "color": "red3", "lexer": "text"},
32
+ }
33
+
34
+
35
+ def _info_for(target_name: str) -> dict:
36
+ info = _TARGET_INFO.get(target_name, {})
37
+ return {
38
+ "label": info.get("label", target_name.title()),
39
+ "ext": info.get("ext", "txt"),
40
+ "color": info.get("color", "white"),
41
+ "lexer": info.get("lexer", "text"),
42
+ }
43
+
44
+
45
+ def _syntax_for(code: str, target_name: str) -> Syntax:
46
+ lexer = _info_for(target_name)["lexer"]
47
+ try:
48
+ return Syntax(code, lexer, theme="ansi_dark", word_wrap=True, background_color="default")
49
+ except Exception: # noqa: BLE001 - any lexer/theme hiccup, just fall back
50
+ return Syntax(code, "text", theme="ansi_dark", word_wrap=True, background_color="default")
51
+
52
+
53
+ def _load_rule(path: Path) -> SigmaRule:
54
+ return SigmaRule.from_yaml(path.read_text(encoding="utf-8"))
55
+
56
+
57
+ def _iter_rule_files(path: Path):
58
+ if path.is_dir():
59
+ files = sorted(path.rglob("*.yml")) + sorted(path.rglob("*.yaml"))
60
+ yield from files
61
+ else:
62
+ yield path
63
+
64
+
65
+ @click.group()
66
+ @click.version_option(package_name="sigmux")
67
+ def main():
68
+ """sigmux -- convert Sigma detection rules into multiple SIEM query languages."""
69
+
70
+
71
+ @main.command()
72
+ def targets():
73
+ """List supported conversion targets."""
74
+ table = Table(title="sigmux conversion targets", header_style="bold")
75
+ table.add_column("Target", style="bold")
76
+ table.add_column("Query language")
77
+ table.add_column("Output ext", justify="center")
78
+
79
+ for name in sorted(REGISTRY):
80
+ info = _info_for(name)
81
+ table.add_row(f"[{info['color']}]{name}[/{info['color']}]", info["label"], f".{info['ext']}")
82
+
83
+ console.print(table)
84
+
85
+
86
+ @main.command()
87
+ @click.argument("path", type=click.Path(exists=True, path_type=Path))
88
+ @click.option(
89
+ "--target",
90
+ "-t",
91
+ "target_names",
92
+ multiple=True,
93
+ default=tuple(sorted(REGISTRY)),
94
+ help="Target SIEM(s) to convert to. Repeatable. Defaults to all targets.",
95
+ )
96
+ @click.option(
97
+ "--out",
98
+ "-o",
99
+ "out_dir",
100
+ type=click.Path(path_type=Path),
101
+ default=None,
102
+ help="Write each conversion to <out>/<rule>.<target>.<ext> instead of stdout "
103
+ "(.spl, .json, .kql, .lql, .aql, .yaral, .sumo depending on target).",
104
+ )
105
+ def convert(path: Path, target_names: Tuple[str, ...], out_dir: Optional[Path]):
106
+ """Convert one Sigma rule file, or every rule in a directory, into one
107
+ or more SIEM query languages."""
108
+ backends = [get_backend(name) for name in target_names]
109
+ if out_dir:
110
+ out_dir.mkdir(parents=True, exist_ok=True)
111
+
112
+ exit_code = 0
113
+ rule_count = 0
114
+ ok_count = 0
115
+ error_count = 0
116
+
117
+ for rule_path in _iter_rule_files(path):
118
+ try:
119
+ rule = _load_rule(rule_path)
120
+ except Exception as exc: # noqa: BLE001 - surfaced directly to the user
121
+ err_console.print(f"[bold yellow]⚠ skip[/bold yellow] {rule_path}: {exc}")
122
+ exit_code = 1
123
+ error_count += 1
124
+ continue
125
+
126
+ rule_count += 1
127
+ for backend in backends:
128
+ info = _info_for(backend.name)
129
+ try:
130
+ rendered = backend.render(rule)
131
+ except Exception as exc: # noqa: BLE001
132
+ err_console.print(
133
+ f"[bold red]✗ error[/bold red] {rule_path} -> {backend.name}: {exc}"
134
+ )
135
+ exit_code = 1
136
+ error_count += 1
137
+ continue
138
+
139
+ ok_count += 1
140
+ if out_dir:
141
+ out_path = out_dir / f"{rule_path.stem}.{backend.name}.{info['ext']}"
142
+ out_path.write_text(rendered + "\n", encoding="utf-8")
143
+ console.print(f"[green]✓[/green] wrote [bold]{out_path}[/bold]")
144
+ else:
145
+ title = f"[bold]{rule.title}[/bold] :: [{info['color']}]{backend.name}[/{info['color']}] ({info['label']})"
146
+ console.print(Panel(_syntax_for(rendered, backend.name), title=title, title_align="left", border_style=info["color"]))
147
+
148
+ summary_style = "bold green" if error_count == 0 else "bold yellow"
149
+ console.print(
150
+ f"[{summary_style}]{ok_count} conversion(s) across {rule_count} rule(s), "
151
+ f"{error_count} error(s)[/{summary_style}]"
152
+ )
153
+ sys.exit(exit_code)
154
+
155
+
156
+ if __name__ == "__main__":
157
+ main()
@@ -0,0 +1,110 @@
1
+ """Parser for Sigma's boolean `condition` mini-language.
2
+
3
+ Supports identifiers, `and` / `or` / `not`, parentheses, and the aggregate
4
+ forms `1 of <glob>`, `all of <glob>`, `1 of them`, and `all of them`.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import fnmatch
9
+ import re as _re
10
+ from typing import Dict, List
11
+
12
+ from .ast_nodes import And, Node, Or
13
+
14
+ _TOKEN_RE = _re.compile(r"\(|\)|[A-Za-z0-9_][A-Za-z0-9_*]*")
15
+
16
+
17
+ def _tokenize(text: str) -> List[str]:
18
+ return _TOKEN_RE.findall(text)
19
+
20
+
21
+ class _Parser:
22
+ def __init__(self, tokens: List[str], selections: Dict[str, Node]):
23
+ self.tokens = tokens
24
+ self.pos = 0
25
+ self.selections = selections
26
+
27
+ def peek(self):
28
+ return self.tokens[self.pos] if self.pos < len(self.tokens) else None
29
+
30
+ def advance(self):
31
+ tok = self.peek()
32
+ self.pos += 1
33
+ return tok
34
+
35
+ def expect(self, tok):
36
+ actual = self.advance()
37
+ if actual != tok:
38
+ raise ValueError(f"Expected '{tok}' but found '{actual}' in condition")
39
+ return actual
40
+
41
+ def parse(self) -> Node:
42
+ node = self.parse_or()
43
+ if self.pos != len(self.tokens):
44
+ raise ValueError(f"Unexpected trailing tokens: {self.tokens[self.pos:]}")
45
+ return node
46
+
47
+ def parse_or(self) -> Node:
48
+ children = [self.parse_and()]
49
+ while self.peek() == "or":
50
+ self.advance()
51
+ children.append(self.parse_and())
52
+ return children[0] if len(children) == 1 else Or(children)
53
+
54
+ def parse_and(self) -> Node:
55
+ children = [self.parse_not()]
56
+ while self.peek() == "and":
57
+ self.advance()
58
+ children.append(self.parse_not())
59
+ return children[0] if len(children) == 1 else And(children)
60
+
61
+ def parse_not(self) -> Node:
62
+ if self.peek() == "not":
63
+ self.advance()
64
+ from .ast_nodes import Not
65
+
66
+ return Not(self.parse_not())
67
+ return self.parse_atom()
68
+
69
+ def parse_atom(self) -> Node:
70
+ tok = self.peek()
71
+ if tok == "(":
72
+ self.advance()
73
+ node = self.parse_or()
74
+ self.expect(")")
75
+ return node
76
+ if tok in ("1", "all"):
77
+ return self.parse_aggregate()
78
+ if tok is None:
79
+ raise ValueError("Unexpected end of condition")
80
+ self.advance()
81
+ return self._resolve(tok)
82
+
83
+ def parse_aggregate(self) -> Node:
84
+ quantifier = self.advance() # "1" or "all"
85
+ self.expect("of")
86
+ pattern = self.advance()
87
+ if pattern is None:
88
+ raise ValueError("Expected a selection name or glob after 'of'")
89
+ if pattern == "them":
90
+ names = list(self.selections.keys())
91
+ else:
92
+ names = [n for n in self.selections if fnmatch.fnmatch(n, pattern)]
93
+ if not names:
94
+ raise ValueError(f"No selections match pattern '{pattern}'")
95
+ nodes = [self.selections[n] for n in names]
96
+ if len(nodes) == 1:
97
+ return nodes[0]
98
+ return And(nodes) if quantifier == "all" else Or(nodes)
99
+
100
+ def _resolve(self, name: str) -> Node:
101
+ if name not in self.selections:
102
+ raise ValueError(f"Condition references unknown selection '{name}'")
103
+ return self.selections[name]
104
+
105
+
106
+ def parse_condition(text: str, selections: Dict[str, Node]) -> Node:
107
+ tokens = _tokenize(text)
108
+ if not tokens:
109
+ raise ValueError("Empty condition")
110
+ return _Parser(tokens, selections).parse()
sigmux/rule.py ADDED
@@ -0,0 +1,127 @@
1
+ """Parsing a Sigma rule's YAML into a small AST."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass, field
5
+ from typing import Any, Dict, List, Optional
6
+
7
+ import yaml
8
+
9
+ from .ast_nodes import And, FieldMatch, Node, Or
10
+ from .condition_parser import parse_condition
11
+
12
+
13
+ def _parse_field_key(key: str):
14
+ """Split 'CommandLine|contains|all' into (field, modifier, require_all)."""
15
+ parts = key.split("|")
16
+ field_name = parts[0]
17
+ mods = parts[1:]
18
+ modifier = "eq"
19
+ require_all = False
20
+ for m in mods:
21
+ if m in ("contains", "startswith", "endswith", "re"):
22
+ modifier = m
23
+ elif m == "all":
24
+ require_all = True
25
+ # Unsupported modifiers (base64, cidr, ...) fall back to 'eq' rather
26
+ # than raising, so a rule using them still converts -- just not
27
+ # perfectly. See README "Known limitations".
28
+ return field_name, modifier, require_all
29
+
30
+
31
+ def _infer_modifier(modifier: str, value: str):
32
+ """Upgrade a bare wildcard value (e.g. '*evil*') to contains/startswith/endswith."""
33
+ if modifier != "eq":
34
+ return modifier, value
35
+ starts = value.startswith("*")
36
+ ends = value.endswith("*") and len(value) > 1
37
+ if starts and ends and len(value) > 1:
38
+ return "contains", value[1:-1]
39
+ if ends and not starts:
40
+ return "startswith", value[:-1]
41
+ if starts and not ends:
42
+ return "endswith", value[1:]
43
+ return "eq", value
44
+
45
+
46
+ def _field_terms(key: str, raw_value: Any) -> Node:
47
+ field_name, modifier, require_all = _parse_field_key(key)
48
+ values = raw_value if isinstance(raw_value, list) else [raw_value]
49
+ matches: List[Node] = []
50
+ for v in values:
51
+ mod, val = _infer_modifier(modifier, str(v))
52
+ matches.append(FieldMatch(field_name, mod, val))
53
+ if len(matches) == 1:
54
+ return matches[0]
55
+ return And(matches) if require_all else Or(matches)
56
+
57
+
58
+ def parse_selection(value: Any) -> Node:
59
+ """Turn one 'detection' map entry into an AST node.
60
+
61
+ A selection is either a field->value(s) map (fields are ANDed, list
62
+ values are ORed unless the '|all' modifier is present), or a list of
63
+ such maps (ORed together), or a bare list of keyword strings (Sigma's
64
+ free-text 'keywords' detection style).
65
+ """
66
+ if isinstance(value, dict):
67
+ terms = [_field_terms(k, v) for k, v in value.items()]
68
+ return terms[0] if len(terms) == 1 else And(terms)
69
+ if isinstance(value, list):
70
+ if all(isinstance(item, dict) for item in value):
71
+ branches = [parse_selection(item) for item in value]
72
+ return branches[0] if len(branches) == 1 else Or(branches)
73
+ matches = [FieldMatch("_raw", "contains", str(item)) for item in value]
74
+ return matches[0] if len(matches) == 1 else Or(matches)
75
+ raise ValueError(f"Unsupported selection shape: {value!r}")
76
+
77
+
78
+ @dataclass
79
+ class SigmaRule:
80
+ title: str
81
+ id: Optional[str]
82
+ status: Optional[str]
83
+ description: Optional[str]
84
+ level: Optional[str]
85
+ logsource: Dict[str, str]
86
+ selections: Dict[str, Node]
87
+ condition_text: str
88
+ ast: Node
89
+ tags: List[str] = field(default_factory=list)
90
+ raw: Dict[str, Any] = field(default_factory=dict)
91
+
92
+ @classmethod
93
+ def from_yaml(cls, text: str) -> "SigmaRule":
94
+ data = yaml.safe_load(text)
95
+ if not isinstance(data, dict):
96
+ raise ValueError("Sigma rule YAML must be a mapping at the top level")
97
+ return cls.from_dict(data)
98
+
99
+ @classmethod
100
+ def from_dict(cls, data: Dict[str, Any]) -> "SigmaRule":
101
+ detection = data.get("detection")
102
+ if not isinstance(detection, dict):
103
+ raise ValueError("Sigma rule is missing a 'detection' block")
104
+ condition_text = detection.get("condition")
105
+ if not condition_text:
106
+ raise ValueError("Sigma rule is missing 'detection.condition'")
107
+
108
+ selections = {
109
+ name: parse_selection(value)
110
+ for name, value in detection.items()
111
+ if name != "condition"
112
+ }
113
+ ast = parse_condition(condition_text, selections)
114
+
115
+ return cls(
116
+ title=data.get("title", "Untitled rule"),
117
+ id=data.get("id"),
118
+ status=data.get("status"),
119
+ description=data.get("description"),
120
+ level=data.get("level"),
121
+ logsource=data.get("logsource") or {},
122
+ selections=selections,
123
+ condition_text=condition_text,
124
+ ast=ast,
125
+ tags=data.get("tags") or [],
126
+ raw=data,
127
+ )
@@ -0,0 +1,181 @@
1
+ Metadata-Version: 2.4
2
+ Name: sigmux
3
+ Version: 0.3.0
4
+ Summary: Convert Sigma detection rules into multiple SIEM query languages (Splunk SPL, Elasticsearch Query DSL, Microsoft Sentinel KQL, CrowdStrike Falcon LogScale, IBM QRadar AQL, Google Chronicle YARA-L, Sumo Logic).
5
+ Author: Kyle Main
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/kylemain/sigmux
8
+ Project-URL: Repository, https://github.com/kylemain/sigmux
9
+ Project-URL: Issues, https://github.com/kylemain/sigmux/issues
10
+ Keywords: sigma,siem,detection-engineering,splunk,elasticsearch,sentinel,kql,crowdstrike,logscale,qradar,chronicle,yara-l,sumologic,security,detectl
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Information Technology
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Security
21
+ Requires-Python: >=3.9
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: PyYAML>=6.0
25
+ Requires-Dist: click>=8.0
26
+ Requires-Dist: rich>=13.0
27
+ Requires-Dist: Pygments>=2.16
28
+ Dynamic: license-file
29
+
30
+ # sigmux
31
+
32
+ [![CI](https://github.com/kylemain/sigmux/actions/workflows/ci.yml/badge.svg)](https://github.com/kylemain/sigmux/actions/workflows/ci.yml)
33
+ [![coverage](coverage.svg)](#testing)
34
+
35
+ Convert [Sigma](https://github.com/SigmaHQ/sigma) detection rules into **seven** SIEM/XDR query languages from a single command: **Splunk SPL**, **Elasticsearch Query DSL**, **Microsoft Sentinel (KQL)**, **CrowdStrike Falcon LogScale (LQL)**, **IBM QRadar (AQL)**, **Google Chronicle (YARA-L 2.0)**, and **Sumo Logic**.
36
+
37
+ This mirrors real multi-SIEM detection engineering work -- writing detection logic once and deploying it consistently across platforms instead of hand-porting query syntax every time a team adds a new SIEM. It pairs directly with [detectl](https://github.com/kylemain/detectl), which takes sigmux's output the rest of the way and actually pushes it to a live platform -- see [Pairs well with detectl](#pairs-well-with-detectl) below.
38
+
39
+ ![sigmux and detectl demo](demo.gif)
40
+
41
+ ```
42
+ $ sigmux convert examples/mimikatz_execution.yml --target splunk --target sentinel --target elastic
43
+
44
+ ╭─ Mimikatz Process Execution :: splunk (Splunk SPL) ──────────────────────────╮
45
+ │ Image=*\mimikatz.exe OR (CommandLine=*sekurlsa::* OR CommandLine=*lsadump::* │
46
+ │ OR CommandLine=*privilege::debug*) │
47
+ ╰──────────────────────────────────────────────────────────────────────────────╯
48
+ ╭─ Mimikatz Process Execution :: sentinel (Microsoft Sentinel (KQL)) ──────────╮
49
+ │ DeviceProcessEvents │
50
+ │ | where Image endswith "\mimikatz.exe" or (CommandLine has "sekurlsa::" or │
51
+ │ CommandLine has "lsadump::" or CommandLine has "privilege::debug") │
52
+ ╰──────────────────────────────────────────────────────────────────────────────╯
53
+ ╭─ Mimikatz Process Execution :: elastic (Elasticsearch Query DSL) ────────────╮
54
+ │ { "query": { "bool": { "should": [ ... ], "minimum_should_match": 1 } } } │
55
+ ╰──────────────────────────────────────────────────────────────────────────────╯
56
+ 3 conversion(s) across 1 rule(s), 0 error(s)
57
+ ```
58
+
59
+ Each target gets its own colored, syntax-highlighted panel in the terminal (JSON, SQL, and YARA-L output get real Pygments highlighting via [rich](https://github.com/Textualize/rich)); `sigmux targets` prints a table of every supported target, its query language, and its output file extension.
60
+
61
+ ## Why
62
+
63
+ Detection engineering across more than one SIEM/EDR platform means writing (and maintaining) the same detection logic in several different query languages. Sigma exists to describe detection logic once, vendor-neutrally — `sigmux` is a small, from-scratch implementation of the parts of the Sigma spec that come up constantly in real rules (field matching with `contains`/`startswith`/`endswith`/wildcards, `and`/`or`/`not`, and the `1 of x*` / `all of them` aggregate forms), plus renderers that turn that into query text you can actually paste into your platform of choice.
64
+
65
+ It's a generalized, from-scratch build — not a wrapper around an existing rule-conversion library — written to be small enough to read end to end in one sitting.
66
+
67
+ ## Install
68
+
69
+ Not published to PyPI yet -- `pyproject.toml` and `.github/workflows/publish.yml` are set up for it (PyPI Trusted Publishing, triggered on a version tag), but that needs a one-time manual step on pypi.org's side first. Until then, install from source:
70
+
71
+ ```bash
72
+ git clone https://github.com/kylemain/sigmux
73
+ cd sigmux
74
+ python3 -m venv .venv
75
+ source .venv/bin/activate
76
+ pip install -e .
77
+ ```
78
+
79
+ ## Usage
80
+
81
+ ```bash
82
+ # Convert a single rule to every supported target
83
+ sigmux convert examples/mimikatz_execution.yml
84
+
85
+ # Convert to specific target(s) only
86
+ sigmux convert examples/mimikatz_execution.yml --target splunk --target crowdstrike
87
+
88
+ # Convert every rule in a directory, writing output files instead of stdout
89
+ sigmux convert examples/ --target elastic --out out/
90
+
91
+ # List supported targets, their query language, and output extension
92
+ sigmux targets
93
+ ```
94
+
95
+ ```
96
+ sigmux conversion targets
97
+ ┏━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━┓
98
+ ┃ Target ┃ Query language ┃ Output ext ┃
99
+ ┡━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━┩
100
+ │ chronicle │ Google Chronicle (YARA-L 2.0) │ .yaral │
101
+ │ crowdstrike │ CrowdStrike Falcon LogScale (LQL) │ .lql │
102
+ │ elastic │ Elasticsearch Query DSL │ .json │
103
+ │ qradar │ IBM QRadar (AQL) │ .aql │
104
+ │ sentinel │ Microsoft Sentinel (KQL) │ .kql │
105
+ │ splunk │ Splunk SPL │ .spl │
106
+ │ sumologic │ Sumo Logic search query │ .sumo │
107
+ └─────────────┴───────────────────────────────────┴────────────┘
108
+ ```
109
+
110
+ ## Pairs well with [detectl](https://github.com/kylemain/detectl)
111
+
112
+ sigmux's target names match detectl's platform names 1:1 on purpose (`elastic`, `crowdstrike`, `sentinel`, `splunk`, `qradar`, `sumologic`, `chronicle`) -- the conversion target and the platform you push it to are never something you have to look up a mapping for.
113
+
114
+ detectl imports sigmux as a library to collapse the two-step "convert, then paste the output into a create command" workflow into one:
115
+
116
+ ```bash
117
+ detectl -p elastic rules create-from-sigma my_rule.yml
118
+ ```
119
+
120
+ That single command parses the Sigma rule, converts it with sigmux using the exact target that matches `--platform`, and creates it as a live detection rule -- with a `--dry-run` flag that shows the full converted query and rule metadata (Terraform-plan style) before anything is actually created. This isn't just a documented pairing either: a separate `integration` CI job in detectl spins up a real Elasticsearch and runs this exact pipeline against it end to end (see detectl's `scripts/integration_test_elastic.py`), so the two projects staying compatible is something CI actually checks, not just a README claim.
121
+
122
+ ## Architecture
123
+
124
+ ```
125
+ Sigma YAML → rule.py (parse) → tiny AST → backend.render(rule) → query text
126
+ (ast_nodes.py) (backends/*.py)
127
+ ```
128
+
129
+ - **`rule.py`** parses a rule's `detection` block into per-selection AST nodes (field matches, ANDed within a selection, ORed across list values), then **`condition_parser.py`** parses the `condition:` string (`and`/`or`/`not`, parentheses, `1 of sel_*`, `all of them`, ...) into a single tree referencing those selections.
130
+ - **`ast_nodes.py`** defines the whole tree with four node types: `FieldMatch`, `And`, `Or`, `Not`.
131
+ - **`backends/`** each implement one `render(rule) -> str` method that walks the same AST and emits target-specific syntax. Adding a new SIEM target means writing one new backend file and registering it in `backends/__init__.py`'s `REGISTRY` — nothing else in the conversion pipeline changes:
132
+
133
+ ```python
134
+ class MyBackend(Backend):
135
+ name = "my_siem"
136
+
137
+ def render(self, rule: SigmaRule) -> str:
138
+ return _render(rule.ast, top=True)
139
+ ```
140
+
141
+ The CLI's `_TARGET_INFO` dict in `cli.py` adds a display label/color/syntax-highlighting lexer per target for `targets` and `convert`'s panels, but it's cosmetic only — a target missing from it still converts and writes files correctly with a plain fallback label/extension.
142
+ - **`cli.py`** wires it all together with [Click](https://click.palletsprojects.com/) for argument parsing and [rich](https://github.com/Textualize/rich) for colored tables, bordered per-target panels, and Pygments-backed syntax highlighting of the rendered query text.
143
+
144
+ ## Known limitations
145
+
146
+ This is a deliberately-scoped implementation of Sigma's *field matching and boolean logic*, not the full spec:
147
+
148
+ - Supported field modifiers: exact match (with automatic wildcard inference), `contains`, `startswith`, `endswith`, `re`. `base64`, `base64offset`, `cidr`, and field-to-field comparisons aren't supported -- rather than rejecting the whole rule, an unsupported modifier degrades to a plain exact-match on the raw field value, so the rule still converts (just not perfectly; don't rely on it decoding base64 or matching a CIDR range for you).
149
+ - Supported condition forms: `and` / `or` / `not`, parentheses, `1 of <glob>`, `all of <glob>`, `1 of them`, `all of them`. Not supported: aggregation/timeframe rules (`count() by ... > N`) and the newer multi-rule `correlation:` type.
150
+ - The Sentinel backend's logsource → table mapping, and the Chronicle backend's logsource → UDM `event_type` mapping, cover the common Sigma categories/products out of the box; anything more specific should be overridden per deployment.
151
+ - The `re` modifier's Splunk and Sumo Logic rendering is a best-effort placeholder — neither SPL nor Sumo's search syntax has an inline regex match operator, so the emitted term is flagged with a comment showing the equivalent pipe stage (`| regex` / `| where ... matches`).
152
+ - The QRadar backend emits raw Sigma field names, not real AQL property names or a QID map, and doesn't add a `LAST <n> <unit>` time-window clause — both are deployment-specific.
153
+ - The Chronicle backend emits raw Sigma field names under the event variable (`$e.Image`) rather than mapping them onto Chronicle's UDM schema (`$e.target.process.file.full_path`, ...) — that mapping is log-source-specific and out of scope here.
154
+
155
+ ## SigmaHQ compatibility
156
+
157
+ The 9 example rules in this repo prove the mechanics work; they don't prove much about coverage. `scripts/benchmark_sigmahq.py` runs every rule in the real, actively-maintained [SigmaHQ/sigma](https://github.com/SigmaHQ/sigma) `rules/` corpus (rules this project doesn't own or control) through every sigmux backend and reports how many convert cleanly:
158
+
159
+ ```bash
160
+ python scripts/benchmark_sigmahq.py
161
+ ```
162
+
163
+ As of this writing, against the current `rules/` corpus:
164
+
165
+ ```
166
+ 3141/3141 rules converted cleanly to all 7 targets (100.0%)
167
+ ```
168
+
169
+ Read that number for what it actually measures, not more: it means every rule parsed and every backend rendered *something* without raising -- it doesn't mean every rendered query is semantically perfect. 28 of those 3,141 rules use `base64`/`cidr` modifiers, which (per Known limitations above) sigmux intentionally degrades to a plain exact-match rather than rejecting; this snapshot of the corpus also happens to contain zero aggregation/`correlation:` rules, which remain genuinely unsupported and would fail if present. This job runs weekly in CI (informational only, not a merge gate, since it depends on an external repo's content) -- see the `sigmahq-benchmark` job in `.github/workflows/ci.yml`.
170
+
171
+ ## Testing
172
+
173
+ ```bash
174
+ python -m unittest discover -v
175
+ ```
176
+
177
+ 36 tests covering field-modifier parsing, the condition-language parser, all seven backends, and the CLI.
178
+
179
+ ## License
180
+
181
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,21 @@
1
+ sigmux/__init__.py,sha256=_oIY4BFE5JyN1JJSTEozMHZ2c4-0FHUHZga4hvNEuEM,106
2
+ sigmux/__main__.py,sha256=MSmt_5Xg84uHqzTN38JwgseJK8rsJn_11A8WD99VtEo,61
3
+ sigmux/ast_nodes.py,sha256=nfLOCJznxVlfBNWwAlgnDju-Dusho5r6DQ9-uQ6ZvLM,744
4
+ sigmux/cli.py,sha256=L69eGVok-lZ21FCArUetUp2tJDXwkBq7pjFNQo3S6S4,5692
5
+ sigmux/condition_parser.py,sha256=Y4Zw4YAegc1XJVLdVUDyOmANLXxE0R11XNfaZMNS2xg,3472
6
+ sigmux/rule.py,sha256=KNmOuc3SmuB9HNrefFDzJkQutSCIWDi75nTNYRZdTaY,4538
7
+ sigmux/backends/__init__.py,sha256=R2oc9K0Kq_lugd_bVx8qJ10lDn92BiLxDtjj9qHLqJA,1230
8
+ sigmux/backends/base.py,sha256=O_vm3IZj043W8pJPkU63szjVBT3-HWfAL0cEa14mIfA,397
9
+ sigmux/backends/chronicle.py,sha256=J2qj97R4-rdSxCdZVOPT4CtojBYtk3sx6TqnUWTU9Kg,4041
10
+ sigmux/backends/crowdstrike.py,sha256=CQScd5TYxLkkE1LvWWzTa-VoPMQnctSkSXaH9iAENWU,1836
11
+ sigmux/backends/elastic.py,sha256=0Em3Y0Evcv-MEZMX1evJEcGKNGUdr_AIWAWP26TqMSM,1559
12
+ sigmux/backends/qradar.py,sha256=mN_qbjvrjKg6jjrGeR7pLa9j6kNo_HA8rjgopWSo2yY,2188
13
+ sigmux/backends/sentinel.py,sha256=hej8vAtkFBch2rNEITXPGOTSWgPwzHR2Yr5Ri2uMlzM,2490
14
+ sigmux/backends/splunk.py,sha256=C2XUtsDJ_CO0m9VGjXEVt8TJMdUtzlFKxt5ZJzQDL1g,1746
15
+ sigmux/backends/sumologic.py,sha256=lt8rB7GAJIWCf2-EpB-CV3q0r4vnsCml2MvaV23VJr8,1986
16
+ sigmux-0.3.0.dist-info/licenses/LICENSE,sha256=kwuN56qBNKBx84Qdtg2tXhGArCQgFH-5XrwKa_o8Xh0,1066
17
+ sigmux-0.3.0.dist-info/METADATA,sha256=aenY1frklWd1mSjJ8hIme6Ubfe9BkPNSmRooxYzDur4,13156
18
+ sigmux-0.3.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
19
+ sigmux-0.3.0.dist-info/entry_points.txt,sha256=nw-4uarrpA8Xjmm3ybCx6t6OGl04BMsWs-9ngDGnWCk,43
20
+ sigmux-0.3.0.dist-info/top_level.txt,sha256=xDPYuA-FwPKc9B39d-SZlSZ0S1a-vY21Ly1iFMBb7uE,7
21
+ sigmux-0.3.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ sigmux = sigmux.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kyle Main
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ sigmux