YARA Rules: How to Write, Run and Tune File and Memory Detections

YARA is the pattern-matching language security teams use to find malware and attacker tooling in files and process memory. This guide covers how a rule is put together, how to run rules on hosts, uploads and samples, and what separates a rule that finds intrusions from one that fires on every installer in the estate.

By the Security Monitoring Review editors · Updated

What a YARA rule is

A YARA rule describes a family of files by what is inside them: text strings, byte sequences or regular expressions, plus a condition that says how many of them must appear, where, and in what kind of file. Point the scanner at a file, a directory or a running process and it reports which rules match.

Where Sigma rules match log events in a SIEM, YARA matches content: the binary a user downloaded, the attachment a mail gateway quarantined, the payload unpacked in a process's memory. The two complement each other — Sigma sees what happened, YARA identifies what the thing was.

YARA was created by Victor Alvarez at VirusTotal and is open source on GitHub (VirusTotal/yara). VirusTotal now develops YARA-X, a rewrite in Rust, as its successor (VirusTotal/yara-x). Most existing rules run on both, but YARA-X is stricter about some constructs; read its documentation on differences before moving a rule set across.

Anatomy of a rule

The rule below flags Windows executables that carry a certutil download command — a common way for a dropper to fetch its next stage with a signed system binary.

import "pe"

rule SUSP_PE_Embedded_Certutil_Download : downloader
{
    meta:
        description = "Windows executable carrying a certutil URL-cache download command"
        author = "Security Monitoring Review"
        date = "2026-11-23"
        reference = "https://attack.mitre.org/techniques/T1105/"

    strings:
        $tool = "certutil" ascii wide nocase
        $opt1 = "-urlcache" ascii wide nocase
        $opt2 = "/urlcache" ascii wide nocase
        $url = /https?:\/\/[a-z0-9.\-]{4,64}\// ascii wide nocase

    condition:
        uint16(0) == 0x5A4D
        and filesize < 5MB
        and pe.number_of_sections > 0
        and $tool and 1 of ($opt*) and $url
}

Every rule has the same parts:

  • Name and tags — rule Name : tag1 tag2. Names must be unique within a rule set; a prefix convention such as SUSP_, MAL_ or HKTL_ (hack tool) tells an analyst how much to trust a hit before they open it.
  • `meta` — free-form key–value pairs: description, author, date, references. YARA ignores them when matching, but scanners print them with a hit, so they are what the analyst reads at triage time.
  • `strings` — the patterns to look for, each named with a $ identifier.
  • `condition` — a Boolean expression over those strings and the file's properties. It is the only required section.
  • `import` — optional modules (pe, elf, math, hash, dotnet and others) that parse the file and expose its structure to the condition.

Strings: text, hex and regular expressions

KindExampleUse it for
Text$a = "cmd.exe /c" ascii wideReadable strings: commands, paths, mutex names, error messages.
Hex$b = { 4D 5A ?? 00 [2-4] E8 }Byte patterns and code: ?? is any byte, [2-4] a jump of two to four bytes, ( 6A | 68 ) an alternative.
Regex$c = /[a-z0-9]{16}\.onion/Variable values such as URLs and keys. Slower than the other two, so keep them anchored to a fixed substring.

Modifiers after a text string change how it matches:

  • ascii and wide — match the one-byte form, the UTF-16 form, or both. Windows binaries often store strings as wide; without it the rule misses them.
  • nocase — case-insensitive.
  • fullword — only match when the string is not part of a longer word.
  • xor and base64 / base64wide — also match the string single-byte-XOR encoded or base64 encoded, a common way malware hides its configuration.
  • private — the string can be used in the condition but is not reported in the output.

Conditions and modules

The condition is where a rule becomes precise. The building blocks:

ExpressionMeaning
$aThe string appears at least once.
#a > 3It appears more than three times.
$a at 0, $a in (0..1024)It appears at an exact offset, or within a range of offsets.
any of them, all of ($s*), 2 of ($a, $b, $c)Counts across sets of strings; wildcards select every string with a prefix.
filesize < 2MBLimits the rule to files of a plausible size.
uint16(0) == 0x5A4DReads raw bytes at an offset: here the MZ header of a Windows executable. uint32, uint16be and similar read other widths and byte orders.
for any i in (1..#a) : (@a[i] < 100)Loops over each match; @a[i] is the offset of the i-th match and !a[i] its length.

Modules add the file's structure. With import "pe" a condition can test pe.imports("kernel32.dll", "VirtualAlloc"), pe.is_dll(), section names or the signing certificate; elf does the same for Linux binaries; math.entropy(0, filesize) helps spot packed or encrypted content; hash.sha256(0, filesize) pins a rule to one known file. Which modules and functions exist depends on the YARA version and how it was built — yara --help and the module documentation for your version are the authority.

Running rules

# Scan a directory recursively, printing matched strings and metadata
yara -r -s -m rules/ /srv/uploads/

# Scan a running process by PID
yara rules/mal_loader.yar 4312

# Compile a large rule set once, then load the compiled form
yarac rules/index.yar rules.compiled
yara -C rules.compiled -r /home/

# YARA-X equivalent
yr scan rules/ /srv/uploads/

The yara-python library (yara.compile(...), then rules.match(...)) and YARA-X's own Python bindings put the same engine inside scripts, mail and upload pipelines and sandbox tooling. Many EDR products, forensic tools such as Velociraptor, and VirusTotal's Livehunt and Retrohunt also run YARA rules directly; check each product's documentation for which YARA version and modules it supports, because a rule that compiles locally can fail to load in a product built on an older engine.

Where YARA fits in a monitoring programme

  • Incident scoping. Once a sample is found on one host, a rule written from it can sweep the rest of the fleet for the same family — faster and more resilient than hunting a single hash.
  • Inbound content. Mail attachments, file shares and web uploads can be scanned before a user opens them.
  • Memory. Packed malware is often only readable once it unpacks itself in memory; scanning processes catches what a disk scan of the packed file misses.
  • Threat intelligence. Rules shared by vendors and researchers turn a published report into something you can run against your own estate the same day.

Send YARA hits to the SIEM with the rule name, tags, file path, hash and host, so they can be correlated with the process and network events around them rather than worked as isolated alerts.

A note on naming: Google Security Operations (formerly Chronicle) uses a detection language called YARA-L. It borrows YARA's layout of meta, events and condition sections, but it matches log events, not file bytes, and YARA rules do not run in it unchanged.

Writing rules that don't drown the SOC

A YARA rule that matches on a handful of common strings will match a lot of legitimate software too. Installers, admin tools, security products and developer toolchains contain the same API names, commands and libraries that malware uses. These habits keep false positives down:

  1. Anchor on the file type and size first. A header check such as uint16(0) == 0x5A4D and a filesize limit cheaply rule out most of what the rule should never fire on.
  2. Prefer strings unique to the family. Mutex names, odd typos, custom protocol markers and specific code sequences beat generic strings like VirtualAlloc or cmd.exe, which belong in a condition only alongside something rarer.
  3. Require several indicators. 3 of ($s*) across distinctive strings is sturdier than any single one, and survives an attacker changing one of them.
  4. Avoid short and weak strings. YARA searches for strings before it evaluates conditions, so a two- or three-byte string or an unanchored regex slows every scan however tight the condition. YARA warns when a string slows down scanning; treat that warning as a bug.
  5. Scan a goodware set before deploying. Run new rules over a clean corpus — a standard OS image, your common software and build artefacts — and fix every hit before the rule reaches production.
  6. Separate hunting from alerting. Broad SUSP_ rules are useful for hunting and retro-scanning; page analysts only on rules that have run quietly against your own estate.

Testing and maintaining rules

  • Keep rules in Git, next to a small set of positive samples (or their hashes, where samples can't be stored) and a pointer to the goodware set they were tested against.
  • Compile the whole rule set in CI — with yarac, or yr check for YARA-X — so a syntax error or duplicate rule name fails a pull request instead of a fleet-wide scan.
  • Use -s when testing to see exactly which strings matched; a rule that fires for the wrong reason will fire on the wrong files later.
  • Review rules after each engine upgrade and each new family variant; malware authors change strings precisely because rules key on them.

Where to find rules and documentation

  • YARA documentation — the reference for the rule language, modules and command-line options.
  • YARA-X documentation — the successor engine, including how it differs from YARA.
  • Neo23x0/signature-base — a large, actively maintained rule set from Florian Roth and contributors.
  • YARAHQ/yara-forge — community rules from many repositories, collected, quality-checked and packaged into sets of increasing breadth.
  • elastic/protections-artifacts — the YARA rules Elastic ships with its endpoint protection.
  • Rule sets are published under different licences, some of which restrict commercial use. Read each repository's licence before building its rules into a product or service.

Common questions

Is YARA an antivirus? No. It is a matching engine and a rule language; it reports which rules match and takes no action. Products build blocking, quarantine and alerting on top of it.

YARA or Sigma? Both, for different data. YARA answers "what is this file or process?"; Sigma answers "did this behaviour happen in our logs?". A mature detection programme writes both and links their hits in the SIEM.

Can YARA scan network traffic? Not on its own. Network detection is the job of Suricata or Snort rules; YARA can scan files carved out of traffic once they are written to disk.

Can rules be generated automatically? Tools such as yarGen (Neo23x0/yarGen) propose strings from samples by filtering out those common in goodware. Treat their output as a draft: review every string and test the rule as you would one written by hand.

More on this in Detection Engineering.