TExcelTAD
Home › Malware Analysis, Digital Forensics & Incident Response › YARA Modules: pe, math and hash

YARA Modules: pe, math and hash

Strings only see bytes. Many of the best family traits are structural: "a PE with four sections, one of them named .lab, writable and executable, with entropy above 7.5, importing InternetOpenUrlA". Writing that with uint32() arithmetic would be painful. YARA modules parse the file and expose its structure as fields and functions in conditions: pe for Windows executables, elf and macho for the other formats, math for statistics such as entropy, hash for hashes of the file or a part of it, dotnet for .NET metadata, time for the current time, and others. This lesson rewrites the triage checks of PE Triage as rules.

Definitions

  • Importing a module: import "pe" at the top of the rule file. Each module adds an identifier (pe., math., …).
  • pe fields and functions (a selection): pe.is_pe, pe.machine (pe.MACHINE_AMD64), pe.number_of_sections, pe.sections[i].name, .characteristics, .raw_data_offset, .raw_data_size, .virtual_size; pe.timestamp; pe.entry_point; pe.imports("wininet.dll", "InternetOpenUrlA") (DLL names compared case-insensitively); pe.imphash(); pe.number_of_signatures, pe.is_signed; pe.exports("name"); pe.pdb_path; constants such as pe.SECTION_MEM_EXECUTE and pe.SECTION_MEM_WRITE.
  • math: math.entropy(offset, size) (or of a string), math.mean(), math.serial_correlation(), math.monte_carlo_pi(), math.count(), math.percentage() (YARA 4.2 and later), math.in_range().
  • hash: hash.md5(offset, size), hash.sha1(…), hash.sha256(…), hash.crc32(…): hash a region, for example one section.
  • Iterators over arrays: for any s in pe.sections : ( s.name == ".lab" ) (YARA 4.0 and later; older rules write for any i in (0..pe.number_of_sections - 1) : (pe.sections[i].name == ".lab")).
  • yara -D: prints everything the modules parsed from a file, the best way to see which fields exist and what values they have.

Structural rules on synthetic executables

The session builds two synthetic 64-bit PE files with a real import table (the builder from PE Triage, made into a script): lab.exe, the lab sample with a writable and executable high-entropy .lab section and network and registry imports, and tool.exe, an ordinary-looking console tool with three sections and only file imports. Neither contains working code. Then rules with modules run against both.

bash · try it yourself
cat > build.py <<'PY'
import struct, hashlib, math, random, datetime
from collections import Counter

LAB_IMPORTS = {"KERNEL32.dll": ["CreateFileW", "WriteFile", "VirtualAlloc", "GetComputerNameW"],
               "WININET.dll": ["InternetOpenA", "InternetOpenUrlA", "InternetReadFile"],
               "ADVAPI32.dll": ["RegOpenKeyExW", "RegSetValueExW"]}

def build_rdata(base, IMPORTS):
    """Import directory, lookup tables, hint/name entries and DLL names, laid out from RVA `base`."""
    n = len(IMPORTS)
    desc_size = 20 * (n + 1)
    tables, names, layout = bytearray(), bytearray(), []
    thunk_area = desc_size
    total_thunks = sum(len(f) + 1 for f in IMPORTS.values())
    name_area = thunk_area + 2 * 8 * total_thunks          # ILT + IAT, 8 bytes per entry (PE32+)
    ilt, iat, hn = bytearray(), bytearray(), bytearray()
    for dll, funcs in IMPORTS.items():
        ilt_rva = base + thunk_area + len(ilt)
        iat_rva = base + thunk_area + 8 * total_thunks + len(iat)
        for f in funcs:
            entry = base + name_area + len(hn)
            hn += struct.pack("<H", 0) + f.encode() + b"\0"
            if len(hn) % 2: hn += b"\0"
            ilt += struct.pack("<Q", entry); iat += struct.pack("<Q", entry)
        ilt += bytes(8); iat += bytes(8)
        layout.append((ilt_rva, iat_rva, dll))
    dllnames = bytearray(); name_rvas = []
    for _, _, dll in layout:
        name_rvas.append(base + name_area + len(hn) + len(dllnames))
        dllnames += dll.encode() + b"\0"
    desc = b"".join(struct.pack("<IIIII", i, 0, 0, nm, a) for (i, a, _), nm in zip(layout, name_rvas)) + bytes(20)
    return bytes(desc + ilt + iat + hn + dllnames), desc_size

