Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 37 ยท Behavioural Indicators and YARA

YARA Rule Basics: Strings, Conditions and Metadata

Learn the structure of a YARA rule: meta, text, hex and regex strings, modifiers and simple conditions, with a runnable Python stand-in that mimics rule matching.

A file hash finds exactly one file. A YARA rule finds a family: every file that contains certain strings or byte patterns, however the surrounding bytes differ. YARA is often called "the pattern-matching Swiss army knife for malware researchers". You write rules that describe what you saw in a sample, then scan folders, memory dumps or whole file collections to find related files.

The real YARA engine cannot run on this site, so rules appear as read-only examples. To let you practise the logic, the lesson ends with a Python stand-in that mimics a small part of how YARA evaluates strings and conditions on a made-up byte buffer. It is a teaching model, not YARA: it has no modules, no performance tricks and a much smaller feature set.

Anatomy of a rule

meta Author, date, description.
strings Text, hex or regex patterns.
condition When the rule matches.

Only the condition is required.

1 / 2

The shape of a rule

Here is a complete rule, written for the made-up family "DemoLoader" used throughout this chapter:

TEXT
rule DemoLoader_Family
{
    meta:
        description = "Detects the invented DemoLoader sample family"
        author      = "Training example"
        date        = "2026-01-15"
        reference   = "internal case 1042"

    strings:
        $mutex  = "demo_instance_" ascii
        $path   = "\\Public\\demo\\" ascii wide nocase
        $url    = /http:\/\/[a-z0-9.-]+\.invalid\/gate/ ascii
        $decode = { 8A 04 0E 34 ?? 88 04 0F 41 }   // XOR loop with an unknown key byte

    condition:
        uint16(0) == 0x5A4D and
        filesize < 2MB and
        ( $decode or 2 of ($mutex, $path, $url) )
}

A rule has a name, optional meta fields (free-form documentation), a strings section that defines named patterns starting with $, and a condition, a Boolean expression over those patterns and file properties. The rule matches a file when the condition is true.

Three kinds of string

Text strings are written in double quotes. By default they are ASCII and case-sensitive. Useful modifiers follow the string:

  • nocase ignores case.
  • wide also matches UTF-16LE (each character followed by a zero byte), common in Windows programs.
  • ascii matches plain bytes; use both ascii wide to match either form.
  • fullword requires non-alphanumeric characters on both sides.
  • xor (and base64) match the string as encoded that way, so one rule can find a single-byte-XORed copy.

Hexadecimal strings go in braces and describe raw bytes. They support wildcards ?? (any byte), jumps [2-6] (between two and six unknown bytes) and alternatives ( 8B | 89 ). They are ideal for matching a short stretch of code, such as the decoder loop above.

Regular expressions go between slashes. They are powerful but slower and easier to make too broad, so use them when a text or hex string cannot express the pattern.

Conditions

The condition combines tests with and, or, not and parentheses. The most common pieces:

Piece Meaning
$a the string $a occurs at least once
#a > 3 $a occurs more than 3 times
$a at 0 $a is exactly at offset 0
$a in (0..1024) $a occurs in the first kilobyte
any of them / all of them at least one / every defined string
2 of ($a, $b, $c) at least two of the listed strings
filesize < 2MB file size check (units KB, MB)
uint16(0) == 0x5A4D the first two bytes are MZ, the PE header magic
uint32(uint32(0x3C)) == 0x00004550 the PE signature PE\0\0 is where the header says

Using the magic number check first makes the rule cheap on non-executables, since YARA can bail out early. Using several weak indicators with 2 of (...) reduces false positives compared with a single common string.

Rule quality: what to match

Poor rules match easily changed things: file names, a single common API name, or text such as "Microsoft Corporation". Better rules match things the author is unlikely to change and that are unlikely in clean software:

  • Unique error or debug messages, internal project paths (C:\build\demo\loader.pdb) and mutex names.
  • Rare combinations of strings.
  • Compiled code of the core algorithm (decoder, command parser), written as hex with wildcards for relocated addresses.
  • Constants such as a custom hash seed or an encryption S-box.

Tuning and testing rules covers how to check a rule against known-good files.

A YARA-style matcher in Python

The stand-in below implements three things from the list: text strings with nocase and wide, hex patterns with ?? wildcards, and conditions of the form n of (...). The buffer is generated in the program. Run it, then change the buffer and the rule to see the match result change.

Python Mimic YARA string matching and conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The $decode pattern matches because the wildcard accepts the unknown key byte A7, and the $path string is found even though the file stores it as UTF-16 and in different case, thanks to wide and nocase. Delete the decoder bytes and the mutex from the buffer and the condition falls to False, because 2 of (...) is no longer satisfied.

Reading a hit count

The #a operator counts occurrences. It lets you write rules such as "the string Invoke- appears at least 5 times in a script file". The stand-in below counts matches and applies positional checks (at and in) to the same style of buffer.

Python Counts and offsets: #a, at and in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Running YARA for real

On your own lab machine, after installing YARA, a typical session looks like this (read-only example, output invented):

TEXT
$ yara -s -r rules/demoloader.yar samples/
DemoLoader_Family samples/case1042/dropper.bin
0x24:$mutex: demo_instance_
0x3d:$path: \x00C\x00:\x00\\x00P\x00u\x00b\x00l\x00i\x00c\x00

-r scans folders recursively, -s prints the matching strings and their offsets, and -m prints the metadata. In production, rules are compiled once (yarac) and run by endpoint tools, mail gateways, sandboxes and platforms like VirusTotal's retrohunt.

Write every rule with a description and a reference to the case or report. Six months later the rule will fire on something unexpected, and the meta fields are what let the next analyst understand why it exists.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which part of a YARA rule is required?

    Only the condition is mandatory; a rule can rely purely on file properties, though most also have strings.
  2. 2. What does the wide modifier do?

    Windows programs commonly store text as UTF-16LE, which wide handles.
  3. 3. What does 2 of ($a, $b, $c) mean?

    The expression counts how many of the listed strings were found.
  4. 4. Why start a PE rule's condition with uint16(0) == 0x5A4D?

    An early cheap check improves performance and avoids false positives on non-PE files.

Summary

  • A YARA rule has optional meta, optional strings and a required condition.
  • Strings can be text (with nocase, wide, xor...), hex with ?? wildcards and jumps, or regex.
  • Conditions combine counts, offsets, n of (...), file size and header checks.
  • Good rules target durable, distinctive artefacts; use several weak signals together.
  • The Python matcher is a simplified teaching model; real YARA runs on your own lab machine.
  • Document each rule with description, author, date and reference.

Next: YARA Conditions and Rule Tuning