YARA-X Documentation

repository·main·Indexed 22 days ago

https://github.com/virustotal/yara-x

A high-performance, safe, and user-friendly pattern matching tool for malware researchers to identify malware families through textual and binary patterns. YARA-X provides a modern re-incarnation of YARA with official bindings for JavaScript (@virustotal/yara-x) and Python, a Language Server Protocol (LSP) implementation for Visual Studio Code, and a browser-based Playground for testing rules via WebAssembly.

Tokens
87.5K
Snippets
229
Records
481
Agent score
79%

What's inside YARA-X

  1. Overview of YARA-X

    main

    YARA-X is a pattern matching tool designed for malware researchers to describe malware families or other entities using textual or binary patterns. It is a modern re-incarnation of YARA, designed to be faster, safer, and more user-friendly.

    Rules in YARA-X consist of a set of patterns (strings) and a boolean expression (condition) that determines the logic for matching. Rules can include metadata for context, such as descriptions or threat levels.

  2. Overview of YARA-X vs YARA

    main

    YARA-X is a complete rewrite of the YARA rule engine implemented in Rust. It is designed to be a modern successor to the original C-based YARA, focusing on several key improvements:

    • Performance: Optimized for rules involving regular expressions or complex loops, aiming to outperform YARA across the board.
    • Compatibility: Targets ~99% rule-level compatibility with YARA, with minimal and documented incompatibilities.
    • Reliability & Security: Leverages Rust's memory safety to reduce bugs and security vulnerabilities common in complex C codebases.
    • User Experience: Features a modern, colorful CLI and more descriptive error reporting.
    • Developer Integration: Provides official APIs for Python, Golang, and C to facilitate easier integration into other projects.

    Current Status: YARA-X is currently in beta. While the APIs may undergo minor changes, the core functionality is considered mature and stable enough for CLI usage and one-shot Python scripts. It is battle-tested via large-scale scanning at VirusTotal.

  3. Use the macho module for Mach-O file analysis

    main

    The macho module enables the creation of fine-grained YARA-X rules targeting specific attributes and features of the Mach-O file format. It exposes Mach-O header fields and provides helper functions to inspect entitlements, dynamic libraries (dylibs), rpaths, imports, and exports.

    To use it, import the module at the top of your rule file:

    import "macho"
    import "macho"
    
    rule cpu_type {
      condition:
        macho.cputype == macho.CPU_TYPE_X86_64
    }
    
    rule frameworks_rpath {
      condition:
        macho.has_rpath("@loader_path/../Frameworks")
    }
    
    rule dylib_hash {
      condition:
        macho.dylib_hash() == "c92070ad210458d5b3e8f048b1578e6d"
    }
  4. Features of the YARA-X Language Server

    main

    The YARA-X Language Server implements the Language Server Protocol (LSP) to provide the following features in supported editors:

    • Real-time diagnostics: Provides on-the-fly syntax error highlighting and descriptive error messages as you type.
    • Advanced autocompletion: Offers intelligent suggestions for keywords and module identifiers (e.g., pe., cuckoo.).
    • Go to definition: Allows instant navigation to the definition of rules or patterns across multiple files.
    • Automatic formatting: Automatically formats YARA code to maintain consistency and readability according to best practices.
  5. Compare YARA-X and YARA

    main

    YARA-X is designed as a replacement for YARA, focusing on usability, backward-compatibility, and performance. While YARA-X is intended to eventually replace YARA, it is currently a younger project and lacks some existing features like process scanning.

    Key Advantages of YARA-X:

    • Detailed Error Reporting: Provides more context and explicative messages for errors.
    • Enhanced CLI: Features colorful output, autocompletion (Bash, Zsh, PowerShell), automatic code formatting, and automatic fixes for certain warnings.
    • File Dissection: Can access YARA module output in YAML and JSON formats without requiring a YARA rule, making it a tool for dissecting PE, ELF, Mach-O, and LNK files.
    • Superior Performance: Significantly faster than YARA when handling complex regular expressions, hex patterns, and extensive loops.
    • Modular Parser: The parser is decoupled from the rule compilation logic, allowing it to be reused for external tools like linters or formatters.

    Current Limitations:

    • Incompatible APIs: The C/C++, Python, and Golang APIs are not drop-in replacements for YARA and require code adaptation.
    • No Process Scanning: Unlike YARA, YARA-X does not currently support scanning running processes.
  6. Use the crx module for Chrome Extension analysis

    main

    The crx module allows you to parse Chrome Extension (CRX) files and create YARA rules based on their metadata. CRX files are ZIP archives used by Chromium-based browsers (like Chrome and Edge) that include digital signatures for integrity validation.

    To use the module, include import "crx" in your YARA-X rule. Note that all hashes returned by the module functions are provided in lowercase.

    import "crx"
    
    rule AllCrx {
        condition:
            crx.is_crx
    }
  7. Performance improvements in YARA-X: Aho-Corasick and RegexSet

    main

    YARA-X has introduced significant performance optimizations for pattern matching and rule evaluation:

    1. Aho-Corasick Optimization: Starting with v1.16.0, YARA-X replaced the aho_corasick crate with daachorse. This uses a compact double-array trie data structure, resulting in a tighter inner loop and better cache efficiency. In benchmarks, this provided a ~2.2x speedup over the previous aho_corasick implementation.

    2. Simultaneous Regex Evaluation: Introduced in v1.17.0, the compiler now detects multiple matches operations against the same target (e.g., a variable or structure field) within an or condition. It automatically groups these into a single RegexSet (from the Rust regex crate), allowing the engine to perform a single scan pass over the data instead of sequential passes for each pattern.

  8. How YARA handles undefined values in conditions

    main

    In YARA, certain module variables may be in an undefined state if they are not applicable to the file being scanned (e.g., accessing pe.entry_point on a non-PE file). YARA uses specific logic to ensure rules remain meaningful even when encountering these values.

    Boolean Logic for undefined

    When using and or or operators, undefined operands are treated as false:

    • undefined and true $\rightarrow$ false
    • undefined and false $\rightarrow$ false
    • undefined or true $\rightarrow$ true
    • undefined or false $\rightarrow$ false

    Other Operators

    For all other operators, including the not operator, the result will be undefined if any of the operands are undefined.

    Example: Logical behavior

    If a rule contains $a or pe.entry_point == 0x1000 and the file is not a PE file, pe.entry_point == 0x1000 evaluates to undefined. Because of the or logic, the rule will match if and only if $a is true.

  9. How YARA-X Python workflow works

    main

    Using YARA-X in Python follows a two-step lifecycle:

    1. Rule Compilation: Transform YARA rules from text into a Rules object. You can use the simple yara_x.compile(...) function for basic tasks, or the Compiler object for complex scenarios involving namespaces and multiple rule sets.
    2. Scanning: Use the Rules object to scan data. You can use the direct Rules.scan(...) method for simplicity, or create a Scanner object for more granular control over the scanning process (e.g., setting timeouts or match limits).
  10. Understand YARA-X Playground architecture

    main

    The playground architecture distributes work across the main UI thread and two dedicated Web Workers to ensure responsiveness:

    1. Main Thread: Hosts the Lit UI and the Monaco editor. It communicates with the other workers.
    2. Language Server Worker: Runs the YARA-X Language Server (WebAssembly). It communicates with the Monaco editor via JSON-RPC over postMessage to provide autocompletion, diagnostics, and navigation.
    3. Scan Worker: Runs the @virustotal/yara-x engine (WebAssembly). It performs the actual rule scanning and returns results and console output to the UI via worker messages.

    Note on Scope: The playground is intended for testing a single rule against a single sample. For batch scans or large files, use the YARA-X CLI instead.