API reference¶
- class yaratool.YaraRule(ruletext: str)[source]¶
One parsed Yara rule: its name, tags, metas, strings and conditions.
- canonical() str[source]¶
Return the semantic canonical form that the
yn02hash is computed from.See
yaratool.canonical. Names, tags and meta are not part of it.- Raises:
YaraParseError – if the rule cannot be canonicalized.
- hash(version: int = 2) str[source]¶
Return the normalized yara hash of the rule.
Version 2 (the default,
yn02:<32 hex digits>) is computed from the rule’s semantic canonical form: rules that detect the same things hash the same, whatever the spelling, string naming, modifier order or condition layout, and rules that detect different things do not collide.Version 1 (
yn01:<16 hex>:<10 hex>, e.g.yn01:042c1fd05933b9b1:4ca58b3314) is the legacy text-based hash: rules with the same strings and condition text, after identifiers are renumbered, hash the same.- Parameters:
version – 1 or 2.
- Raises:
ValueError – for any other version.
YaraParseError – if version 2 cannot parse the rule.
- class yaratool.DuplicateDetector[source]¶
Remembers rules by hash and name so that later duplicates can be spotted.
- check(rule: YaraRule) List[YaraRule][source]¶
Check whether
ruleduplicates one seen earlier, and remember it.Rules are duplicates if their hash matches or their name matches. The database of previously seen rules is updated as a side effect.
- Parameters:
rule – the rule to check.
- Returns:
the earlier rules it duplicates (via hash or name); empty if it is new.
Semantic canonicalization of a Yara rule (the basis of the yn02 hash).
The legacy yn01 hash works on text: it keeps string identifiers apart from the
strings they name and treats every spelling difference as a difference. This module
instead parses the rule and rewrites it into a canonical form that depends only on
what the rule detects:
every string is reduced to a canonical definition (modifier order, defaults,
/x/ivsnocase, hex spelling, text-vs-hex, jump/wildcard forms …);string identifiers in the condition are replaced by those canonical definitions, so the link between a name and its string is part of the hash and the names themselves are not;
the condition is parsed into an expression tree and rewritten:
and/orare flattened and sorted,any of/all of/none ofare expanded, comparisons are oriented, literals are evaluated (1KBis1024), and loop variables are renamed.
Only rewrites that are sound under Yara’s semantics (including undefined values) are applied. If a condition cannot be parsed, a conservative token-level form is used instead, which never merges rules that differ.
Rule names, tags and meta do not affect detection and are not part of the form.
- yaratool.canonical.canonical_form(ruletext: str) str[source]¶
Return the canonical form of a single rule (what the
yn02hash is computed from).- Parameters:
ruletext – the text of one rule.
- Raises:
ValueError – if the text is not a recognizable rule.