def build_pe(stamp, imports, packed, note):
    falign, salign, hdr = 0x200, 0x1000, 0x400
    rdata, isize = build_rdata(0x2000, imports)
    secs = [(b".text", 0x1000, 0x60000020, bytes.fromhex("4883ec28") + bytes.fromhex("488d0d00000000e8000000004885c0740a") * 24 + bytes.fromhex("4883c428c3")),
            (b".rdata", 0x2000, 0x40000040, rdata + note),
            (b".data", 0x3000, 0xC0000040, bytes(64)),
            (b".lab", 0x4000, 0xE0000020, random.Random(13).randbytes(0x1000))]   # R W X, random bytes
    if not packed:
        secs = secs[:3]
    dos = bytearray(64); dos[0:2] = b"MZ"; struct.pack_into("<I", dos, 0x3C, 0x80)
    stub = b"\0" * (0x80 - 64)
    coff = struct.pack("<HHIIIHH", 0x8664, len(secs), stamp, 0, 0, 240, 0x0022)
    opt = struct.pack("<HBBIIIIIQIIHHHHHHIIIIHHQQQQII", 0x20B, 14, 40, 0x200, 0x1200, 0, 0x1000, 0x1000,
        0x140000000, salign, falign, 6, 0, 0, 0, 6, 0, 0, 0x5000, hdr, 0, 2, 0x8160,
        0x100000, 0x1000, 0x100000, 0x1000, 0, 16)
    dirs = bytearray(16 * 8); struct.pack_into("<II", dirs, 8, 0x2000, isize)      # directory 1: imports
    table, body, raw = b"", b"", hdr
    for name, rva, flags, content in secs:
        rsize = -(-len(content) // falign) * falign
        table += struct.pack("<8sIIIIIIHHI", name, len(content), rva, rsize, raw, 0, 0, 0, 0, flags)
        body += content.ljust(rsize, b"\0"); raw += rsize
    head = bytes(dos) + stub + b"PE\0\0" + coff + opt + bytes(dirs) + table
    return head.ljust(hdr, b"\0") + body


stamp = int(datetime.datetime(2030, 5, 1, tzinfo=datetime.timezone.utc).timestamp())
open("lab.exe", "wb").write(build_pe(stamp, LAB_IMPORTS, True, b"labagent config v1 server=update.beacon.lab.test\0"))
open("tool.exe", "wb").write(build_pe(1767225600, {"KERNEL32.dll": ["CreateFileW", "ReadFile", "WriteFile",
     "CloseHandle"]}, False, b"lab copy tool 1.0\0"))
PY
python3 build.py
cat > structure.yar <<'RULE'
import "pe"
import "math"
import "hash"

rule PE_rwx_high_entropy_section
{
    condition:
        pe.is_pe and
        for any s in pe.sections : (
            s.characteristics & pe.SECTION_MEM_EXECUTE and s.characteristics & pe.SECTION_MEM_WRITE and
            math.entropy(s.raw_data_offset, s.raw_data_size) > 7.2 )
}

rule PE_downloader_with_registry_writes
{
    condition:
        pe.is_pe and pe.imports("wininet.dll", "InternetOpenUrlA") and pe.imports("wininet.dll", "InternetReadFile")
        and pe.imports("advapi32.dll", "RegSetValueExW")
}

rule LabAgent_imphash
{
    condition:
        pe.imphash() == "b91aa3bc9567e611fd7937cb4ae0e750"
}

rule PE_timestamp_in_future
{
    condition:
        pe.is_pe and pe.timestamp > 1798761600        // 2027-01-01 00:00 UTC
}

rule LabAgent_packed_section_hash
{
    condition:
        for any s in pe.sections : ( s.name == ".lab" and
            hash.sha256(s.raw_data_offset, s.raw_data_size) ==
            "0b7f50e8a8a3d4e2c6e63a0e4bb87c5c4e85fbe3c6b3d9a8a0f00000deadbeef" )
}
RULE
for f in lab.exe tool.exe; do echo "== $f"; yara structure.yar $f | sort; done
echo "== module data for lab.exe (selected fields)"
yara -D structure.yar lab.exe | grep -P '^\t(number_of_sections|timestamp|entry_point|is_signed) =|^\t\t\t(name|raw_data_offset) = |library_name'
echo "== the .lab section's real SHA-256 (for the last rule)"
python3 -c "import hashlib; d=open('lab.exe','rb').read(); print(hashlib.sha256(d[0xa00:0xa00+0x1000]).hexdigest())"
== lab.exe
LabAgent_imphash lab.exe
PE_downloader_with_registry_writes lab.exe
PE_rwx_high_entropy_section lab.exe
PE_timestamp_in_future lab.exe
== tool.exe
== module data for lab.exe (selected fields)
	is_signed = 0
			library_name = "KERNEL32.dll"
			library_name = "WININET.dll"
			library_name = "ADVAPI32.dll"
			name = ".text"
			raw_data_offset = 1024
			name = ".rdata"
			raw_data_offset = 1536
			name = ".data"
			raw_data_offset = 2048
			name = ".lab"
			raw_data_offset = 2560
	entry_point = 1024
	timestamp = 1903824000
	number_of_sections = 4
== the .lab section's real SHA-256 (for the last rule)
25b47977e16188fde57a6d87c2a6bc13b3cd48f3efaef250a4770b98f5b741df

What each rule shows:

  • PE_rwx_high_entropy_section expresses three triage findings in one loop: executable, writable and near-random content. It matches lab.exe only.
  • PE_downloader_with_registry_writes matches an import combination, written with lowercase DLL names; pe.imports() ignores case in the DLL name.
  • LabAgent_imphash matches the value computed by hand and by pefile in the triage lesson.
  • PE_timestamp_in_future compares the linker timestamp with a fixed date. YARA's time.now() (in the time module) could compare with the scan time, but a fixed date keeps the rule's behaviour reproducible.
  • LabAgent_packed_section_hash matches nothing, on purpose: the value in the rule is a made-up placeholder. The session prints the real SHA-256 of the section (its raw data starts at file offset 2560 = 0xa00, as yara -D shows), which is what you would paste in. Section hashes survive changes elsewhere in the file but break with every new packing key.

How module rules are used for detection

  • Hunting rules describe structure that is rare in goodware (RWX high-entropy sections, few imports with LoadLibrary/GetProcAddress only, an invalid checksum in a signed-looking file) and feed analysts' queues rather than blocking.
  • Family rules combine structure with strings: pe.imphash() or an import set plus the family's configuration marker.
  • Triage of a disk or a sample store: yara -r with structural rules sorts thousands of executables into "look at these first".

How to keep module rules reliable

  • Check the field values with yara -D on a known sample before writing the condition.
  • Guard with pe.is_pe (or uint16(0) == 0x5A4D) so the rule is cheap on non-PE files.
  • Prefer ranges to exact values for counts and sizes, which vary across builds.
  • Note the minimum YARA version in meta when you use newer features (iterators, math.count).

Pitfalls

  • Malformed files. Malware often has broken headers; a module may fail to parse a file that Windows still runs, and then fields are undefined and comparisons with them are false. Keep a string-based fallback.
  • Negations match everything else. not pe.is_signed is true for every text file, image and archive too; guard negated conditions with pe.is_pe, and test rules on non-PE files.
  • Performance. math.entropy() over the whole of a large file in every rule is slow; restrict it to sections and to PE files.
  • imphash as identity. Shared toolchains give shared imphashes; combine it with something family-specific.

Practice

1. Write a condition that matches a PE whose entry point lies in the last section.

pe.is_pe and pe.entry_point >= pe.sections[pe.number_of_sections - 1].raw_data_offset. (pe.entry_point is a file offset when scanning files; an entry point in the last section is a common sign of packers and appended code.)

2. Why does the rule use s.characteristics & pe.SECTION_MEM_WRITE instead of ==?

Characteristics is a bit field with several flags set at once (code, read, write, execute); the & tests one bit regardless of the others.

3. Replace the placeholder in LabAgent_packed_section_hash with the printed value. Which file matches, and what breaks the rule?

lab.exe matches. Any change to the .lab section's bytes breaks it: a new packing key, a different payload, even one byte. It is an exact hash of a part, more robust than the file hash but still brittle.

Test yourself

Which command shows every field a module parsed from a file?

  1. yara -s
  2. yara -D
  3. yara -m
  4. yara -n

What does math.entropy(s.raw_data_offset, s.raw_data_size) compute?

  1. The section's SHA-256
  2. The Shannon entropy of the section's raw bytes
  3. The number of imports
  4. The section's virtual size

Why did LabAgent_packed_section_hash match nothing in the session?

  1. The hash module is not installed
  2. The hash in the rule was a placeholder that doesn't equal the section's real SHA-256
  3. tool.exe was scanned first
  4. Sections cannot be hashed

What happens to a pe-based condition when the file is too malformed for the module to parse?

  1. YARA crashes
  2. The fields are undefined and comparisons with them evaluate to false
  3. The rule always matches
  4. YARA repairs the file