# Malware Yara Writing Rule Syntax Patterns

> Use when you need deep YARA rule syntax for malware detection work, covering every string type (text, hex, regex), every modifier (wide, ascii, nocase, fullword, private, xor, base64), hex string jumps and wildcards, condition operators and set logic, for-loops and math in conditions, external variables, includes, and private versus global rules. Use when a parent rule needs a tricky pattern, when matching encoded or wide strings, or when a condition must express "at least N of these with constraints".

- Skill: `mizazhaider-ceh/malware-yara-writing-rule-syntax-patterns` (Agent Skill)
- Install (CLI): `npx get-skill add mizazhaider-ceh/malware-yara-writing-rule-syntax-patterns`
- Raw SKILL.md: https://api.skillmd.com/api/skills/mizazhaider-ceh/malware-yara-writing-rule-syntax-patterns/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- Author: mizazhaider-ceh (https://skillmd.com/u/mizazhaider-ceh)
- Updated: 2026-11-22
- Page: https://skillmd.com/skills/mizazhaider-ceh/malware-yara-writing-rule-syntax-patterns

---


String types and condition logic are where rules gain or lose precision.
This sub-skill is the syntax reference for the parent malware-yara-writing
skill: how to match text in any encoding, how to describe byte patterns
with gaps, and how to write conditions that count, locate, and constrain
matches. Scope: use when analyzing a malware sample in an isolated lab
during authorized DFIR or detection engineering. Test every pattern against
clean corpora before deployment.

## Quick Workflow

1. List the exact byte patterns you need to match from triage (strings,
   opcodes, encoded blobs).
2. Pick the string type per pattern: text for readable strings, hex for
   opcodes, regex for formatted values.
3. Add modifiers for encoding and strictness (wide, ascii, nocase,
   fullword).
4. Write the condition using counts, offsets, and set expressions.
5. Compile and test each pattern in isolation before combining.
6. Combine into the final rule and run the full corpus test from the
   parent skill.

## 1. Text strings and modifiers

```yara
rule Syntax_Text_Example
{
    strings:
        $a = "beacon.example.net" ascii
        $b = "Global\\SyncMutex" ascii wide
        $c = "cmd.exe /c powershell" nocase
        $d = "Run" fullword ascii
        $e = "helper" private ascii
    condition:
        2 of them
}
```

Modifier notes: `ascii` and `wide` can combine to match both encodings;
`wide` alone matches UTF-16LE. `nocase` folds ASCII case only. `fullword`
requires non-alphanumeric boundaries on both sides, which kills substring
false positives (matching "Run" inside "Brunei"). `private` marks helper
strings that do not count in `them` and do not show in output; use it for
strings that only serve a `for` loop or an offset check.

## 2. Hex strings: wildcards and jumps

```yara
rule Syntax_Hex_Example
{
    strings:
        $op1 = { 8B 45 ?? 33 C0 89 45 FC }
        $op2 = { E8 ?? ?? ?? ?? 83 C4 04 [0-16] 55 8B EC }
        $op3 = { 48 8D ?? ?? ?? ?? ?? ( 90 | CC ) 48 89 }
    condition:
        any of them
}
```

`??` matches any single byte (variable operand). `[0-16]` is a jump: 0 to
16 arbitrary bytes between the anchored parts, which survives inserted
instructions. `( 90 | CC )` is an alternation. Keep hex strings anchored
by at least 4 fixed bytes on each side of any jump; unanchored jumps scan
slowly and match loosely.

## 3. Regular expressions

```yara
rule Syntax_Regex_Example
{
    strings:
        $ua  = /NimbusAgent\/[0-9]+\.[0-9]+/ ascii
        $ip  = /[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}:[0-9]{2,5}/ ascii
        $id  = /CAMP-[0-9]{4}-[0-9]{3}/ ascii wide nocase
    condition:
        any of them
}
```

Regexes match formatted values: versioned user agents, IP:port pairs,
campaign IDs. Escape literal slashes and dots. Regex performance depends
on atom quality: a regex starting with a long literal (`/NimbusAgent/`)
is fast; one starting with `[0-9]{1,3}` is slow. Prefer a literal prefix
whenever the format allows it.

## 4. Condition operators and set logic

