Skip to content

Instantly share code, notes, and snippets.

@c3rb3ru5d3d53c
Last active June 19, 2023 12:19
Show Gist options
  • Save c3rb3ru5d3d53c/3b2e5dad8c7ee944b8efc7a2fb63194d to your computer and use it in GitHub Desktop.
Save c3rb3ru5d3d53c/3b2e5dad8c7ee944b8efc7a2fb63194d to your computer and use it in GitHub Desktop.
Find YARA Matches with Ghidra
#Find YARA Matches
#@author @c3rb3ru5d3d53c
#@category YARA
#@keybinding
#@menupath
#@toolbar
import yara
from dataclasses import dataclass
@dataclass
class YARAMatch():
offset: int = None
address: object = None
rule: str = None
name: str = None
data: bytes = None
size: int = None
tags:list = None
class YARA():
def __init__(self, file_path):
self.yarac = yara.compile(file_path)
self.memory = currentProgram.getMemory()
def scan(self, data):
matches = self.yarac.match(data=data)
for i in range(0, len(matches)):
for j in range(0, len(matches[i].strings)):
for k in range(0, len(matches[i].strings[j].instances)):
yield YARAMatch(
rule=matches[i].rule,
tags=matches[i].tags,
name=matches[i].strings[j].identifier,
offset=matches[i].strings[j].instances[k].offset,
address=self.memory.locateAddressesForFileOffset(matches[i].strings[j].instances[k].offset)[0],
data=matches[i].strings[j].instances[k].matched_data,
size=matches[i].strings[j].instances[k].matched_length,
)
@staticmethod
def get_bytes(address, size):
return bytes(map(lambda b: b & 0xff, getBytes(address, size)))
def get_memory(self):
ranges = self.memory.getAddressRanges()
return b''.join([self.get_bytes(r.getMinAddress(), r.getLength()) for r in ranges])
@staticmethod
def pprint(matches):
for match in matches:
print(f'{match.address} {match.rule} {match.name}')
y = YARA(file_path=askFile('Select YARA Signature', 'Okay').toString())
data = y.get_memory()
matches = y.scan(data=data)
y.pprint(matches)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment