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,notX of ($s*)– X out of all matching stringsany of them– at least one string matchesfilesize– file size constraintsuint16(0)– value at offset
Best Practices
- Always check for PE header (
uint16(0) == 0x5A4D) - Use multiple strings for robustness
- Avoid overly generic patterns (high false positives)
- Test against clean file corpus before deployment
- Include metadata for tracking
