TExcelTAD

A Mini YARA Matcher in Python

YARA rules can feel like magic until you see how little is needed to evaluate one. Writing a small matcher is the best way to understand what a rule means: what wide does to the bytes, why ?? costs nothing, what 2 of ($a*) counts, and why a condition is evaluated only after every string has been searched. This lesson implements a subset of YARA in about 120 lines of Python, using real YARA syntax, and checks it against the results the real yara 4.5.0 gave in YARA Rules: Strings and Conditions.

It is a teaching tool: the real engine compiles all strings into an Aho–Corasick automaton of short atoms, scans the file once, verifies candidate matches, and supports far more syntax. Use real YARA for real work.

The design

  1. Parse each rule name { strings: … condition: … } block.
  2. Compile every string to a regular expression over bytes: a text string becomes its escaped bytes (plus a UTF-16LE form for wide, case-insensitive for nocase); a hex string becomes . for ??, a character class for a nibble wildcard such as 7?, .{n,m} for a jump [n-m], and (?:…|…) for alternatives; a /regex/ stays a regex.
  3. Search: find every match offset of every string (YARA also searches all strings first, then evaluates).
  4. Evaluate the condition with a small recursive-descent parser: or binds weaker than and, which binds weaker than not; terms are $a, $a at N, #a > N, any/all/none/N of them or of ($a*), filesize, uint8/16/32(offset) and integer comparisons with KB/MB suffixes.

The matcher

The test data are the lab sample (the same synthetic bytes as in the YARA lesson), the notes file, and a stand-in for the EICAR test file: only its last 40 bytes after a 28-byte placeholder, enough for the rule's $s at 28 test. (The real 68-byte file is in the sandbox at $SAMPLES/files/eicar.com; lesson pages don't embed it, so that anti-virus products don't flag the page.)

python · try it yourself
import re, struct, base64, random

def compile_string(value, mods):
    """Turn one YARA string into a compiled bytes regex."""
    if value.startswith("{"):                                     # hex string
        out = []
        for tok in re.findall(r"\?\?|\[\d+-\d+\]|\[\d+\]|[0-9A-Fa-f?]{2}|\(|\)|\|", value[1:-1]):
            if tok == "??":            out.append(b".")
            elif tok.startswith("["):  lo, _, hi = tok[1:-1].partition("-"); out.append(b".{%s,%s}" % (lo.encode(), (hi or lo).encode()))
            elif tok in "()|":         out.append(b"(?:" if tok == "(" else tok.encode())
            elif "?" in tok:           # one nibble wildcard, e.g. 7? = 70..7F
                vals = [v for v in range(256) if all(p == "?" or p == c for p, c in zip(tok.upper(), f"{v:02X}"))]
                out.append(b"[" + b"".join(re.escape(bytes([v])) for v in vals) + b"]")
            else:                      out.append(re.escape(bytes.fromhex(tok)))
        return re.compile(b"".join(out), re.S)
    if value.startswith("/"):                                     # regular expression
        return re.compile(value[1:value.rindex("/")].encode(), re.S)
    text = value[1:-1].encode().decode("unicode_escape").encode("latin-1")
    forms = []
    if "wide" in mods: forms.append(b"".join(re.escape(bytes([c])) + b"\x00" for c in text))
    if "ascii" in mods or "wide" not in mods: forms.append(re.escape(text))
    return re.compile(b"|".join(forms), re.S | (re.I if "nocase" in mods else 0))

def parse_rules(src):
    rules = []
    for name, body in re.findall(r"rule\s+(\w+)[^{]*\{(.*?)\n\}", src, re.S):
        strings = {}
        sec = re.search(r"strings:(.*?)condition:", body, re.S)
        for line in (sec.group(1).strip().splitlines() if sec else []):
            m = re.match(r"\s*(\$\w*)\s*=\s*(\".*?\"|\{.*?\}|/.*/)\s*(.*)", line)
            strings[m.group(1)] = compile_string(m.group(2), m.group(3).split())
        cond = body.split("condition:")[1].strip()
        rules.append((name, strings, cond))
    return rules

