All posts
TutorialJuly 6, 20267 min read

YARA rules in 10 minutes

Write your first YARA rule, understand strings and conditions, and learn why most beginner rules are far too fragile to survive a repack.

Malware Analysis Academy

Editorial team

YARA is pattern matching for files. You describe what a malware family looks like, and YARA tells you which files match. That is the whole idea.

The anatomy of a rule

rule Example_Loader
{
    meta:
        author      = "analyst"
        description = "Example loader family"

    strings:
        $ua   = "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
        $path = "\\Microsoft\\Windows\\CurrentVersion\\Run"
        $mz   = { 4D 5A 90 00 }

    condition:
        $mz at 0 and all of ($ua, $path)
}

Three sections:

  • meta — free-form documentation. It does not affect matching, but future-you will want it.
  • strings — the things to look for: text, hex byte sequences, or regular expressions.
  • condition — the boolean logic that decides a match.

Text, hex, and regex

$text  = "InternetOpenA"           // ASCII by default
$wide  = "InternetOpenA" wide      // UTF-16, very common in Windows binaries
$nocase = "powershell" nocase      // case-insensitive
$hex   = { 6A 40 68 00 30 00 00 }  // raw bytes
$re    = /https?:\/\/[a-z0-9.]+\/gate\.php/

The wide modifier catches more real-world malware than beginners expect — Windows APIs are full of UTF-16 strings, and an ASCII-only rule silently misses them.

Conditions are where rules get good

condition:
    uint16(0) == 0x5A4D          // it is a PE file
    and filesize < 2MB           // cheap early exit
    and 3 of ($str*)             // resilient: any 3 of a group

3 of ($str*) is the important pattern. Requiring all strings makes a rule that breaks the moment the author changes one URL. Requiring some of a group survives minor variation.

Why most beginner rules are bad

The classic mistake is matching on something incidental — a compiler artefact, a common library string, or a single hardcoded domain. Such a rule either:

  • breaks immediately when the sample is repacked, or
  • fires constantly on benign files.

Good rules target things the author cannot cheaply change: distinctive decryption routines, unusual API call combinations, or structural quirks in the binary.

Testing

yara -r rules.yar /path/to/samples/    # scan recursively
yara -s rules.yar suspicious.bin       # -s shows which strings matched

Always test against benign files too. A rule you have only tested on malware has an unknown false-positive rate, which in production is the same as an unusable rule.

#yara#detection#signatures

Keep reading