YARA rules are how a finding from static triage becomes reusable detection: a set of strings plus a boolean condition that fires on every sample of a family and on nothing else. Writing a rule that only works on one sample is easy; writing one that survives packing variants, string reordering, and compiler noise while never firing on clean software is the actual skill. This skill covers turning triage artifacts into robust rules, testing them against malicious and clean corpora, tuning them for performance, and shipping them in a versioned, documented form. Scope: use when analyzing a malware sample in an isolated lab during authorized DFIR, threat intel work, or detection engineering. Test every rule against a clean corpus before it is allowed to alert or block anywhere.
Quick Workflow
- Confirm the family: have 3 or more samples you are confident belong to the same family (same strings, same config, same behavior).
- Extract candidate strings with FLOSS and capa, keep only ones that appear in all family samples.
- Drop generic strings (compiler paths, common library text, standard error messages) and keep family-unique ones: PDB paths with odd project names, unique mutex names, C2 URL patterns, custom error text.
- Write the rule with meta, strings, and a condition (start with
2 of themor3 of ($a*), tune from there). - Compile-check with
yara rule.yar sample.exeand confirm it fires. - Test coverage on the malicious corpus: every family sample should fire.
- Test false positives on a clean corpus (system32, common applications): zero fires is the target.
- Measure scan speed on a large directory and fix slow atoms if needed.
- Write meta (author, date, reference hash, sample count tested) and commit the rule with its test report.
1. Picking strings that survive
Good rule strings are long, unique, and tied to the malware's own logic, not to its toolchain. Sources, in order of value:
# Decoded strings catch what plain strings misses
floss -n 10 sample.exe > strings.txt
# capa output names capabilities; the strings behind them are often unique
capa -v sample.exe 2>/dev/null | grep -i "string" | head -20
# PDB paths and mutex names are almost always family-unique
strings -n 8 sample.exe | grep -iE "\.pdb|mutex|Global\\\\" | sort -u
Example output shape from a real triage pass:
Z:\Builds\ProjectNimbus\Release\loader.pdb
Global\NimbusSyncMutex_7f3a
POST /api/v2/beacon HTTP/1.1
XOR key schedule initialized, rc=%d
Prefer the PDB path and the mutex over the HTTP line (HTTP text is common). Keep 5 to 10 candidates so the condition can tolerate one being stripped in a variant.
2. String types and modifiers
rule Malware_Family_Loader
{
meta:
description = "Detects Family loader, all known variants"
author = "analyst"
date = "2026-10-23"
reference = "sha256:aaa... (first sample)"
sample_count = 12
strings:
$pdb = "Z:\\Builds\\ProjectNimbus\\Release\\loader.pdb" ascii
$mutex = "Global\\NimbusSyncMutex_7f3a" ascii wide nocase
$ua = /NimbusAgent\/[0-9]+\.[0-9]+/ ascii
$key = { 8B 45 ?? 33 C0 89 45 FC 8D 45 ?? E8 ?? ?? ?? ?? }
$err = "XOR key schedule initialized, rc=%d" ascii fullword
condition:
uint16(0) == 0x5A4D and
filesize < 5MB and
3 of them
}
Modifiers that matter: wide catches UTF-16 strings (very common in
Windows malware), nocase survives case changes, fullword kills partial
matches that cause false positives, ascii pins encoding. Regex is good
for versioned user agents or formatted IDs. Hex strings with ?? wildcards
capture opcode sequences with variable operands; keep them short (8 to 16
bytes) so they stay fast and match across compiler versions.
3. Conditions that survive variants
all of them dies the moment one string changes. Prefer counts:
2 of them,3 of them: simple, robust, easy to tune.2 of ($a*)/1 of ($hex*): group by string family so you can mix string sources with different weights.- Add a structural anchor:
uint16(0) == 0x5A4Dfor PE,uint32(0) == 0x464C457Ffor ELF. This alone kills most cross-format false positives. - Add a filesize bound when the family is consistent:
filesize < 5MBkeeps the rule from firing on giant installers that happen to contain a string.
Test shape: run the rule against each sample and record hits.
for f in family/*.exe; do
echo -n "$f: "
yara rule.yar "$f" | wc -l
done
Expected output shape: every line ends with 1 (fired). Any 0 is a
missed variant you must investigate before shipping.
4. Module checks for structure, not just text
Modules let the condition inspect file structure, which string-only rules cannot do:
import "pe"
import "math"
rule Malware_Family_Loader_Struct
{
condition:
pe.number_of_sections == 5 and
pe.imphash() == "d4b2c1a0f3e8..." and
math.entropy(0, filesize) > 7.2 and
pe.imports("kernel32.dll", "VirtualAlloc")
}
Use imphash (import hash) as a family fingerprint when the import table is
stable; use section counts and entry point section when packers are in play.
The dotnet module covers .NET assemblies, hash covers checksums. Keep
module conditions alongside string conditions: strings catch intent,
modules catch shape.
5. False-positive testing on a clean corpus
A rule that fires on clean software is worse than no rule. Build a clean corpus once and reuse it: a fresh Windows system32, common applications (browsers, office tools), and your own toolset.
yara -r rule.yar /mnt/clean_corpus/ > fp.txt
wc -l fp.txt # target: 0
If it fires, find which string matched with yara -s and replace that
string with something more unique, or add a structural condition that
excludes the clean file. Document every false positive you found and fixed
in the rule's meta or commit message; the next analyst needs that history.
6. Naming, versioning, deployment
Naming convention: <Type>_<Family>_<Role>, e.g.
Trojan_Nimbus_Loader, Ransom_CryptX_Payload. Keep names stable; add a
suffix (_v2, _202610) only when the rule changes semantics. Meta must
include description, author, date, at least one reference hash, and the
sample counts you tested against. Store rules in git, one family per file
or one rule per file, and tag releases. Deploy to sandboxes first (alert
only), watch for a week of production traffic, then promote to blocking if
your pipeline supports it.
Edge cases
- Packed samples: strings are hidden until unpacked. Write the rule against the unpacked payload, and add a companion rule for the packer stub if the stub is family-specific. Never write the main rule against packed bytes alone.
- .NET and script-based malware: prefer the
dotnetmodule (assembly name, streams) over raw strings, since decompilers and obfuscators mangle string layout. - Very small samples (under 50 KB): short strings are unavoidable, so
lean harder on module conditions and
fullwordto keep false positives down. - Rules that must run on endpoints: keep them fast. Avoid long regexes,
avoid
all of themon 40 strings, and check atom quality (see the rule-optimization sub-skill). - Family drift: when new samples stop matching, do not widen the rule until it matches everything; add a v2 rule for the new branch and keep v1 for the old one.
- Shared builder strings: crimeware builders reuse strings across unrelated families. If a string appears in two families, it is not a family string; drop it or demote it to a weak signal.
- Private rules: use
private rulefor helper rules imported by others so they do not alert on their own.
Escalation
- If the family is packed with a custom packer and no unpacked payload exists, escalate to manual unpacking (malware-packer-triage) before writing the rule; a rule on packed bytes is fragile by design.
- If coverage testing shows two distinct string clusters, you may be looking at two families; split them and write one rule each rather than one loose rule.
- If a rule fires on a legitimate signed binary, stop deployment immediately, investigate whether the binary is trojanized or the string is generic, and fix before re-enabling.
- If scan performance degrades a pipeline (rule takes seconds per file), escalate to rule-optimization: rewrite atoms, split the rule, or move the expensive check to a second-stage rule.
Detection and defender view
YARA rules are the detection artifact this skill produces, so think like the defender who will run them. Write meta that another analyst can act on: what family, what role in the infection chain, what to do when it fires (isolate host, collect the file, check for the persistence mechanism named in the sub-skill on persistence). Pair every rule with a hunt query for your SIEM: the same mutex name or C2 pattern in process creation logs or DNS logs catches what the file rule misses. Track rule health over time: coverage on new samples, false-positive rate per week, and mean scan time. Retire rules for dead families instead of letting them rot; stale rules erode trust in the whole set.
Key references
- YARA documentation (rules, modules, performance): https://yara.readthedocs.io/
- YARA-X documentation and migration guide: https://virustotal.github.io/yara-x/
- MITRE ATT&CK: T1027 (Obfuscated Files or Information), T1587 (Develop Capabilities), T1588 (Obtain Capabilities)
- Mandiant FLARE FLOSS (string extraction): https://github.com/mandiant/flare-floss
- Mandiant FLARE capa (capability identification): https://github.com/mandiant/capa
- YARA style guide (Bayer / standard conventions): https://github.com/Neo23x0/YARA-Style-Guide
- YARA performance and atom quality notes: https://yara.readthedocs.io/en/stable/writingrules.html#performance
See also
yara-rules: Use it instead for general rule craft, including performance tuning with atoms and YARA-X differences.
