Ultimate YARA Cheat Sheet



Ultimate YARA Cheat Sheet

The pattern matching swiss knife for malware researchers.

1. Basic Rule Structure

A standard YARA rule consists of three sections: Meta, Strings, and Condition.

rule Example_Rule_Name { meta: author = "Your Name" description = "Detects malicious hex code" date = "2023-10-25" strings: $text_string = "suspicious_function" $hex_string = { E2 34 A1 C8 23 FB } condition: $text_string or $hex_string }
Key Concept: The rule name cannot start with a number. The condition section is the only mandatory part (it must evaluate to Boolean True or False).

2. Strings & Modifiers

Defining what you are looking for in the file.

String Types

TypeSyntaxDescription
Text$s = "text"Standard ASCII string.
Hex$h = { 00 FF A1 }Raw bytes. Wildcards ? allowed (e.g., { 00 ?F }).
Regex$r = /md5: [0-9a-f]{32}/Regular expressions.

String Modifiers

Append these after the string definition to change how YARA searches.

strings: $a = "http" nocase // Case insensitive (HTTP, http) $b = "login" wide // Unicode (l\x00o\x00g\x00...) $c = "admin" ascii // ASCII (default) $d = "pass" fullword // Matches "pass" but not "password" $e = "hacked" xor // Searches for XOR-encoded version

3. Conditions

The logic that triggers the rule. Boolean operators: and, or, not.

Counting Strings

Use #variable to count occurrences.

condition: #text_string > 3 // String appears more than 3 times

File Size

condition: filesize < 5MB

At Specific Offset

condition: $magic_bytes at 0 // Must be at the very start of file

Sets of Strings

condition: 2 of ($a, $b, $c) // Any 2 of these specific strings any of them // Any string defined in the Strings section all of them // All strings must be present

4. Modules (PE, ELF, Magic)

YARA can analyze specific file formats using importable modules. You must add import "module_name" at the top.

PE Module (Windows Executables)

import "pe" rule Detect_DLL_Injection { condition: pe.number_of_sections > 3 and pe.imports("kernel32.dll", "CreateRemoteThread") }

Magic Module (File Types)

Detect file type based on libmagic (better than extensions).

import "magic" rule PDF_File { condition: magic.mime_type() == "application/pdf" }

Hash Module

Match specific full-file hashes.

import "hash" rule Known_Malware { condition: hash.md5(0, filesize) == "5d41402abc4b2a76b9719d911017c592" }

5. Command Line Usage

How to run YARA against files on your system.

Basic Scan

Scan a single file with a rule file.

yara my_rules.yar malware.exe

Scan Directory

Recursively scan a folder.

yara -r my_rules.yar /path/to/directory/

Useful Flags

FlagDescription
-sPrint matching strings (shows exactly what triggered the rule).
-nPrint logical negation (show rules that did NOT match).
-wDisable warnings.
-CCompile rules (check syntax errors before running).