-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmatch4ida.py
327 lines (201 loc) · 8.74 KB
/
match4ida.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
import json
import sys
from enum import IntEnum
from pathlib import Path
try:
import pychrysalide
from pychrysalide.analysis.contents import FileContent
from pychrysalide.analysis.scan import ContentScanner
from pychrysalide.analysis.scan import ScanOptions
from pychrysalide.analysis.scan.patterns.backends import AcismBackend
except:
pass
try:
import yara
except:
pass
try:
import idaapi
from PyQt5 import QtCore, QtWidgets
except:
pass
class ScanHandler():
"""Generic handler for scan rules."""
class ScannerType(IntEnum):
YARA = 0
ROST = 1
GUESS = 2
def __init__(self, rule_filename, rule_type, binary_filename):
"""Create a generic handler for scanning."""
self._rule_filename = rule_filename
self._rule_type = rule_type
self._binary_filename = binary_filename
def _guess_suitable_scanner(self):
"""Try to guess if a rule is for YARA or ROST."""
with open(self._rule_filename, 'rb') as fd:
content = fd.read()
has_strings = b'strings:' in content
has_bytes = b'bytes:' in content
if has_strings and not(has_bytes):
rtype = ScanHandler.ScannerType.YARA
elif not(has_strings) and has_bytes:
rtype = ScanHandler.ScannerType.ROST
else:
rtype = ScanHandler.ScannerType.GUESS
return rtype
def run(self):
"""Run a scan."""
rtype = self._rule_type
if rtype == ScanHandler.ScannerType.GUESS:
rtype = self._guess_suitable_scanner()
found = []
if rtype == ScanHandler.ScannerType.YARA and 'yara' in sys.modules.keys():
idaapi.msg('Running YARA against %s...' % self._binary_filename)
rules = yara.compile(self._rule_filename)
matches = rules.match(self._binary_filename)
for m in matches:
for s in m.strings:
for i in s.instances:
extra = {
'identifier': s.identifier,
'bytes': str(i),
'start': i.offset,
'length': i.matched_length
}
found.append(extra)
elif rtype == ScanHandler.ScannerType.ROST and 'pychrysalide' in sys.modules.keys():
idaapi.msg('Running ROST against %s...' % self._binary_filename)
scanner = ContentScanner(filename=self._rule_filename)
content = FileContent(self._binary_filename)
options = ScanOptions()
options.backend_for_data = AcismBackend
ctx = scanner.analyze(options, content)
data = scanner.convert_to_json(ctx)
data = json.loads(data)
for rule in data:
for pat in rule['bytes_patterns']:
for m in pat['matches']:
extra = {
'identifier': pat['name'],
'bytes': m['content_str'].replace(r'\\', '\\'),
'start': m['offset'],
'length': m['length']
}
found.append(extra)
return found
class MatchPanel(idaapi.PluginForm):
"""Panel for the IDA GUI."""
def OnCreate(self, form):
"""Create a panel for the plugin activity."""
parent = self.FormToPyQtWidget(form)
# Create layout
layout = QtWidgets.QGridLayout()
parent.setLayout(layout)
# Connection properties
self._rule_filename = QtWidgets.QLineEdit()
self._rule_filename.setText('/tmp/Match4IDA/Sample/APT_MAL_UNC4841_SEASPY_Jun23_1.yar')
layout.addWidget(self._rule_filename, 0, 0)
self._browse_button = QtWidgets.QPushButton('Browse')
self._browse_button.clicked.connect(self._browse)
layout.addWidget(self._browse_button, 0, 1)
self._scanner_type = QtWidgets.QComboBox()
self._scanner_type.addItems(['Yara', 'ROST', 'auto'])
self._scanner_type.setCurrentIndex(2)
layout.addWidget(self._scanner_type, 0, 2)
self._scan_button = QtWidgets.QPushButton('Scan')
self._scan_button.clicked.connect(self._run_scan)
layout.addWidget(self._scan_button, 0, 3)
# Match display
self._rows = QtWidgets.QTableWidget()
column_names = [ 'Identifier', 'Found bytes', 'Offset', 'Start location', 'Match size' ]
self._rows.setColumnCount(len(column_names))
self._rows.setHorizontalHeaderLabels(column_names)
self._rows.setRowCount(0)
self._rows.doubleClicked.connect(self._jump_to_match_location)
header = self._rows.horizontalHeader()
header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
header.setSectionResizeMode(4, QtWidgets.QHeaderView.ResizeToContents)
# fromRow - fromColumn - rowSpan - columnSpan
layout.addWidget(self._rows, 1, 0, 1, 4)
def _browse(self):
"""Select a rule as analysis source."""
dlg = QtWidgets.QFileDialog()
dlg.setFileMode(QtWidgets.QFileDialog.ExistingFile)
dlg.setNameFilter('YARA rules (*.yar);;ROST rules (*.rost)')
if dlg.exec_():
filename = str(Path(dlg.selectedFiles()[0]))
self._rule_filename.setText(filename)
def _run_scan(self):
"""Run a scan and display the results."""
rule_filename = self._rule_filename.text()
rule_type = self._scanner_type.currentIndex()
binary_filename = idaapi.get_input_file_path()
if len(rule_filename) == 0:
return
scanner = ScanHandler(rule_filename, rule_type, binary_filename)
matches = scanner.run()
self._rows.setRowCount(0)
for m in matches:
index = self._rows.rowCount()
self._rows.setRowCount(index + 1)
item = QtWidgets.QTableWidgetItem(m['identifier'])
item.setFlags(item.flags() & ~QtCore.Qt.ItemIsEditable)
self._rows.setItem(index, 0, item)
item = QtWidgets.QTableWidgetItem(m['bytes'])
item.setFlags(item.flags() & ~QtCore.Qt.ItemIsEditable)
self._rows.setItem(index, 1, item)
item = QtWidgets.QTableWidgetItem('0x%x' % m['start'])
item.setFlags(item.flags() & ~QtCore.Qt.ItemIsEditable)
self._rows.setItem(index, 2, item)
ea = idaapi.get_fileregion_ea(m['start'])
item = QtWidgets.QTableWidgetItem('0x%x' % ea)
item.setFlags(item.flags() & ~QtCore.Qt.ItemIsEditable)
self._rows.setItem(index, 3, item)
item = QtWidgets.QTableWidgetItem('0x%x' % m['length'])
item.setFlags(item.flags() & ~QtCore.Qt.ItemIsEditable)
self._rows.setItem(index, 4, item)
self._rows.update()
idaapi.msg('Found %u match(es)\n' % self._rows.rowCount())
def _jump_to_match_location(self, item):
addr = int(self._rows.item(item.row(), 3).text(), 16)
idaapi.jumpto(addr)
class Match4IDA(idaapi.plugin_t):
flags = idaapi.PLUGIN_KEEP
comment = 'Navigate to rule matched locations inside IDA.'
wanted_name = 'Match4IDA'
wanted_hotkey = ''
help = 'Scan the current open binary against byte patterns.'
def init(self):
"""Init the IDA plugin."""
idaapi.msg('Starting %s\n' % self.wanted_name)
self._form = None
return idaapi.PLUGIN_KEEP
def run(self, arg):
"""Run the IDA plugin."""
idaapi.msg('Running %s\n' % self.wanted_name)
self._form = MatchPanel()
self._form.Show('Scan matches')
def term(self):
"""Terminate the IDA plugin."""
idaapi.msg('Terminating %s\n' % self.wanted_name)
def PLUGIN_ENTRY():
return Match4IDA()
if __name__ == '__main__':
"""Script entrypoint."""
has_yara = 'yara' in sys.modules.keys()
if not(has_yara or False):
print('At least one scanner is requiered')
inside_ida = 'ida_idaapi' in sys.modules.keys()
if not(inside_ida):
if len(sys.argv) != 3:
print('Usage: %s <rule> <binary>' % sys.argv[0])
sys.exit(2)
rule_filename = sys.argv[1]
binary_filename = sys.argv[2]
scanner = ScanHandler(rule_filename, ScanHandler.ScannerType.GUESS, binary_filename)
matches = scanner.run()
for m in matches:
print('0x%x:%s:' % (m['start'], m['identifier']), m['bytes'])