Testing Rules: False Positives and Performance
A YARA rule that matches the sample it was written from proves almost nothing: of course it matches, it was built from those bytes. The questions that decide whether a rule can be deployed are the other two: does it match the other members of the family (recall), and does it stay silent on everything else (false positives)? A false positive in a hunting rule costs an analyst ten minutes. In an EDR rule set to quarantine, it can delete a system library on ten thousand machines. Rule testing is therefore part of writing the rule, with a corpus of known-bad and a much larger corpus of known-good files.
Definitions
- True positive / false positive: the rule matches a family member / something that is not.
- Goodware corpus: a large set of legitimate files of the platform the rule targets: operating-system files, common applications, installers, documents. Teams build their own; NSRL-listed files and clean OS images are common sources.
- Recall on the family set: matched family samples divided by all family samples you have.
- Atoms: the short substrings (up to 4 bytes) YARA picks from each string to drive its fast search. Strings with no good atom (short, common bytes, regexes starting with wildcards) make every rule file slower and trigger the compiler warning "string … may slow down scanning".
yarac: compiles rules to a binary file; compile errors and warnings appear there, before deployment.
Testing a sloppy rule and a careful one
The session sets up a family set (two synthetic builds of the lab sample, as in YARA basics) and uses the sandbox's own operating-system files (/usr/bin and /usr/lib/x86_64-linux-gnu) as a goodware corpus. Then it measures three rules: a sloppy one built from words that "looked distinctive" in the sample, a careful one without a file-type guard, and the careful one with the guard.
mkdir family && python3 - <<'PY'
import random
r = random.Random(21)
cfg = b"server=update.beacon.lab.test;port=8080;interval=60"
for build, key in ((1, 0x5C), (2, 0x21)):
data = (b"MZ" + bytes(62) + r.randbytes(300) + b"LABAGENT-CFG" + bytes([build]) + bytes(c ^ key for c in cfg)
+ r.randbytes(200) + "Global\\LabAgent-Mutex-7f3a".encode("utf-16-le") + b"\0\0" + r.randbytes(300))
open(f"family/agent-{build}.bin", "wb").write(data)
PY
find /usr/bin /usr/lib/x86_64-linux-gnu -type f -size -20M | sort > goodware.txt
echo "goodware files: $(wc -l < goodware.txt)"
cat > sloppy.yar <<'RULE'
rule LabAgent_sloppy
{
strings:
$a = "beacon" nocase
$b = "interval="
$c = "config" nocase
condition:
any of them
}
RULE
cat > careful-noguard.yar <<'RULE'
rule LabAgent_careful_noguard
{
strings:
$magic = "LABAGENT-CFG"
$dom = "update.beacon.lab.test" xor(0x01-0xff)
$mutex = "LabAgent-Mutex-7f3a" wide
condition:
$magic and ($dom or $mutex)
}
RULE
sed -e 's/careful_noguard/careful/' -e 's/^ \$magic and/ uint16(0) == 0x5A4D and $magic and/' careful-noguard.yar > careful.yar
for rule in sloppy.yar careful-noguard.yar careful.yar; do
tp=$(yara -r "$rule" family 2>/dev/null | wc -l)
fp=$(yara --scan-list "$rule" goodware.txt 2>/dev/null | wc -l)
printf '%-20s family matched %d/2 goodware matched %4d\n' "$rule" "$tp" "$fp"
done
echo "--- what the sloppy rule hit (first five) and why"
yara --scan-list sloppy.yar goodware.txt 2>/dev/null | sort | head -5
yara -s sloppy.yar /usr/bin/apt-config | head -4
echo "--- compiler warnings for a slow rule"
printf 'rule slow { strings: $x = { 00 00 } $y = /.*beacon/ condition: any of them }\n' > slow.yar
yarac slow.yar slow.yarc 2>&1goodware files: 1712
sloppy.yar family matched 0/2 goodware matched 223
careful-noguard.yar family matched 2/2 goodware matched 0
careful.yar family matched 2/2 goodware matched 0
--- what the sloppy rule hit (first five) and why
LabAgent_sloppy /usr/bin/apt
LabAgent_sloppy /usr/bin/apt-cache
LabAgent_sloppy /usr/bin/apt-cdrom
LabAgent_sloppy /usr/bin/apt-config
LabAgent_sloppy /usr/bin/apt-get
LabAgent_sloppy /usr/bin/apt-config
0xa25:$c: Config
0xae3:$c: Config
0xb09:$c: Config
--- compiler warnings for a slow rule
warning: rule "slow" in slow.yar(1): string "$x" may slow down scanning
warning: rule "slow" in slow.yar(1): $y contains .*, .+ or .{x,} consider using .{,N}, .{1,N} or {x,N} with a reasonable value for N
The sloppy rule fails in both directions. It matches none of the family builds, because in the real samples the configuration that contained "beacon" and "interval=" is XOR-encoded (the analyst copied the words from the decoded configuration), and it matches 223 legitimate system files, because "config" is an ordinary word (apt-config contains Config many times). The careful rules match both builds and no goodware.
The guard (uint16(0) == 0x5A4D) didn't change the numbers here, and that is a lesson too: this goodware corpus is Linux ELF files, so it can't reveal false positives that a Windows rule would have on Windows files. Test against goodware of the platform the rule is for: Windows rules against a clean Windows image and common Windows software, document rules against real documents.
The compiler warnings flag two classic mistakes: a 2-byte hex string of zeros (it matches almost everywhere and has no useful atom) and a regular expression that starts with .* (unbounded, and no literal to anchor the search).
How rule quality is measured over time
- Before release: recall on the family set, zero (or an accepted, documented number of) goodware hits, no compiler warnings, a scan-time check on a large corpus.
- After release: every match is reviewed; confirmed false positives go into the goodware corpus and the rule is fixed, so the same mistake can't come back (a regression test).
- Retire rules that never match anything in a year, or keep them in hunting only.
How to write rules that pass
- Base strings on what is unique and stable in the family: configuration markers, distinctive code sequences, PDB paths, unusual strings, never common words.
- Combine several weak strings with
N of them, add a file-type guard and a size limit. - Put a
metablock with author, date, reference, the samples' hashes, and the minimum YARA version. - Keep rules in version control with their test sets, and run the tests in CI like any other code.
Pitfalls
- Testing only on the source sample. It is the least informative test.
- A goodware corpus of the wrong platform, as above.
- Goodware that contains your strings for good reasons: security products and analysis tools ship YARA rules and threat names; your own rule repository will match itself.
- Silent errors:
yaraprints read errors (permission denied, files that vanished) on stderr; discarding stderr in tests can hide that half the corpus was never scanned. Count the files actually scanned.
Practice
1. Suppose you fix the sloppy rule by adding xor to its strings, and it then matches 2/2 family builds. Is it a good rule now?
No. Recall says nothing about specificity: it would still match the same 223 goodware files (more, in fact, since xor widens the search). A rule that matches every file has perfect recall and is useless.
2. Change the careful rule to any of them. Predict the effect, then test it.
$dom with xor(0x01-0xff) alone is still fairly specific, but any of them means a single 19-character mutex name or the marker alone triggers it, including in analysts' notes and reports. Expect possible hits on text files that mention the names; with this Linux corpus probably still none, which again shows the corpus limits.
3. How would you count the files actually scanned, not just the matches?
Run with -n (negate) and add both counts: matches plus non-matches should equal the number of files in the list. Any difference is files that failed to scan; print stderr to see why.
Test yourself
What is the main purpose of a goodware corpus?
- To train the malware
- To measure false positives: the rule must stay silent on legitimate files
- To speed up YARA
- To store samples
Why did the sloppy rule match hundreds of system files but none of the family builds?
- System files are infected
- Its strings are ordinary words common in legitimate programs, and in the samples those words are XOR-encoded
- YARA was misconfigured
- The files are too large
Why didn't the MZ guard change the result in this test?
- The guard is ignored by YARA
- The goodware corpus contained only Linux ELF files, so no false positive the guard prevents could appear
- The family samples are ELF
- The guard was misspelt
What does the warning 'string may slow down scanning' mean?
- The rule has a syntax error
- The string has no good atom for YARA's fast search, so it costs time on every file
- The file is too big
- The string uses wide