TOKEN = re.compile(r"\s*(0x[0-9A-Fa-f]+|\d+(?:KB|MB)?|[#$@]\w*\*?|\w+|==|!=|<=|>=|[<>()(),])")

def evaluate(cond, strings, data):
    toks = TOKEN.findall(cond)
    hits = {k: [m.start() for m in rx.finditer(data)] for k, rx in strings.items()}
    pos = 0
    def peek(): return toks[pos] if pos < len(toks) else None
    def take(expect=None):
        nonlocal pos
        t = toks[pos]; pos += 1
        if expect and t != expect: raise SyntaxError(f"expected {expect}, got {t}")
        return t
    def number(t):
        if t.startswith("0x"): return int(t, 16)
        return int(t[:-2]) * (1024 if t.endswith("KB") else 1024 * 1024) if t[-2:] in ("KB", "MB") else int(t)
    def value():                                                  # integer-valued terms
        t = take()
        if t == "filesize": return len(data)
        if t.startswith("#"): return len(hits["
quot; + t[1:]]) if t in ("uint8", "uint16", "uint32"): take("("); off = number(take()); take(")") size = {"uint8": 1, "uint16": 2, "uint32": 4}[t] return int.from_bytes(data[off:off + size], "little") if off + size <= len(data) else None return number(t) def string_set(): if peek() == "them": take(); return list(strings) take("("); names = [] while peek() != ")": t = take() if t == ",": continue names += [k for k in strings if k.startswith(t[:-1])] if t.endswith("*") else [t] take(")"); return names def primary(): t = peek() if t == "(": take(); v = expr(); take(")"); return v if t == "not": take(); return not primary() if t in ("any", "all", "none") or (t and t.isdigit() and toks[pos + 1] == "of"): q = take(); take("of"); names = string_set() n = sum(bool(hits[k]) for k in names) return {"any": n >= 1, "all": n == len(names), "none": n == 0}.get(q, n >= int(q) if q.isdigit() else False) if t.startswith("
quot;): take() if peek() == "at": take(); return number(take()) in hits[t] return bool(hits[t]) left = value(); op = take(); right = value() if left is None: return False return {"==": left == right, "!=": left != right, "<": left < right, ">": left > right, "<=": left <= right, ">=": left >= right}[op] def conj(): v = primary() while peek() == "and": take(); r = primary(); v = v and r return v def expr(): v = conj() while peek() == "or": take(); r = conj(); v = v or r return v result = expr() if pos != len(toks): raise SyntaxError(f"unexpected token {toks[pos]!r}") return result, {k: v for k, v in hits.items() if v} 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)) files = {"agent-a.bin": a, "notes.txt": b"Notes: the lab agent talks to update.beacon.lab.test, mutex LabAgent-Mutex-7f3a.\n", "eicar-standin.com": b"[a 28-byte stand-in prefix.]EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*"} RULES = r''' rule LabAgent_core { strings: $magic = "LABAGENT-CFG" $mutex = "LabAgent-Mutex-7f3a" wide $code = { 48 83 EC 28 E8 ?? ?? ?? ?? 85 C0 7? [1-2] } condition: uint16(0) == 0x5A4D and filesize < 100KB and $magic and ($mutex or $code) } rule LabAgent_mentioned_in_text { strings: $m = "labagent-mutex-7f3a" nocase condition: $m and not uint16(0) == 0x5A4D } rule eicar_test_file { strings: $s = "EICAR-STANDARD-ANTIVIRUS-TEST-FILE!" condition: $s at 28 and filesize < 128 } ''' rules = parse_rules(RULES) for fname, data in files.items(): for name, strings, cond in rules: ok, hits = evaluate(cond, strings, data) if ok: print(f"{name} {fname} " + " ".join(f"{k}@{[hex(o) for o in v]}" for k, v in hits.items())) try: evaluate("$magic and and", rules[0][1], a) except (SyntaxError, IndexError, ValueError) as e: print("syntax error caught:", type(e).__name__, e)
LabAgent_core agent-a.bin  $magic@['0x16c']  $mutex@['0x282']  $code@['0x2aa']
LabAgent_mentioned_in_text notes.txt  $m@['0x3c']
eicar_test_file eicar-standin.com  $s@['0x1c']
syntax error caught: ValueError invalid literal for int() with base 10: 'and'

