Skip to content

Instantly share code, notes, and snippets.

@Neo23x0
Created October 10, 2020 15:51
Show Gist options
  • Save Neo23x0/81990b8e5eb351a118dca1d5f2a2a86b to your computer and use it in GitHub Desktop.
Save Neo23x0/81990b8e5eb351a118dca1d5f2a2a86b to your computer and use it in GitHub Desktop.
YARA Rule Hash Used by Nextron Systems
import hashlib
import re
def calculate_rule_hash(rule):
"""
Calculates a hash over the relevant YARA rule content (string contents, sorted condition)
Requires a YARA rule object as generated by 'plyara': https://github.com/plyara/plyara
:param rule: yara rule object
:return hash: generated hash
"""
hash_strings = []
m = hashlib.md5()
# Adding all string contents to the list
if 'strings' in rule:
for s in rule['strings']:
if s['type'] == "byte":
hash_strings.append(re.sub(r'[^a-fA-F\?0-9]+', '', s['value']))
else:
hash_strings.append(s['value'])
# Adding the components of the condition to the list (except the variables)
for e in rule['condition_terms']:
if not e.startswith("$") and not e.startswith("#"):
hash_strings.append(e)
# Empty
if len(hash_strings) == 0:
return ""
# Generate a hash from the sorted contents
hash_strings.sort()
m.update("".join(hash_strings).encode("ascii"))
return m.hexdigest()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment