YARA-X: A Rust-Based Pattern Matching Engine
#yara-x#yara#rust#malware-detection#pattern-matching
Contents
When detecting malicious files, the most widely used and simplest method is hash matching.
It matches the hash of the file being scanned against a list of hashes of malicious files to decide whether the file is malicious.
It is fast and produces almost no false positives, but it can only detect files that are already known.
Also, an attacker can easily evade it by changing a single variable in a webshell or rebuilding a binary, which changes the hash.
To detect modified files as well, the file content has to be inspected instead of the hash.
YARA is both a language for writing the characteristics of file content as rules and an engine that runs those rules.
For example, a content characteristic such as "a PHP file that reads a request parameter and passes its value to a command execution function" is defined as a condition, and the files that match it are found.
YARA-X is VirusTotal’s rewrite in Rust of YARA, which is written in C.
It keeps most of the rule language as is and aims to be a faster and safer engine.
YARA will continue with bug fixes and minor features only, while new features and modules are added to YARA-X.
1. How a YARA Rule Is Built
A YARA rule consists of patterns and a condition.
Patterns define the byte sequences to search for in the strings section, and the condition combines the pattern match results in the condition section to decide whether the file is malicious.
| Pattern type | What it expresses | Example in webshell and malicious binary detection |
|---|---|---|
| Text | Fixed phrases | PHP request parameter variables, the prefix of a mining pool address |
| Hex | Byte sequences, wildcards, jumps | The byte structure of an executable header |
| Regex | Patterns whose whitespace or case changes | Calls to command execution functions |
Modifiers can be attached to text patterns to also find modified forms of the same phrase.
- nocase: ignores case
- wide: finds the 2-byte form with a zero byte inserted for each character. It does not support real UTF-16 strings that contain non-English characters
- fullword: matches only when the phrase is delimited by non-alphanumeric characters on both sides, excluding cases where it appears as part of another word
- xor, base64: also finds forms XORed with a one-byte key or encoded in Base64
A condition can check not only whether patterns matched, but also the number of matches, their positions, the file size and the magic bytes at the start of the file.
For example, a webshell rule requires several patterns together, such as "smaller than 200KB, reads a request parameter and calls a command execution function". If the verdict relied on the command execution function alone, legitimate admin tools that use the same function would also be flagged as webshells.
2. Differences from YARA
YARA-X differs from YARA in three main ways.
The first is safety.
A scanner is a program that reads files made by attackers.
In particular, modules that parse executable headers take structures that an attacker has deliberately corrupted directly as input.
If the parser has a flaw such as an out-of-bounds access, the file being scanned can instead become an input that attacks the scanner.
In C, developers have to prevent these flaws themselves, but Rust’s bounds checks and ownership rules keep the same class of flaws from turning into memory corruption.
The YARA-X README also states the goal of being a safer engine than YARA.
The second is parser reuse.
In YARA, the parser is tied to the rule compilation logic, so tools such as code formatters and linters could not reuse it.
As a result, several separate YARA parsers were written, but they were slow to pick up changes in the official parser.
YARA-X separates the parser from the compilation logic so that other tools can reuse the same parser.
The third is embedding.
YARA was embedded into other programs through its C library (libyara).
YARA-X ships as a Rust crate and also provides C, Python and Go APIs.
A security agent written in Rust can therefore use the engine directly as a library, without a separate process or an FFI layer.
3. Multi-Pattern Search That Reads the File Once
With hundreds of rules, there are thousands of patterns.
If the file is read again from the beginning for every pattern, scan time grows in proportion to the number of patterns.
To avoid this, YARA and YARA-X extract an atom, a fixed byte fragment inside each pattern.
In a hex pattern, the fixed byte sequences between wildcards and jumps become atoms; in a regex, the fixed strings between repetitions and character classes become atoms.
The atoms of all rules are then combined into a single Aho-Corasick automaton, and the file is read through this automaton only once.
The full original pattern is checked only at positions where an atom matched, and the condition is evaluated last.
Scan speed is therefore determined by atom quality rather than by the number of rules.
YARA-X considers atoms that are long, contain few zero bytes and have a variety of byte values to be good atoms.
- Rare byte sequences: phrases that rarely appear in normal files, such as the prefix of a mining pool address, yield few candidate positions and are fast
- Patterns with short fixed parts: if only one or two fixed bytes sit between wildcards or jumps, no useful atom can be extracted
- Common byte sequences: a pattern of consecutive zero bytes produces candidate positions throughout the file
In other words, a few low-quality atoms alone can greatly increase the total scan time.
4. File Structure Modules
Modules parse file formats and provide values for use in conditions.
| Module | Values provided | Use in detection |
|---|---|---|
| pe | Headers, imports and sections of Windows executables | Executables that import APIs used for memory allocation and process injection |
| elf | Type, sections and symbols of Linux executables | Executables dropped into a server’s temporary directory |
| hash | Hashes of the whole file or a range | Hash matching against known malicious files |
| math | Statistics such as entropy | Packed or encrypted regions |
Binaries that hide their strings cannot be detected with text patterns.
In that case, the condition uses a structural characteristic: the file is an executable and its entropy is abnormally high.
With the hash module, hash matching can also be written in the same rule set, so known files and modified files are judged in one pass.
5. Migrating from YARA to YARA-X
YARA-X is mostly compatible with existing rules, but checks some syntax more strictly.
So the first step is to compile the existing rule set with YARA-X and examine the rules that produce errors.
Among the differences listed in the official documentation, the typical cases that surface as compile errors are the following.
- Braces in regular expressions: an opening brace that is not used as a repetition operator must be escaped. YARA matched such a brace literally, and the
--relaxed-re-syntaxoption of the YARA-X CLI escapes it automatically - base64 modifier: can only be used on patterns of 3 or more characters. In return, the false positives that base64 patterns produced in YARA do not occur
- Negative indexes: a negative match index, which YARA always evaluated as undefined, is an error in YARA-X
Braces and negative indexes compile without errors in YARA, but in practice they behaved differently from what the author intended.
So for a rule that produces an error, fixing the syntax is not enough; it also has to be checked that the rule behaves as originally intended.
Also note that, unlike rules, the API is not compatible.
Programs that embed YARA have to be changed to fit the YARA-X API, and programs that use process memory scanning cannot switch to YARA-X yet.
6. Usage Examples
6.1 Placement by Scan Timing
Even with the same rules, cost and effectiveness depend on when the scan runs.
| Timing | Benefit | Cost |
|---|---|---|
| On file creation or modification | Verdict before execution | One scan per event |
| Periodic full scan | Catches missed files | Reads the entire disk |
| Memory scan | Payloads that never touch disk | High privileges, not supported by YARA-X |
| Only the affected host after an alert | Lowest cost | After-the-fact verdict |
For example, an XDR agent uses file events reported by the kernel to narrow down what to scan.
It immediately scans only executables newly created in the web root, upload directories and temporary directories, and runs full scans only on hosts suspected of compromise.
This creation-time scan, the pre-scan path, does not include an LLM agent.
The path runs once per file event, so passing through an LLM would make latency and cost grow with the number of events, and the verdict on the same file could also differ each time.
Pre-scan therefore stays a deterministic pipeline with the engine embedded in the XDR agent, and the LLM agent only reads its results.
However, process memory scanning exists in YARA but is not yet implemented in YARA-X.
To scan payloads that never touch disk with YARA-X, memory has to be dumped to a file and scanned, or YARA has to be used alongside it for memory scanning only.
6.2 Using YARA-X as an Agent Tool in the Response Phase
In contrast, the investigation and response phase after an alert is a good fit for an LLM agent calling YARA-X as a tool.
It runs only when needed, only reads files and always returns the same result for the same input.
For the agent, the benefit is that a deterministic scan result, not a guess, can serve as the basis for its judgment.
The features YARA-X provides can be used to build tools such as the following.
| Tool | What it does | Underlying feature |
|---|---|---|
| Rule scan | Scans a specified file with a pre-approved rule set and returns the matched rules, tags, metadata and offsets | JSON and NDJSON output of scan results |
| File structure lookup | Returns the parsed results of the pe, elf, hash and math modules without rules | The dump command, which prints module results |
| Hunting rule execution | Runs a rule the agent wrote for its hypothesis, after approval and within a fixed scope | Rule compilation, a setting that treats slow patterns as errors |
The most useful of these is the file structure lookup.
Facts such as “this binary imports APIs used for process injection, and its entropy is 7.8” come back as structured values without any rule.
The agent can then base its judgment on these values instead of guessing at the binary’s content.
6.3 Boundaries to Keep When Building the Tool
When scanning is opened up to an agent, the following boundaries have to be designed along with it.
- Do not return raw file content: the scanned file was made by an attacker and may contain prompt injection text. Return only rule names and offsets, and pass raw fragments only as length-limited hex
- Set resource limits: use the scanner’s timeout, the maximum number of matches per pattern and the option to skip large files, and also limit the CPU and memory of the scanning process
- Pin the scan scope and rule sets to an allowlist: the agent must not be able to scan arbitrary paths or hosts
- Precompile rule sets and distribute them as versions: compiled rules can be serialized, so there is no need to recompile on every call, and recording the rule set version in the results makes verdicts reproducible
- Do not take automatic action on matches alone: the tool only goes as far as collecting read-only evidence, and actions such as stopping a process or isolation run only after policy or human approval
Summary
- Hash matching can only detect known files, while YARA judges modified files as well by the characteristics of their content
- Rules consist of patterns and conditions, and modifiers and modules can express encodings and even file structure
- The engine reads the file only once using atoms and Aho-Corasick, and scan speed is determined by atom quality
- YARA-X rewrites YARA in Rust and improves safety, parser reuse and embedding, but does not yet support process memory scanning
- Most existing rules compile as is, but the API is not compatible
- Operating cost depends much more on scan timing than on the rules
- Pre-scan stays in a deterministic pipeline, and in the response phase YARA-X is provided to the agent as a read-only tool
References
- YARA-X README: https://github.com/VirusTotal/yara-x
- YARA-X vs YARA: https://virustotal.github.io/yara-x/docs/intro/yara-x-vs-yara/
- Differences with YARA: https://virustotal.github.io/yara-x/docs/writing_rules/differences-with-yara/
- Text patterns: https://virustotal.github.io/yara-x/docs/writing_rules/text-patterns/
- CLI commands: https://virustotal.github.io/yara-x/docs/cli/commands/