A Small Sigma Evaluator in Python
Converters turn Sigma rules into SIEM queries, and the SIEM evaluates them. When a rule misbehaves, it helps to know exactly what the rule means, independent of any backend: which events match, and why. The best way to learn that is to evaluate Sigma's detection logic yourself. This lesson builds a small evaluator (about 50 lines) that supports the core of the specification: maps and lists, the common modifiers, and conditions with and, or, not, parentheses and 1 of / all of quantifiers. It then runs two rules on synthetic process events, which is also how detection tests work (Testing Detections).
What the evaluator must implement
From the previous lesson (Sigma Rules):
| Construct | Semantics | In the code |
|---|---|---|
map {field: value, field2: value2} |
every field must match (AND) | match_map |
| list of values for a field | any value matches (OR); with |all, every value (AND) |
match_map |
| list of maps | any map matches (OR) | match_identifier |
| plain value | case-insensitive, * and ? wildcards |
match_value with fnmatch |
|contains, |startswith, |endswith |
substring, prefix, suffix | wildcards added around the value |
|re, |cidr |
regular expression; address in a network | re.search, ipaddress |
condition |
boolean expression over identifiers, with 1 of x*, all of x*, them |
evaluate |
A missing field never matches, which matters for filters: not filter is true when the field the filter tests is absent.
The evaluator and two rules
The first rule is the Office-spawns-a-shell rule from the previous lesson, with its condition rewritten to use a quantifier. The second looks for encoded PowerShell (-enc) with -nop in any order, except when an administrator runs it interactively from Explorer.
import re, fnmatch, ipaddress, yaml
def match_value(field_value, mods, pattern):
if field_value is None:
return False
s, p = str(field_value).lower(), str(pattern).lower()
if "re" in mods:
return re.search(str(pattern), str(field_value)) is not None
if "cidr" in mods:
return ipaddress.ip_address(s) in ipaddress.ip_network(p)
if "contains" in mods:
p = f"*{p}*"
elif "startswith" in mods:
p = f"{p}*"
elif "endswith" in mods:
p = f"*{p}"
return fnmatch.fnmatchcase(s, p.replace("[", "[[]")) # Sigma wildcards: * and ?
def match_map(event, m):
for key, values in m.items(): # fields: AND
field, *mods = key.split("|")
values = values if isinstance(values, list) else [values]
hits = [match_value(event.get(field), mods, v) for v in values]
if not (all(hits) if "all" in mods else any(hits)): # values: OR (AND with |all)
return False
return True
def match_identifier(event, spec):
maps = spec if isinstance(spec, list) else [spec] # list of maps: OR
return any(match_map(event, m) for m in maps)
def evaluate(rule, event):
det = rule["detection"]
ids = {k: match_identifier(event, v) for k, v in det.items() if k != "condition"}
cond = det["condition"]
def quantifier(m): # "1 of selection_*", "all of them"
how, pat = m.group(1), m.group(2)
names = [k for k in ids if pat == "them" or fnmatch.fnmatchcase(k, pat)]
vals = [ids[k] for k in names]
return str(any(vals) if how == "1" else all(vals))
cond = re.sub(r"\b(1|all) of (\w+\*?|them)", quantifier, cond)
tokens = re.findall(r"\(|\)|\w+", cond)
expr = " ".join(t if t in ("and", "or", "not", "(", ")", "True", "False") else str(ids[t]) for t in tokens)
return eval(expr, {"__builtins__": {}}) # only True/False/and/or/not/() remain
RULE = yaml.safe_load(r"""
title: Office Application Spawns a Command Shell or Script Host
detection:
selection_parent:
ParentImage|endswith: ['\winword.exe', '\excel.exe', '\powerpnt.exe', '\outlook.exe']
selection_child:
Image|endswith: ['\cmd.exe', '\powershell.exe', '\pwsh.exe', '\wscript.exe', '\cscript.exe', '\mshta.exe']
filter_known_macro:
CommandLine|contains: 'lab-finance-report.cmd'
condition: all of selection_* and not filter_known_macro
""")
ENC = yaml.safe_load(r"""
title: Encoded PowerShell Outside Admin Sessions
detection:
selection:
Image|endswith: '\powershell.exe'
CommandLine|contains|all: [' -nop', ' -enc']
filter_admins:
ParentImage|endswith: '\explorer.exe'
User|startswith: 'LAB\adm-'
condition: selection and not 1 of filter_*
""")
events = [
{"ParentImage": r"C:\Program Files\Microsoft Office\root\Office16\WINWORD.EXE", "Image": r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe",
"CommandLine": "powershell -nop -w hidden -enc SQBFAFgA", "User": r"LAB\erin"},
{"ParentImage": r"C:\Program Files\Microsoft Office\root\Office16\EXCEL.EXE", "Image": r"C:\Windows\System32\cmd.exe",
"CommandLine": r"cmd /c \\fs01\finance\lab-finance-report.cmd", "User": r"LAB\grace"},
{"ParentImage": r"C:\Windows\explorer.exe", "Image": r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe",
"CommandLine": "powershell -nop -enc RwBlAHQALQBEAGEAdABlAA==", "User": r"LAB\adm-alice"},
{"ParentImage": r"C:\Windows\explorer.exe", "Image": r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe",
"CommandLine": "powershell -enc RwBlAHQALQBEAGEAdABlAA== -nop", "User": r"LAB\erin"},
{"ParentImage": r"C:\Windows\explorer.exe", "Image": r"C:\Program Files\Google\Chrome\Application\chrome.exe",
"CommandLine": "chrome.exe --profile-directory=Default", "User": r"LAB\ivan"},
]
for i, e in enumerate(events, 1):
hits = [name for name, r in {"office-shell": RULE, "encoded-ps": ENC}.items() if evaluate(r, e)]
print(f"event {i}: {e['CommandLine'][:46]:46} -> {hits or 'no match'}")event 1: powershell -nop -w hidden -enc SQBFAFgA -> ['office-shell', 'encoded-ps']
event 2: cmd /c \\fs01\finance\lab-finance-report.cmd -> no match
event 3: powershell -nop -enc RwBlAHQALQBEAGEAdABlAA== -> no match
event 4: powershell -enc RwBlAHQALQBEAGEAdABlAA== -nop -> ['encoded-ps']
event 5: chrome.exe --profile-directory=Default -> no match
Five events, five different paths through the logic:
- Word starting hidden, encoded PowerShell for erin matches both rules: both selections of
office-shelland theencoded-psselection. Note thatWINWORD.EXEin capitals still matches\winword.exe: Sigma comparisons are case-insensitive. - Excel starting the finance report script matches both selections of
office-shellbut also its filter, soand not filter_known_macroremoves it. - An admin's encoded command from Explorer matches the
encoded-psselection, andfilter_admins(both fields: Explorer parent and anadm-account) removes it. - The same command from erin's session, with the switches in the other order, matches:
|contains|allrequires both strings anywhere, and erin is not anadm-account. - Chrome matches nothing.
The fixture set is small but covers the behaviours a rule author must check: a true positive, a filtered look-alike, a variant (switch order), and a plainly benign event.
Why the condition is evaluated this way
The evaluator first computes a True/False value for every search identifier, replaces quantifiers (all of selection_*) by the combined value, then replaces each remaining identifier name in the condition with its value. What is left contains only True, False, and, or, not and parentheses, which Python's own parser evaluates with the right precedence (not binds tighter than and, which binds tighter than or, as in Sigma). Passing an empty __builtins__ and only those tokens keeps the eval safe: an identifier that is not defined raises a KeyError instead of being evaluated as code. Real implementations (pySigma) parse the condition into a tree instead, which also lets them convert it into other query languages.
What this evaluator leaves out
It is enough for tests and for learning, not for production:
- Other modifiers (
base64,base64offset,windash,utf16le,expand,exists, numeric comparisons such asgt), escaping of literal*and?, and keyword (field-less) searches. logsourcehandling: it assumes every event belongs to the rule's log source. In a real pipeline, aprocess_creationrule must only see process-creation events.- Correlation rules (counts and sequences across events), which need state over time; the pandas rules in the SIEM section do that.
- Performance: it evaluates each rule against each event in Python, fine for fixtures, slow for millions of events.
How it is used
- Fixture tests in CI. Every rule has positive and negative example events; the evaluator checks them on every change, before conversion.
- Explaining alerts. Evaluating one alerting event identifier by identifier shows which clause matched, which helps analysts and rule authors.
- Checking converters. Run the same fixtures through the converted query in a test SIEM; if the evaluator and the SIEM disagree, either the mapping or the converter is wrong.
Pitfalls
- Case-sensitivity in the backend. The evaluator lower-cases everything as Sigma specifies; a SIEM field stored as an exact-match keyword may not. Event 1's
WINWORD.EXEin capitals is a good fixture for this. - Negations and missing fields.
not filteris true for events without the filter's fields; if a parser dropsUser, every event passes the filter and the rule may suddenly fire much more (or, forselectionblocks, much less). - Wildcards inside values. A literal
*in a command line must be escaped (\*) in Sigma; otherwise it matches anything.
Practice
1. Add an event where `outlook.exe` starts `mshta.exe` with the command line `mshta http://203.0.113.66/a.hta`. Which rule matches?
office-shell: the parent ends with \outlook.exe, the child with \mshta.exe, and the filter does not match. encoded-ps does not (the image is not PowerShell).
2. Change event 4's user to `LAB\adm-bob`. What happens, and is the result right?
The filter matches (Explorer parent and an adm- account), so nothing alerts. That is what the rule says, but it is also a blind spot: an attacker who controls an admin's session is exempt. The rule's documentation should list it, and a separate, lower-severity rule could still record encoded commands by admins.
3. Add `|cidr` support to a rule: write a selection for network connections from the server subnet `10.10.0.0/28` to port 4444.
selection: { SourceIp|cidr: '10.10.0.0/28', DestinationPort: 4444 }. The evaluator's match_value already implements cidr with ipaddress; DestinationPort is compared as the string 4444.
Test yourself
Why does event 2 (Excel starting cmd.exe) not match the office-shell rule?
- Excel is not in the parent list
- The filter_known_macro identifier matches its command line, and the condition says
and not filter_known_macro - cmd.exe is not in the child list
- The event has no user
Why does event 4 match encoded-ps although -enc comes before -nop?
- Order matters in Sigma
|contains|allrequires every value somewhere in the field, in any order- The rule uses a regex
- It doesn't match
What does all of selection_* mean?
- Any identifier starting with selection_ matches
- Every identifier starting with selection_ matches
- All events are selected
- The rule is disabled
What happens to not filter when the event lacks the field the filter tests?
- The rule errors
- The filter is false, so
not filteris true and the event is not filtered out - The event is dropped
- The filter is true