The offsets are the ones the real YARA printed for the same bytes: $magic at 0x16c, $mutex at 0x282, $code at 0x2aa. The rule here is slightly different from the original (a nibble wildcard 7? and a jump [1-2] replace 74 ??, and the text rule uses nocase), so the example exercises more syntax. The last line shows the parser refusing a malformed condition; YARA's compiler does the same, with a line number, before any file is scanned.

What the implementation teaches about real rules

  • A wildcard is cheap, a short string is not. ?? only widens a regular expression; the cost of a rule is dominated by strings that occur often (a 2-byte string matches everywhere). Real YARA warns when a string has no good atom ("string $a may slow down scanning").
  • Conditions are evaluated after the search. Putting uint16(0) == 0x5A4D first doesn't stop the string search here, and in YARA it helps only partly (YARA can skip evaluating, but the scan already happened); what makes rules fast is specific strings.
  • wide is literally "every byte followed by a zero byte", which is why it only matches UTF-16 text in the Latin-1 range.
  • Undefined values: uint16(0) on an empty file has no value; this matcher returns False for the comparison, like YARA does for undefined operands.

How this helps in detection work

Analysts write small evaluators like this when they need YARA-like matching where YARA isn't available (inside a log pipeline, a browser tool, a test harness), and, more often, to test their rules: a rule that should match the training samples and not the goodware corpus is a unit test (testing rules).

Pitfalls of a home-made matcher

  • Regex back-tracking: large jumps ([0-1000]) and nested quantifiers can make Python's regular expressions very slow; YARA limits jumps for the same reason.
  • Overlapping matches: finditer returns non-overlapping matches only; YARA counts overlapping ones in #a. A string like "aa" in "aaaa" is 2 here, 3 in YARA.
  • Subset semantics: anything this matcher doesn't parse (modules, for loops, in ranges, xor, base64) raises an error or, worse, evaluates differently. Always test against real YARA before trusting it.

Practice

1. Add the fullword modifier.

Wrap the compiled pattern in a look-behind and look-ahead for non-alphanumerics: re.compile(rb"(?<![A-Za-z0-9])(?:" + pattern + rb")(?![A-Za-z0-9])") when "fullword" is in mods.

2. Make #a count overlapping matches, as YARA does.

Search with a look-ahead: compile (?=(pattern)) and use m.start() from finditer, which advances one byte at a time and therefore finds overlapping occurrences.

3. Add $a in (lo..hi).

In primary(), after reading a string identifier, handle peek() == "in": take in, (, a number, the .. token (add \.\. to the tokenizer), a number and ), then return any(lo <= o <= hi for o in hits[t]).

Test yourself

What does the hex token [2-4] become in the matcher's regular expression?

  1. Two to four zero bytes
  2. Any 2 to 4 bytes: .{2,4}
  3. The bytes 02, 03, 04
  4. A comment

In what order does the matcher (like YARA) work?

  1. Condition first, then strings only if needed
  2. Search all strings, then evaluate the condition
  3. One string at a time, stopping at the first match
  4. Hash the file, then compare

Why does this lesson use a stand-in for the EICAR file instead of the real string?

  1. Python cannot store it
  2. So that anti-virus products don't flag the lesson page itself
  3. The real file is not 68 bytes
  4. YARA cannot match it

How does "aa" in "aaaa" count with Python's finditer, and in YARA's #a?

  1. 2 and 3
  2. 3 and 2
  3. 1 and 1
  4. 4 and 4