How to Write a Basic YARA Rule

Task

How to Write a Basic YARA Rule

YARA Rule Structure

rule MalwareFamily_Variant {
    meta:
        author = "Your Name"
        date = "2024-01-01"
        description = "Detects MalwareFamily variant X"

    strings:
        $s1 = "suspicious_string" ascii wide
        $s2 = { 4D 5A 90 00 }  // hex pattern
        $s3 = /https?:\/\/[a-z]+\.evil\.com/ // regex

    condition:
        uint16(0) == 0x5A4D and  // PE file
        filesize < 500KB and
        2 of ($s*)
}

String Types

  • Text strings: "http://evil.com" (ascii, wide, nocase)
  • Hex strings: { 4D 5A ?? 00 } (wildcards with ??)
  • Regex: /pattern/ (regular expressions)

Condition Operators

  • and, or, not
  • X of ($s*) – X out of all matching strings
  • any of them – at least one string matches
  • filesize – file size constraints
  • uint16(0) – value at offset

Best Practices

  1. Always check for PE header (uint16(0) == 0x5A4D)
  2. Use multiple strings for robustness
  3. Avoid overly generic patterns (high false positives)
  4. Test against clean file corpus before deployment
  5. Include metadata for tracking