YARA Rules: A Practitioner's Guide
What YARA rules are, how a rule is built, how modules and conditions work, how to keep rules fast and quiet, where YARA runs, and how it differs from Sigma and YARA-L.
Last reviewed December 2026
YARA is an open pattern-matching language and engine for identifying files, and sometimes process memory, by the text strings, byte sequences and structural properties they contain.
A YARA rule names some patterns and states a condition over them. The engine scans a file, a directory or a running process, and reports every rule whose condition is true. It was written by Victor Alvarez at VirusTotal and has become the common language malware analysts use to describe a family, a toolkit or a single sample in a way others can run.
If Sigma is the shared format for detections over logs, YARA is the shared format for detections over files. Sigma asks "did this behavior happen?" and YARA asks "is this artifact one I recognize?". Both have a place in a detection program, and they fail in different ways. For the wider discipline both belong to, see our detection engineering guide.
Anatomy of a YARA rule
A rule has three sections: meta, strings and condition. Only condition is required. Here is a realistic rule for a fictional loader, annotated.
import "pe" // modules expose parsed file structure
rule Loader_Stager_UpdChk
{
meta: // free-form key/value pairs; not used for matching
description = "UpdChk shellcode stager: mutex, user agent, config decode loop"
author = "Your name"
date = "2026-12-01"
reference = "Internal case notes"
score = 70 // some scanners read this to rank hits
strings:
// text string, searched as both ASCII and UTF-16LE
$mutex = "Global\\SvcUpd8_Mtx" ascii wide
$ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) UpdChk/2.1" ascii
// hex string: ?? is a wildcard byte, [2-6] is a jump of 2 to 6 bytes
$cfg_key = { 8B 45 ?? 35 5A 3C 7E 11 89 45 ?? EB [2-6] 83 7D ?? 00 }
// regex with bounded repetition, matching the build path in the PDB string
$pdb = /[A-Z]:\\[^\\]{1,40}\\stager[^\\]{0,20}\\Release\\[a-z0-9_]{1,20}\.pdb/ nocase
condition:
uint16(0) == 0x5A4D // "MZ" at offset 0
and uint32(uint32(0x3C)) == 0x00004550 // "PE\0\0" at the PE header offset
and filesize < 3MB
and (
$cfg_key // code bytes alone are enough
or 2 of ($mutex, $ua, $pdb) // otherwise two artifacts together
)
and pe.imports("kernel32.dll", "VirtualAlloc")
}
Meta is for people and tooling. The engine ignores it when matching, but it is how a rule stays reviewable a year later: what it detects, who wrote it, where the evidence came from.
Strings come in three kinds. Text strings take modifiers: ascii and wide for encodings, nocase, fullword to require non-alphanumeric boundaries, and xor and base64 for common obfuscation. Hex strings describe byte patterns with wildcards (??), jumps ([2-6]) and alternatives (( 4D 5A | 5A 4D )), which makes them the natural way to match compiled code where registers or offsets vary between builds. Regular expressions cover what the other two cannot, at a cost discussed below.
The condition is a boolean expression. It can reference whether a string matched ($ua), how many times (#ua > 3), where ($mutex at 0, $pdb in (0..1024)), how many of a set matched (2 of ($mutex, $ua, $pdb), any of them), the file size, and raw integers read at an offset. uint16(0) == 0x5A4D is the idiomatic check that a file starts with "MZ": YARA reads integers little-endian, so the bytes 4D 5A read back as 0x5A4D.
The structure of that condition is deliberate. A single distinctive code sequence is allowed to match on its own; weaker artifacts like a mutex name or user agent have to appear together. That split between strong and weak indicators is most of the craft of writing a YARA rule.
Modules: pe, math and friends
Modules let a condition reason about file structure rather than raw bytes. You import them at the top of the file.
- pe parses Windows executables: imports and exports, sections, resources, the rich header, timestamps, version info and signatures.
pe.imports("kernel32.dll", "VirtualAlloc"),pe.number_of_sections, andpe.imphash()(when YARA is built with crypto support) are common. - elf and macho do the same for Linux and macOS binaries.
- math computes statistics over a byte range, most often entropy. High entropy in a code section is a reasonable hint of packing or encryption:
import "pe"
import "math"
rule Suspicious_High_Entropy_Section
{
condition:
uint16(0) == 0x5A4D
and for any section in pe.sections : (
math.entropy(section.raw_data_offset, section.raw_data_size) >= 7.2
)
}
- hash computes MD5, SHA-1 and SHA-256 over a range, useful for matching a known embedded resource.
- dotnet parses .NET metadata such as assembly names, GUIDs and streams.
A rule like the entropy example above is a hunting rule, not an alerting rule. Plenty of legitimate software is packed or carries compressed resources. Use it to find candidates, then write the specific rule once you know what you are looking at.
Writing rules that stay fast
YARA scans quickly because it does not test every string against every byte. When rules compile, it picks a short substring, called an atom (up to four bytes), from each string and feeds all atoms into a single Aho-Corasick automaton. Only where an atom hits does YARA verify the full string. Rule performance is mostly about giving YARA good atoms.
Practical consequences:
- Avoid short strings. A two- or three-byte string has a poor atom and gets verified everywhere. YARA prints a warning that a string "may slow down scanning" for this reason; treat that warning as an error.
- Avoid common atoms. Strings that begin with
00 00 00 00,FF FF FF FFor90 90 90 90hit constantly in real files. Pick a more distinctive anchor, or move wildcards so that the fixed bytes YARA can use are unusual. - Bound your regular expressions.
.*and.+let a single hit scan to the end of the file. Use{1,40}style limits, and anchor regexes with a literal prefix so YARA can extract an atom from it. - Prefer hex jumps over huge wildcards.
[2-6]is cheap;[0-5000]is not. - Remember the order of work. YARA searches for all strings first and evaluates conditions afterwards, so
filesize < 3MBin a condition does not skip the string scan. Condition ordering still matters for expensive checks such as module calls and loops, which short-circuit behind cheaper ones.
When a rule set is scanned across a fleet or a mail stream, one slow rule costs everyone. Profile new rules against a realistic corpus before deployment, not after someone notices endpoint CPU.
Testing for false positives
A YARA rule is a claim that a pattern is specific to something malicious. Testing that claim is the difference between a usable rule and a source of noise.
- Compile and check.
yaracor a plainyararun catches syntax errors and performance warnings. - Confirm it hits the samples it was written from. Run
yara -s rule.yar samples/and read which strings matched. A rule that matches for the wrong reason will fail on the next variant. - Test related samples. If the rule is meant to cover a family, run it against every sample you have, not just the one you started with.
- Scan a goodware corpus. Run the rule over a large collection of clean files: a fresh Windows install, common software installers, your own golden images, and the internal tools your organization builds. Any hit on clean files is a false positive until proven otherwise.
- Look at the size and file-type guard. Many false positives come from a rule that was meant for PE files matching inside an archive, a memory dump or a backup. The
uint16(0)check and afilesizebound remove most of these. - Keep the test in version control. Store the sample hashes and the expected result next to the rule, and run them on every change, the same way you would treat any other rule under detection as code.
Rules decay too. A YARA rule tied to strings in one build stops matching when the authors change a compiler flag or rotate a mutex name. That rule still compiles, still shows as deployed, and silently covers nothing. In Spectrum's Detection Debt Report, 29% of deployed, enabled detection rules were broken; that work measured SIEM rules, but the lesson carries over. A detection nobody re-tests is a detection nobody knows is working.
Where YARA runs
YARA is a library and a command-line tool, and most of its reach comes from products that embed it.
| Where | What it scans | Typical use |
|---|---|---|
| EDR and endpoint agents | Files on disk, sometimes process memory | Sweeps for a known family across the fleet |
| Forensic and IR scanners (THOR, Loki, Velociraptor) | Disk images, live hosts, memory | Compromise assessment and incident scoping |
| Malware sandboxes (CAPE and others) | Submitted samples, dropped files, memory dumps | Family classification and config extraction |
| VirusTotal Livehunt and Retrohunt | New uploads, and historical uploads | Tracking a family over time and finding new variants |
| Mail and web gateways | Attachments and downloads | Blocking known malicious documents and payloads |
| File-scanning pipelines | Uploads, artifact stores, object storage | Checking files entering an environment |
The same rule can run in several of these, but each embeds its own YARA version and may enable a different set of modules. A rule that uses a newer module function can fail to compile on an older scanner, so check the version on each target before rolling out shared content.
YARA is also a natural fit for threat hunting: a retrohunt across months of submissions, or a memory sweep across hosts, is often how a team finds out how long something has been present.
YARA-X
YARA-X is VirusTotal's rewrite of YARA in Rust, maintained by the same author and intended as YARA's successor. It aims to be largely compatible with existing rules while improving error messages, safety and performance on complex rules. Some edge cases behave differently and some rarely used features are not carried over, so test an existing rule set before switching engines, rather than assuming it will behave identically.
YARA vs. YARA-L
The names collide, and they mean different things. YARA-L is the detection language in Google Security Operations (formerly Chronicle). It borrows YARA's look (a rule with meta and condition sections) but works on log events in Google's Unified Data Model, with events, match and outcome sections for joining events over a time window. It is a SIEM query language, closer to Sigma or KQL than to YARA.
If you are writing patterns for files and memory, you want YARA. If you are writing detections over logs in Google SecOps, you want YARA-L. A Sigma rule can be converted to YARA-L; a YARA rule cannot.
Where YARA fits
YARA answers a narrow question very well: is this file, or this memory, something we have seen before? It complements log-based detection, it does not replace it. The best programs use YARA for artifacts, Sigma or native queries for behavior, and test both against real data on a schedule.
The research behind a good YARA rule (which strings are stable across builds, which code survives recompilation, which artifacts are shared with legitimate software) is the same research that drives behavioral detections. Spectrum's threat intelligence platform turns that research into detections for your own environment, and keeps checking that they still fire.
Related guides
See what your environment is actually detecting
Spectrum maps your coverage, builds the detections you are missing, and keeps them working.