YARA Rules: Strings and Conditions
A hash identifies one file; the analyst wants to identify a family: every build of the lab sample, past and future, whatever its hash. YARA ("the pattern matching swiss knife for malware researchers", created by Victor Alvarez at VirusTotal) does that with rules that describe what the files have in common: strings, byte patterns with wildcards, regular expressions, and a boolean condition over them, file size and file structure. YARA rules run in EDR products, mail gateways, sandboxes, memory scanners and forensic tools, and they are the most widely shared detection format for files. Security Foundations showed the EICAR rule; this lesson writes a real one.
Anatomy of a rule
rule LabAgent_config : lab rat // name and optional tags
{
meta: // free key = value pairs; not used for matching
author = "ExcelTAD lab"
strings: // what to look for
$magic = "LABAGENT-CFG"
$code = { 48 83 EC 28 E8 ?? ?? ?? ?? 85 C0 74 ?? }
$re = /beacon\.[a-z]+\.test/
condition: // when the rule matches
uint16(0) == 0x5A4D and $magic and ($code or $re)
}Strings come in three kinds:
| Kind | Syntax | Notes |
|---|---|---|
| Text | "LABAGENT-CFG" |
modifiers: nocase, wide (UTF-16LE), ascii (the default, needed together with wide to match both), fullword (delimited by non-alphanumerics), xor (every single-byte XOR key from 0x00, so the plaintext matches too) or a key range such as xor(0x01-0xff), base64 / base64wide, private |
| Hex | { 48 83 EC 28 E8 ?? ?? ?? ?? } |
?? any byte, 4? a nibble wildcard, [2-4] a jump of 2 to 4 bytes, ( 74 | 75 ) alternatives. Ideal for code bytes with variable addresses |
| Regular expression | /beacon\.[a-z]+\.test/ |
powerful but slower; keep them anchored to a literal part |
Conditions combine:
- string tests:
$a(present),#a > 3(count),@a[1](offset of the first match),$a at 0x100,$a in (0..1024); - sets:
any of them,all of ($cfg*),2 of ($a, $b, $c),none of ($x*), and loopsfor any i in (1..#a) : (@a[i] < 0x400); - file properties:
filesize < 100KB, integers read from the fileuint16(0) == 0x5A4D(little-endian;uint32be()for big-endian), and module functions (next lesson).
Writing and running a rule
The session builds two synthetic builds of the lab sample (benign blobs: a PE-like header, a configuration marker, the configuration XOR-encoded with a different key in each build, a UTF-16 mutex name, a few code-like bytes, a Base64 fragment) and a text file of notes that mentions the same names, then runs a rule against all of them and the EICAR test file.
mkdir samples && python3 - <<'PY'
import base64, random
r = random.Random(21)
cfg = b"server=update.beacon.lab.test;port=8080;interval=60"
a = (b"MZ" + bytes(62) + r.randbytes(300) + b"LABAGENT-CFG\x01" + bytes(c ^ 0x5C for c in cfg)
+ r.randbytes(200) + "Global\\LabAgent-Mutex-7f3a".encode("utf-16-le") + b"\0\0"
+ bytes.fromhex("4883EC28E8") + bytes(4) + bytes.fromhex("85C0740A") + r.randbytes(100)
+ base64.b64encode(b"ua=LabAgent/1.0;sleep=60") + b"\0" + r.randbytes(300))
open("samples/agent-a.bin", "wb").write(a)
b = a.replace(b"CFG\x01", b"CFG\x02").replace(bytes(c ^ 0x5C for c in cfg), bytes(c ^ 0x21 for c in cfg))
open("samples/agent-b.bin", "wb").write(b)
open("samples/notes.txt", "w").write("Notes: the lab agent talks to update.beacon.lab.test, mutex LabAgent-Mutex-7f3a.\n")
PY
cp $SAMPLES/files/eicar.com samples/
cat > lab.yar <<'RULE'
rule LabAgent_config
{
meta:
author = "ExcelTAD lab"
description = "LabAgent benign lab sample: configuration marker plus two family traits"
date = "2026-01-15"
strings:
$magic = "LABAGENT-CFG"
$dom = "update.beacon.lab.test" xor(0x01-0xff)
$mutex = "LabAgent-Mutex-7f3a" wide
$ua = "ua=LabAgent/" base64
$code = { 48 83 EC 28 E8 ?? ?? ?? ?? 85 C0 74 ?? }
condition:
uint16(0) == 0x5A4D and filesize < 100KB and $magic and 2 of ($dom, $mutex, $ua, $code)
}
rule LabAgent_mentioned_in_text
{
strings:
$m = "LabAgent-Mutex-7f3a" ascii
condition:
$m and uint16(0) != 0x5A4D
}
RULE
echo "== one sample, with matching strings (-s)"
yara -s lab.yar samples/agent-a.bin
echo "== build b: different XOR key"
yara -s lab.yar samples/agent-b.bin | grep -e '^Lab' -e 'dom'
echo "== the whole folder, with metadata (-m)"
yara -m lab.yar samples | sort
echo "== negated (-n): each rule with the files it does NOT match"
yara -n lab.yar samples | sort== one sample, with matching strings (-s)
LabAgent_config samples/agent-a.bin
0x16c:$magic: LABAGENT-CFG
0x180:$dom: ),8=(9r>9=?32r0=>r(9/(
0x282:$mutex: L\x00a\x00b\x00A\x00g\x00e\x00n\x00t\x00-\x00M\x00u\x00t\x00e\x00x\x00-\x007\x00f\x003\x00a\x00
0x31b:$ua: dWE9TGFiQWdlbnQv
0x2aa:$code: 48 83 EC 28 E8 00 00 00 00 85 C0 74 0A
== build b: different XOR key
LabAgent_config samples/agent-b.bin
0x180:$dom: TQE@UD\x0FCD@BNO\x0FM@C\x0FUDRU
== the whole folder, with metadata (-m)
LabAgent_config [author="ExcelTAD lab",description="LabAgent benign lab sample: configuration marker plus two family traits",date="2026-01-15"] samples/agent-a.bin
LabAgent_config [author="ExcelTAD lab",description="LabAgent benign lab sample: configuration marker plus two family traits",date="2026-01-15"] samples/agent-b.bin
LabAgent_mentioned_in_text [] samples/notes.txt
== negated (-n): each rule with the files it does NOT match
LabAgent_config samples/eicar.com
LabAgent_config samples/notes.txt
LabAgent_mentioned_in_text samples/agent-a.bin
LabAgent_mentioned_in_text samples/agent-b.bin
LabAgent_mentioned_in_text samples/eicar.com
Read the -s output carefully:
$dommatched encoded bytes at0x180: YARA tried every XOR key from0x01to0xffand found the domain under0x5cin build A and under0x21in build B. One plaintext string catches both builds and every other single-byte key.$mutexmatched the UTF-16 bytes (L\x00a\x00…), thanks towide.$uamatched the Base64 textdWE9TGFiQWdlbnQv:base64searches for the three possible Base64 alignments of the string.$codematched with the four wildcard bytes filled in by whatever the file contains:00 00 00 00here, a call offset in real code.- The notes file matches only the second rule, because the first one requires the
MZmagic, the marker and two traits.-ninverts the output: for each rule, the files it did not match. EICAR appears under both rules, so nothing matched it, which is correct for these rules.
How rules detect, and how they go wrong
YARA is a detection language: it decides whether a file belongs to a family. A good rule is:
- specific to the family (strings that legitimate software doesn't contain, combined),
- robust to rebuilds (no hashes, no build-specific values like the campaign byte after the marker, which this rule deliberately ignores),
- fast (a cheap condition first, long and rare strings rather than short common ones).
It must be tested against goodware before it ships: a rule that fires on a system DLL causes an outage when an EDR quarantines it (testing rules).
Where rules are deployed
- EDR and anti-virus engines that accept custom YARA rules; mail and web gateways on attachments and downloads.
- Retro-hunts over sample repositories (VirusTotal Retrohunt, internal stores).
- Memory scans of running processes, which find unpacked payloads that never touch the disk (memory forensics).
- Forensic triage of seized disks (
yara -r rules.yar /mnt/evidence).
Pitfalls
- Matching your own notes. Analysts' write-ups, rule files and threat reports contain the strings; scope rules with a file-type check, as the first rule does.
- Too few strings. One string of 6 characters will match random data in large files sooner or later.
xorandbase64cost: they multiply the patterns YARA searches for; use them on specific strings, not on short common words.- Wide without ascii.
widealone matches only UTF-16; writeascii wideto match both forms. - Little-endian surprises.
uint32(0) == 0x464C457Fis\x7fELF; write the bytes in reverse order, or useuint32be.
Practice
1. Write a condition that requires the marker in the first kilobyte and at least two matches of the mutex.
$magic in (0..1024) and #mutex >= 2.
2. Why does the rule not include the byte after LABAGENT-CFG?
It differs between builds (01 and 02, a campaign or version byte). Including it would make the rule match one build only; robust rules avoid build-specific values.
3. Write a hex string that matches 74 0A or 75 0A after 85 C0, with one to three arbitrary bytes in between.
{ 85 C0 [1-3] ( 74 | 75 ) 0A }.
Test yourself
What does the YARA modifier wide do?
- Matches the string case-insensitively
- Matches the string encoded as UTF-16LE (each character followed by a zero byte)
- Allows jumps
- Matches any XOR key
In a hex string, what does ?? mean?
- Two zero bytes
- Any single byte
- A comment
- The end of the string
How did one rule match the domain in two builds encoded with different keys?
- With nocase
- With the xor modifier, which tries every single-byte key in the given range
- With base64
- With a regular expression
Why does the first rule test uint16(0) == 0x5A4D?
- To check the file is signed
- To restrict it to files starting with MZ, so notes and reports that mention the strings don't match, and to make scanning faster
- To read the PE timestamp
- It is required syntax