YARA is fast when its prefilter is fast. Before evaluating your condition, YARA extracts short literal substrings ("atoms") from every string and scans for those with Aho-Corasick; only files containing an atom get the full expensive check. A rule whose atoms are short, common, or numerous forces the slow path on nearly every file. This sub-skill covers picking atoms that filter well, measuring where time goes, and rewriting rules for speed without losing coverage. Scope: use when analyzing a malware sample in an isolated lab during authorized DFIR or detection engineering. Optimization must never weaken the rule's precision; re-run false-positive tests after every rewrite.
Quick Workflow
- Benchmark the current rule: time a scan over a fixed corpus and record per-file time.
- Identify the slow strings: test each string alone and rank by scan time.
- Check atom quality: short or common atoms are the suspects.
- Rewrite the worst strings with longer literals, fullword, or tighter patterns.
- Re-benchmark on the same corpus; confirm identical match results.
- Re-run the clean-corpus false-positive test to confirm precision held.
- Document the before/after numbers in the rule's test report.
1. How atoms decide your speed
YARA picks atoms automatically from your strings: for text it takes literal runs, for regex the longest literal prefix, for hex the longest fixed run. Quality rules of thumb:
- Longer is better: a 12-byte literal filters harder than a 4-byte one.
- Rarer is better: "NimbusSyncMutex" beats "temp" as an atom.
- Fewer strings is better: 40 strings means 40 atom sets to check.
# Measure: time each string as its own rule over the same corpus
for s in strings_list.txt; do
# build single-string rule, time it
/usr/bin/time -f "%e s" yara single.yar /corpus/large/ > /dev/null
done
Example output shape after ranking:
$mutex_full (24 bytes) 0.42 s
$ua_regex 1.10 s
$err_short (6 bytes) 8.70 s <- suspect: short atom, common bytes
The 6-byte string dominates runtime. That is the one to rewrite or drop.
2. Rewriting slow patterns
Techniques, weakest-first to cut:
- Lengthen: extend a short string with adjacent context bytes from the binary ("Error" becomes "Error: beacon failed, rc=").
- fullword: a substring atom that matches inside many words becomes far more selective with word boundaries.
- Anchor regexes: rewrite
/[0-9]{3}-[0-9]{4}/as/CAMP-[0-9]{3}-[0-9]{4}/when the prefix is constant; the literal "CAMP-" becomes the atom. - Drop the worst: if a short string adds little coverage (fires on samples the other strings already catch), remove it and adjust the count condition.
- Split the rule: a fast first-stage rule (3 strong strings) that gates a slow second-stage rule (regexes, module checks) run only on hits.
// Stage 1: fast, runs everywhere
rule Trojan_Nimbus_Fast
{
strings:
$a = "NimbusSyncMutex_7f3a" ascii wide fullword
$b = "Z:\\Builds\\ProjectNimbus\\Release\\loader.pdb" ascii
condition:
uint16(0) == 0x5A4D and 2 of them
}
// Stage 2: thorough, runs only on stage-1 hits
rule Trojan_Nimbus_Deep
{
strings:
$re = /beacon\/[a-z]+\/[0-9]{4}/ ascii
condition:
Trojan_Nimbus_Fast and $re
}
3. Condition order and short-circuiting
YARA evaluates conditions left to right with short-circuiting. Put the cheapest, most selective test first:
condition:
uint16(0) == 0x5A4D and // cheap integer check, kills non-PE instantly
filesize < 5MB and // cheap, kills huge files
3 of them // expensive string matching runs last
Module calls (pe.imphash(), math.entropy over the whole file) are expensive; place them after the string count, not before, unless the module check is the selective one. Measure both orders if unsure; the difference is often 2x or more.
4. Benchmarking discipline
# Fixed corpus, fixed hardware, three runs, take the median
hyperfine --warmup 1 --runs 3 \
'yara rule_v1.yar /corpus/mixed/ > /dev/null'
hyperfine --warmup 1 --runs 3 \
'yara rule_v2.yar /corpus/mixed/ > /dev/null'
Example output shape:
rule_v1: 12.4 s +- 0.3 s
rule_v2: 3.1 s +- 0.1 s (4x faster, same hits: verified by diff)
Always diff the match lists between versions: yara v1 vs yara v2
output must be identical on both corpora. A faster rule that misses a
sample is a regression, not an optimization.
5. Endpoint and scale considerations
For rules deployed to endpoints or scanned across millions of files:
- Keep total strings under ~15; each string is prefilter cost on every file.
- Avoid
math.entropy(0, filesize)on large files; bound the range or drop it. - Prefer
pe.module checks over full-file scans where possible; the module parses structures instead of scanning bytes. - Set realistic filesize bounds; scanning a 2 GB file for a 200 KB malware family is pure waste.
Edge cases
- YARA-X has a different optimizer; a rule fast under YARA 4 may behave differently under YARA-X. Benchmark on the engine you deploy.
- Over-optimization can hurt coverage: lengthening a string past a variant's mutation point loses that variant. Re-run coverage tests.
- Atoms from
xororbase64modifiers multiply the atom set; use them sparingly in hot rules. fullwordonwidestrings has edge behavior at buffer ends; test with real samples.- Benchmarks on SSD vs network storage are not comparable; always use the same mount.
- A rule that is fast on your corpus may be slow on the SOC's corpus; ask for a sample of their data distribution before promising numbers.
Escalation
If a rule cannot be made fast without losing coverage, escalate the architecture: split into fast triage plus slow confirm, or move the expensive check to a post-processing job.
If endpoint CPU budgets block deployment, escalate to the detection owner with measured numbers; do not silently ship a neutered rule.
If YARA-X migration changes performance characteristics, escalate to re-benchmarking the whole ruleset, not just the one rule.
If optimization for one engine (YARA) regresses another (YARA-X), keep per-engine variants and document the split.
Detection and defender view
Performance is a detection property: a rule too slow for the pipeline effectively does not exist. Report rule cost alongside rule coverage (mean ms per file, corpus size tested) so detection owners can budget. In incident response, a fast rule that scans the fleet in minutes beats a perfect rule that takes hours; keep a "hunt-fast" variant of critical rules with the expensive conditions stripped. Track per-rule scan time in production and alert on regressions; a rule that suddenly slows down often means its atoms started matching a new common file type.
Key references
YARA performance documentation: https://yara.readthedocs.io/en/stable/writingrules.html
YARA-X performance notes: https://virustotal.github.io/yara-x/docs/intro/
YARA style guide (performance section): https://github.com/Neo23x0/YARA-Style-Guide
hyperfine (benchmarking): https://github.com/sharkdp/hyperfine
YARA-X repository: https://github.com/VirusTotal/yara-x