```yara
rule Syntax_Condition_Example
{
    strings:
        $s1 = "alpha" ascii
        $s2 = "beta" ascii
        $h1 = { DE AD BE EF }
    condition:
        uint16(0) == 0x5A4D and
        filesize < 10MB and
        (
            2 of ($s*) or
            ( $h1 at 0x1000 ) or
            ( #s1 > 5 )
        )
}
```

Operators: `at <offset>` pins a match location (entry point code, header
field), `in <range>` constrains to a region, `#s1` counts occurrences,
`!s1` counts occurrences... (note: `!` is the count operator only in
offsets context; `#` is the count). `of` works on sets: `2 of ($s*)`
matches the s-group, `all of them`, `any of them`, `none of them`.
Parenthesize mixed `and`/`or`; YARA follows standard precedence but
explicit parens prevent misreads.

## 5. For loops and math in conditions

```yara
rule Syntax_Loop_Example
{
    strings:
        $mz = "MZ" ascii
    condition:
        for any i in (1..pe.number_of_sections) : (
            pe.sections[i].name == ".packed" and
            math.entropy(pe.sections[i].raw_data_offset,
                         pe.sections[i].raw_data_size) > 7.5
        )
}
```

For loops iterate sections, resources, or imports with per-item tests.
`math.entropy(offset, size)` and `math.deviation` give statistical checks
inside conditions. Keep loop bodies cheap: one or two comparisons, not
nested loops.

## 6. External variables, includes, private and global rules

```bash
# External variables let one rule adapt per environment
yara -d filename="invoice.doc.exe" -d min_size=100000 rule.yar target/
```

```yara
include "common_strings.yar"

private rule Helper_Is_PE
{
    condition:
        uint16(0) == 0x5A4D
}

global rule Global_No_Empty_File
{
    condition:
        filesize > 0
}
```

`include` shares string sets across rules. `private` rules never alert on
their own but can be referenced. `global` rules must all match for any
rule in the file to match; use sparingly (a global filesize floor is the
common case).

## Edge cases

- `wide` strings in files that are actually UTF-8: no match, no error.
  When unsure of encoding, declare both `ascii wide`.
- Overlapping matches with `fullword`: a match at the boundary of
  another match can behave unexpectedly; test with `yara -s` to see
  exact offsets.
- Hex jumps with large ranges (`[0-1024]`) are slow and loose; keep
  jumps under ~32 bytes or anchor harder.
- Regex catastrophic patterns: nested quantifiers like `(a+)+` can hang
  the scan; keep regexes flat and literal-led.
- `at` with a computed offset: the offset expression must be constant
  per file; it cannot depend on a match position.
- Case folding is ASCII-only: `nocase` does not fold Unicode case.
- Private strings still cost scan time; they only hide output and
  counting.

## Escalation

- If a pattern needs context-free grammar power (nested structures),
  YARA is the wrong tool; escalate to a parser-based detector and keep
  YARA for the flat patterns.
- If rule compile fails with cryptic errors, isolate to a minimal rule
  and bisect; escalate to the YARA-X migration notes if the syntax is
  version-specific.
- If performance collapses on a specific pattern, escalate to the
  rule-optimization sub-skill before deploying.

- If a needed pattern exceeds YARA's expressive power, escalate to a companion detector (script or parser) and keep YARA for the flat patterns.

## Detection and defender view

Syntax precision is detection precision. Prefer `fullword` and anchored
hex over loose substrings; every loose pattern is a future false
positive the SOC will have to triage. When a rule fires, the matched
strings shown by `yara -s` are the first thing the analyst reads, so
name strings meaningfully ($c2_url, not $a) and keep private the ones
that would confuse. Version-controlled rule files with includes let the
team share string sets for a campaign across many rules without
duplication.

## Key references

- YARA writing rules documentation:
  https://yara.readthedocs.io/en/stable/writingrules.html
- YARA-X syntax documentation:
  https://virustotal.github.io/yara-x/docs/intro/
- YARA style guide:
  https://github.com/Neo23x0/YARA-Style-Guide
- MITRE ATT&CK: T1027 (Obfuscated Files or Information)

- YARA-X syntax reference:
  https://virustotal.github.io/yara-x/docs/intro/syntax/

