-
Notifications
You must be signed in to change notification settings - Fork 1
/
FIRST3.py
5222 lines (4083 loc) · 196 KB
/
FIRST3.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import random
import functools
from signal import default_int_handler
# Third Party Python Modules
required_modules_loaded = True
try:
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
except ImportError:
required_modules_loaded &= False
print('FIRST requires Python module requests\n')
try:
from requests_kerberos import HTTPKerberosAuth
except ImportError:
print('[1st] Kerberos support is not avaialble')
HTTPKerberosAuth = None
from PyQt5 import QtGui, QtWidgets, QtCore
from PyQt5.QtCore import Qt
# Python Modules
import re
import csv
import sys
import math
import time
import json
import inspect
import os.path
import datetime
import calendar
import threading
import collections
from configparser import RawConfigParser
from pprint import pprint
from os.path import exists
from hashlib import sha256, md5, sha1
from base64 import b64encode, b64decode
def cmp(a, b):
return (int(a) > int(b)) - (int(a) < int(b))
def remove_dup(buffer:list):
ret = []
for b in buffer:
if b in ret:
continue
ret.append(b)
return ret
# Constants
#-------------------------------------------------------------------------------
FIRST_INDEX = {
'hashes' : 1,
'malware_name' : 2,
}
# Global Variables
#-------------------------------------------------------------------------------
FIRST_ICON = None
FIRST_DB = 'FIRST_data'
g_network_headers = {}
import ida_kernwin
import ida_funcs
import idc
import idautils
import ida_segment
import idaapi
import ida_ida
import ida_nalt
import ida_bytes
import ida_ua
import ida_name
import ida_xref
class IDAWrapper(object):
'''
Class to wrap functions that are not thread safe. These functions must
be run on the main thread to avoid random crashes (and starting in 7.2,
this is enforced by IDA, with an exception being generated if a
thread-unsafe function is called from outside of the main thread.)
'''
mapping = {
'get_widget_type' : 'get_widget_type',
}
def __init__(self):
self.version = idaapi.IDA_SDK_VERSION
def __getattribute__(self, name):
default = '[1st] default'
if (idaapi.IDA_SDK_VERSION >= 700) and (name in IDAWrapper.mapping):
name = IDAWrapper.mapping[name]
val = getattr(ida_name, name, default)
if val == default:
val = getattr(idautils, name, default)
if val == default:
val = getattr(idc, name, default)
if val == default:
val = getattr(ida_kernwin, name, default)
if val == default:
val = getattr(ida_funcs, name, default)
if val == default:
val = getattr(ida_segment, name, default)
if val == default:
val = getattr(ida_ida, name, default)
if val == default:
val = getattr(ida_nalt, name, default)
if val == default:
val = getattr(ida_bytes, name, default)
if val == default:
val = getattr(ida_ua, name, default)
if val == default:
val = getattr(ida_xref, name, default)
if val == default:
val = getattr(idaapi, name, default)
if val == default:
msg = 'Unable to find {}'.format(name)
idaapi.execute_ui_requests((FIRSTUI.Requests.Print(msg),))
return
if hasattr(val, '__call__'):
def call(*args, **kwargs):
holder = [None] # need a holder, because 'global' sucks
def trampoline():
holder[0] = val(*args, **kwargs)
return 1
# Execute the request using MFF_WRITE, which should be safe for
# any possible request at the expense of speed. In my testing,
# though, it wasn't noticably slower than MFF_FAST. If this
# is observed to impact performance, consider creating a list
# that maps API calls to the most appropriate flag.
idaapi.execute_sync(trampoline, idaapi.MFF_WRITE)
return holder[0]
return call
else:
return val
IDAW = IDAWrapper()
# Some of the IDA API functions return generators that invoke thread-unsafe
# code during iteration. Thus, making the initial API call via IDAW is not
# sufficient to have these underlying API calls be executed safely on the
# main thread. This generator wraps those and performs the iteration safely.
def safe_generator(iterator):
# Make the sentinel value something that isn't likely to be returned
# by an API call (and isn't a fixed string that could be inserted into
# a program to break FIRST maliciously)
sentinel = '[1st] Sentinel %d' % (random.randint(0, 65535))
holder = [sentinel] # need a holder, because 'global' sucks
def trampoline():
try:
holder[0] = next(iterator)
except StopIteration:
holder[0] = sentinel
return 1
while True:
# See notes above regarding why we use MFF_WRITE here
idaapi.execute_sync(trampoline, idaapi.MFF_WRITE)
if holder[0] == sentinel:
return
yield holder[0]
# Main Plug-in Form Class
#-------------------------------------------------------------------------------
class FIRST_FormClass(idaapi.PluginForm):
system = {0 : 'Unknown', 1 : 'Win', 6 : 'Linux', 9 : 'Osx'}
def __init__(self):
super(FIRST_FormClass, self).__init__()
self.parent = None
def OnCreate(self, form):
self.form = form
self.parent = self.FormToPyQtWidget(form)
self.populate_model()
self.populate_main_form()
def populate_model(self):
# Selectable views in the main plug-in window
self.views_ui = {'Configuration' : self.view_configuration_info,
'Management' : self.view_created,
'Currently Applied' : self.view_applied,
'About' : self.view_about}
self.views = ['About', 'Configuration', 'Management', 'Currently Applied']
self.views_model = FIRST.Model.Base(['Views'], self.views)
def view_configuration_info(self):
self.thread_stop = True
container = QtWidgets.QVBoxLayout()
label = QtWidgets.QLabel('Configuration Information')
label.setStyleSheet('font: 18px;')
container.addWidget(label)
layout = QtWidgets.QHBoxLayout()
self.message = QtWidgets.QLabel()
layout.addWidget(self.message)
layout.addStretch()
save_button = QtWidgets.QPushButton('Save')
layout.addWidget(save_button)
scroll_layout = FIRSTUI.ScrollWidget(frame=QtWidgets.QFrame.NoFrame)
FIRSTUI.SharedObjects.server_config_layout(self, scroll_layout, FIRST.config)
container.addWidget(scroll_layout)
container.addStretch()
container.addLayout(layout)
save_button.clicked.connect(self.save_config)
return container
def save_config(self):
FIRST.config = FIRSTUI.SharedObjects.get_config(self)
FIRST.config.save_config(FIRST.config_path)
info = FIRST.Info.get_file_details()
FIRST.server = FIRST.Server(FIRST.config,
info['md5'],
info['crc32'],
h_sha1=info['sha1'],
h_sha256=info['sha256'])
title = 'FIRST: Configuration Changes'
msg = 'FIRST\'s configuration information has been updated'
idaapi.execute_ui_requests((FIRSTUI.Requests.MsgBox(title, msg, QtWidgets.QMessageBox.Information),))
def view_created(self):
container = QtWidgets.QVBoxLayout()
groups = None
label = QtWidgets.QLabel('FIRST Metadata')
label.setStyleSheet('font: 18px;')
container.addWidget(label)
container.addSpacing(5)
description = ('The metadata you\'ve created and added to FIRST '
'are shown below. You can delete them via right '
'clicking on them and selecting delete or '
'selecting one and hitting the delete key.')
description = QtWidgets.QLabel(description)
description.setWordWrap(True)
container.addWidget(description)
container.addSpacing(10)
data_model = FIRST.Model.Check({})
tree_view = FIRST.Model.TreeView(depth=1)
tree_view.setExpandsOnDoubleClick(False)
tree_view.setIndentation(15)
tree_view.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
tree_view.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
# Setup the Model's header
FIRSTUI.SharedObjects.make_model_headers(data_model, full=False)
tree_view.setModel(data_model)
self.created_data_model = data_model
tree_view.setColumnWidth(0, 175) # Function
tree_view.setColumnWidth(1, 35) # Rank
tree_view.setColumnWidth(2, 150) # Prototype
tree_view.setColumnWidth(3, 20) # i
# Add chunks to the list at a time receieved
self.__received_data = False
if FIRST.server:
# Spawn thread to get chunks of data back from server
self.thread_stop = False
idaapi.show_wait_box('Querying FIRST for metadata you\'ve created')
server_thread = FIRST.server.created(self.__data_callback,
self.__complete_callback)
# wait several seconds
for i in range(2):
time.sleep(1)
if idaapi.user_cancelled():
self.thread_stop = True
FIRST.server.stop_operation(server_thread)
idaapi.hide_wait_box()
self.history_dialogs = []
tree_view.setContextMenuPolicy(Qt.ActionsContextMenu)
delete_action = QtWidgets.QAction('&Delete', self.parent)
delete_action.setShortcut('Del')
delete_action.triggered.connect(self.delete_metadata)
history_action = QtWidgets.QAction('View &History', self.parent)
history_action.setShortcut('H')
history_action.triggered.connect(self.metadata_history)
tree_view.addAction(delete_action)
tree_view.addAction(history_action)
self.created_tree_view = tree_view
container.addWidget(self.created_tree_view)
return container
def __data_callback(self, thread, data):
if self.thread_stop:
FIRST.server.stop_operation(thread)
# Build the model
root_node = self.created_data_model.invisibleRootItem()
for match in data:
self.__received_data = True
row = FIRSTUI.SharedObjects.make_match_info(match, full=False)
root_node.appendRow(row)
def __complete_callback(self, thread, data):
FIRST.server.remove_operation(thread)
# Alert the user if no matches were found in FIRST
if not self.__received_data:
title = 'FIRST: No Metadata Found'
msg = 'You have not added any metadata to FIRST'
idaapi.execute_ui_requests((FIRSTUI.Requests.MsgBox(title, msg, QtWidgets.QMessageBox.Information),))
return
def delete_metadata(self):
selected = self.created_tree_view.selectedIndexes()
if not selected:
return
ids = remove_dup([x.data(FIRSTUI.ROLE_ID) for x in selected])
index = selected[0]
for metadata_id in ids:
# Delete from FIRST
if metadata_id:
response = FIRST.server.delete(metadata_id)
if (not response
or ('failed' not in response)
or response['failed']
or (('deleted' in response) and not response['deleted'])):
title = 'FIRST: Delete Created Metadata'
msg = 'Cannot delete the requested signature. '
if response and ('msg' in response):
msg += 'Error: {0[msg]} '.format(response)
idaapi.execute_ui_requests((FIRSTUI.Requests.MsgBox(title, msg),))
return
# Remove from view, get the top row of the tree
if index.parent().isValid():
index = index.parent()
root = self.created_data_model.invisibleRootItem()
root.removeRow(index.row())
def metadata_history(self):
selected = self.created_tree_view.selectedIndexes()
if not selected:
return
ids = [x.data(FIRSTUI.ROLE_ID) for x in selected]
index = selected[0]
if not ids:
return
dialog = FIRSTUI.Dialog(None, FIRSTUI.History, metadata_id=ids[0])
dialog.show()
self.history_dialogs.append(dialog)
def view_about(self):
self.thread_stop = True
container = QtWidgets.QVBoxLayout()
label = QtWidgets.QLabel('FIRST ')
label.setStyleSheet('font: 24px;')
container.addWidget(label)
label = QtWidgets.QLabel('Function Identification and Recovery Signature Tool')
label.setStyleSheet('font: 12px;')
container.addWidget(label)
grid_layout = QtWidgets.QGridLayout()
grid_layout.addWidget(QtWidgets.QLabel('Version'), 0, 0)
grid_layout.addWidget(QtWidgets.QLabel(str(FIRST.VERSION)), 0, 1)
grid_layout.addWidget(QtWidgets.QLabel('Date'), 1, 0)
grid_layout.addWidget(QtWidgets.QLabel(FIRST.DATE), 1, 1)
grid_layout.addWidget(QtWidgets.QLabel('Report Issues'), 2, 0)
label = QtWidgets.QLabel(('<a href="https://github.com/'
'vrtadmin/FIRST-plugin-ida/issues">'
'github.com/vrtadmin/FIRST-plugin-ida</a>'))
label.setTextFormat(Qt.RichText)
label.setTextInteractionFlags(Qt.TextBrowserInteraction)
label.setOpenExternalLinks(True)
grid_layout.addWidget(label, 2, 1)
grid_layout.setColumnMinimumWidth(0, 100)
grid_layout.setColumnStretch(1, 1)
grid_layout.setContentsMargins(10, 0, 0, 0)
container.addSpacing(10)
container.addLayout(grid_layout)
container.addStretch()
copyright = '{}-{} Cisco Systems, Inc.'.format(FIRST.BEGIN, FIRST.END)
label = QtWidgets.QLabel(copyright)
label.setStyleSheet('font: 10px;')
label.setAlignment(Qt.AlignCenter)
container.addWidget(label)
return container
def view_applied(self):
self.thread_stop = True
container = QtWidgets.QVBoxLayout()
groups = None
label = QtWidgets.QLabel('Applied Metadata')
label.setStyleSheet('font: 18px;')
container.addWidget(label)
container.addSpacing(5)
description = ('FIRST metadata you\'ve applied in this IDB '
'are shown below. You can go to the function via '
'right clicking on the function and selecting View '
'or double clicking the function.')
description = QtWidgets.QLabel(description)
description.setWordWrap(True)
container.addWidget(description)
container.addSpacing(10)
data = FIRST.Metadata.get_functions_with_applied_metadata()
data = {d.address : d for d in data}
data_model = FIRST.Model.Check(data)
tree_view = FIRST.Model.TreeView(depth=1)
tree_view.setExpandsOnDoubleClick(False)
tree_view.setIndentation(15)
tree_view.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
tree_view.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
# Setup the Model's header
headers = [ ('Function', 'function name and address in this IDB', 0),
('Prototype', 'function prototype', 1),
('User', 'creator of the metadata', 2)]
for display_name, tooltip, i in headers:
item_header = QtGui.QStandardItem(display_name)
item_header.setToolTip(tooltip)
data_model.setHorizontalHeaderItem(i, item_header)
# Setup all other rows
name_str = '0x{0.address:08x}: {0.name}'
if not FIRST.Info.is_32bit():
name_str = name_str.replace(':08x}', ':016x}')
root_node = data_model.invisibleRootItem()
cmp_func = lambda x,y: cmp(x.address, y.address)
for match in sorted(list(data.values()), key=functools.cmp_to_key(cmp_func)):
# Row: <address and name> <prototype> <creator>
name = QtGui.QStandardItem(name_str.format(match))
prototype = QtGui.QStandardItem(match.prototype)
prototype.setToolTip(match.prototype)
creator = QtGui.QStandardItem(match.creator)
creator.setToolTip(match.creator)
info = [name, prototype, creator]
# Add row:
# Comment:
# (comment)
comment = match.comment
if not comment:
comment = '- No Comment -'
comment = QtGui.QStandardItem('Comment:\n' + comment)
comment.setColumnCount(8)
comment.setData(True, role=FIRSTUI.ROLE_COMMENT)
comment_list = [comment] + ([QtGui.QStandardItem()] * 2)
info[0].appendRow(comment_list)
# Mark all items noneditable and add id associated with the match
for item in info + comment_list:
item.setEditable(False)
item.setData(match.id, role=FIRSTUI.ROLE_ID)
item.setData(match.address, role=FIRSTUI.ROLE_ADDRESS)
root_node.appendRow(info)
tree_view.setModel(data_model)
self.applied_data_model = data_model
tree_view.setColumnWidth(0, 200) # Address and Function
tree_view.setColumnWidth(1, 400) # Prototype
tree_view.setColumnWidth(2, 20) # Author
# Keep a reference to the dialog so it doesn't hide before the
# user is done with it
self.history_dialogs = []
tree_view.setContextMenuPolicy(Qt.CustomContextMenu)
tree_view.customContextMenuRequested.connect(self.applied_custom_menu)
self.applied_tree_view = tree_view
container.addWidget(self.applied_tree_view)
return container
def applied_custom_menu(self, point):
index = self.applied_tree_view.indexAt(point)
address = index.data(FIRSTUI.ROLE_ADDRESS)
if not address:
return
menu = QtWidgets.QMenu(self.applied_tree_view)
goto_action = QtWidgets.QAction('&Go to Function', self.applied_tree_view)
goto_action.triggered.connect(lambda:IDAW.jumpto(address))
menu.addAction(goto_action)
metadata_id = index.data(FIRSTUI.ROLE_ID)
if metadata_id:
history_action = QtWidgets.QAction('View &History', self.applied_tree_view)
history_action.triggered.connect(lambda:self._metadata_history(metadata_id))
menu.addAction(history_action)
menu.exec_(QtGui.QCursor.pos())
def _metadata_history(self, metadata_id):
dialog = FIRSTUI.Dialog(None, FIRSTUI.History, metadata_id=metadata_id)
dialog.show()
# Keep a reference to the dialog so it doesn't hide before the
# user is done with it
self.history_dialogs.append(dialog)
def populate_main_form(self):
list_view = QtWidgets.QListView()
list_view.setFixedWidth(115)
list_view.setModel(self.views_model)
select = QtCore.QItemSelectionModel.Select
list_view.selectionModel().select(self.views_model.createIndex(0, 0), select)
list_view.clicked.connect(self.view_clicked)
current_view = QtWidgets.QWidget()
view = self.view_about()
if not view:
view = QtWidgets.QBoxLayout()
current_view.setLayout(view)
self.splitter = QtWidgets.QSplitter(Qt.Horizontal)
self.splitter.addWidget(list_view)
self.splitter.addWidget(current_view)
self.splitter.setChildrenCollapsible(False)
self.splitter.show()
outer_layout = QtWidgets.QHBoxLayout()
outer_layout.addWidget(self.splitter)
self.parent.setLayout(outer_layout)
def view_clicked(self, index):
key = self.views_model.data(index)
if key in self.views_ui:
# Get the new view
widget = QtWidgets.QWidget()
layout = self.views_ui[key]()
if not layout:
layout = QtWidgets.QVBoxLayout()
widget.setLayout(layout)
# Remove the old view to the splitter
old_widget = self.splitter.widget(1)
if old_widget:
old_widget.hide()
old_widget.deleteLater()
self.splitter.insertWidget(1, widget)
def check_function_accept(self, dialog):
FIRST.Callbacks.accepted(self, dialog)
def check_function(self, ctx):
if not IDAW.get_func(IDAW.get_screen_ea()):
title = 'Unable to derive function'
msg = ( 'Cannot upload function. Ensure the cursor is '
'positioned within a defined function (cursor '
'currently at 0x{0:X})').format(IDAW.get_screen_ea())
idaapi.execute_ui_requests((FIRSTUI.Requests.MsgBox(title, msg),))
return
dialog = FIRSTUI.Dialog(None, FIRSTUI.Check)
dialog.registerSuccessCallback(self.check_function_accept)
dialog.show()
def check_all_function(self, ctx):
dialog = FIRSTUI.Dialog(None, FIRSTUI.CheckAll)
dialog.registerSuccessCallback(self.check_function_accept)
dialog.show()
def upload_func(self, ctx):
dialog = FIRSTUI.Dialog(None, FIRSTUI.Upload)
dialog.registerSuccessCallback(self.check_function_accept)
dialog.show()
def upload_all_func(self, ctx):
dialog = FIRSTUI.Dialog(None, FIRSTUI.UploadAll)
dialog.registerSuccessCallback(self.check_function_accept)
dialog.show()
def update_funcs(self, ctx):
FIRST.Callbacks.Update()
data = FIRST.Metadata.get_functions_with_applied_metadata()
if data:
title = 'FIRST: Updating Metadata for Functions'
msg = ('There are {} functions with FIRST data. They are '
'being updated to reflect the most recent '
'metadata for each function.').format(len(data))
idaapi.execute_ui_requests((FIRSTUI.Requests.MsgBox(title, msg, QtWidgets.QMessageBox.Information),))
def view_history(self, ctx):
function = IDAW.get_func(IDAW.get_screen_ea())
if not function:
msg = '[1st] Unable to retrieve function at 0x{0:x}\n'.format(IDAW.get_screen_ea())
idaapi.execute_ui_requests((FIRSTUI.Requests.Print(msg),))
return
metadata = FIRST.Metadata.get_function(function.start_ea)
if not metadata:
message = '[1st] Unable to retrieve function at 0x{0:x}\n'
idaapi.execute_ui_requests((FIRSTUI.Requests.Print(message.format(metadata.address)),))
return
if not metadata.id:
message = '[1st] No FIRST metadata is applied to the function at 0x{0:x}\n'
idaapi.execute_ui_requests((FIRSTUI.Requests.Print(message.format(metadata.address)),))
return
dialog = FIRSTUI.Dialog(None, FIRSTUI.History, metadata_id=metadata.id)
dialog.show()
class FIRST(object):
debug = False
# About Information
#------------------------
VERSION = 'BETA'
DATE = 'May 2018'
BEGIN = 2014
END = 2018
plugin_enabled = False
show_welcome = False
server = None
config = None
config_path = os.path.join(idaapi.get_user_idadir(), 'first_beta.cfg')
installed_hooks = []
function_list = None
plugin = None
iat = []
# Colors used
color_changed = QtGui.QBrush(QtGui.QColor.fromRgb(255, 153, 139))
color_unchanged = QtGui.QBrush(QtGui.QColor.fromRgb(238, 238, 238))
color_default = QtGui.QBrush(QtGui.QColor.fromRgb(255, 255, 255))
color_selected = QtGui.QBrush(QtGui.QColor.fromRgb(160, 216, 241))
color_applied = QtGui.QBrush(QtGui.QColor.fromRgb(214, 227, 181))
@staticmethod
def initialize():
'''Initializes FIRST by installing hooks and populating required data
strucutres.'''
global g_network_headers
g_network_headers['User-Agent'] = "FIRST {} {} Cython {}({}.{}.{}) {}".format(
FIRST.VERSION,
FIRST.DATE,
sys.api_version,
sys.version_info.major,
sys.version_info.minor,
sys.version_info.releaselevel,
sys.platform
)
FIRST.installed_hooks = [FIRST.Hook.IDP(), FIRST.Hook.UI()]
[x.hook() for x in FIRST.installed_hooks]
FIRST.plugin = FIRST_FormClass()
@staticmethod
def cleanup_hooks():
if FIRST.installed_hooks:
for x in FIRST.installed_hooks:
x.unhook()
FIRST.installed_hooks = []
class Error(Exception):
'''FIRST Exception Class'''
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Metadata():
'''Class containing Misc Metadata functions.
Contains helper functions that will allow interaction with the memory
list containing all functions within the IDB.
This class contains only static methods and should be accessed as such.
'''
@staticmethod
def get_non_jmp_wrapped_functions():
'''Returns a list of functions addresses
Functions definited in the IDB, from auto analysis or manually
definited, are part of the list returned. Functions that are
just wrappers with a jmp instruction are not included.
Returns:
list: Empty list or list of integer values
The list of integer values correspond to a function's start
address
'''
addresses = []
for function_ea in IDAW.Functions():
function = IDAW.get_func(function_ea)
if function:
mnem = IDAW.print_insn_mnem(function.start_ea)
op_type = IDAW.get_operand_type(function.start_ea, 0)
if not (('jmp' == mnem) and (op_type == idc.o_mem)):
addresses.append(function.start_ea)
return addresses
@staticmethod
def get_segments_with_functions():
'''Returns a list of segments with defined functions in it.
Returns:
list: Empty list or list of segment_t objects
'''
data = []
if not FIRST.function_list:
return None
for segment_offset in FIRST.function_list:
data.append(IDAW.getseg(segment_offset + IDAW.get_imagebase()))
return data
@staticmethod
def get_segment_functions(segment):
'''Returns functions for a given segment.
Args:
segment (`segment_t`): The segment functions will be returned
from. segment_t objects are returned from IDA's getseg API.
Returns:
list: Empty list or list of MetadataShim objects on success.
None: None on failure.
Fails if argument is not a segment_t or there are no functions
in that segment.
'''
if not isinstance(segment, idaapi.segment_t):
return None
segment_offset = segment.start_ea - IDAW.get_imagebase()
if segment_offset not in FIRST.function_list:
return None
return list(FIRST.function_list[segment_offset].values())
@staticmethod
def populate_function_list():
'''Initializes FIRST's function list
This should be called to initialize the FIRST.function_list global
variable, thus it should be called once IDA's auto analysis is
complete to ensure it gets as many functions as possible.
Base case: User loads up sample in IDA for first time or IDB is
opened in IDA with FIRST for the first time action: create new
function list, save, monitor for changes
Complex case: User reopens an IDB that already has FIRST data in it
action: extract function list from IDB, monitor for changes
'''
if None != FIRST.function_list:
return
FIRST.function_list = {}
idaapi.show_wait_box('Initializing FIRST\'s cache')
for address in FIRST.Metadata.get_non_jmp_wrapped_functions():
function_name = IDAW.get_func_name(address)
function = FIRST.MetadataShim(address, function_name)
db_function = FIRST.DB.get_function(function=function)
# Function has not been saved to DB, create it and save it
if not db_function:
# If we failed to create a FIRSTMetadata object for the
# address then skip it
if not function:
temp_str = 'Cannot create function at address {0:x}\n'
idaapi.execute_ui_requests((FIRSTUI.Requests.Print(temp_str.format(address)),))
continue
FIRST.DB.save(function)
else:
function = db_function
segment = function.segment
if not segment:
temp_str = 'Cannot get function segment {0:x}\n'
idaapi.execute_ui_requests((FIRSTUI.Requests.Print(temp_str.format(function.address)),))
continue
seg_offset = segment - IDAW.get_imagebase()
if seg_offset not in FIRST.function_list:
FIRST.function_list[seg_offset] = {}
FIRST.function_list[seg_offset][function.offset] = function
idaapi.hide_wait_box()
@staticmethod
def get_function(function_address):
'''Get the MetadataShim object for a given function.
Args:
function_address (`int`): A functions start address. The value
should be the start address of the function or else the
function will return None.
Returns:
MetadataShim: object on success.
None on failure.
'''
if dict != type(FIRST.function_list):
return None
# Ensure this is the start of a function and not just a repeatable
# label somewhere else
function = IDAW.get_func(function_address)
if (not function) or (function_address != function.start_ea):
return None
# Calculate offset to function from segment
segment = IDAW.getseg(function.start_ea)
if not segment:
return None
seg_offset = segment.start_ea - IDAW.get_imagebase()
offset = function.start_ea - segment.start_ea
if ((seg_offset not in FIRST.function_list)
or (offset not in FIRST.function_list[seg_offset])):
return None
return FIRST.function_list[seg_offset][offset]
@staticmethod
def get_functions_with_applied_metadata():
'''Returns a list of functions with FIRST metadata applied to it.
Returns:
list: Empty list or list of `MetadataShim` objects
'''
applied_metadata = []
segments = FIRST.Metadata.get_segments_with_functions()
if segments:
for segment in segments:
functions = FIRST.Metadata.get_segment_functions(segment)
for function in functions:
if function.id:
applied_metadata.append(function)
return applied_metadata
class Info():
'''Information gathering functions.
Will get different information required by FIRST to interact with
server or other plug-in side operations.
This class contains only static methods and should be accessed as such.
Attributes:
processor_map (:obj:`dict`): Dictionary mapping between IDA's naming
convention to FIRST's.
include_bits (:obj:`list`): List of processors that should include
the number of bits.
'''
processor_map = {'metapc' : 'intel'}
include_bits = ['intel', 'arm']
@staticmethod
def set_file_details(md5, crc32, sha1=None, sha256=None):
'''Sets details about the sample.
This is a work around for situations where there is no original
sample on disk that IDA analyzes. FIRST requires a MD5 and CRC32 to
store functions, without it the function will not be saved.
Args:
md5 (:obj:`str`): Valid MD5 hash
'''
# Validate User Input
md5 = md5.lower()
if not re.match(r'^[a-f\d]{32}$', md5) or type(crc32) != int:
return
db = IDAW.get_array_id(FIRST_DB)
key = FIRST_INDEX['hashes']
if -1 == db:
db = IDAW.create_array(FIRST_DB)
# Get hashes from file
data = {'md5' : md5,
'sha1' : sha1,
'sha256' : sha256,
'crc32' : crc32}
IDAW.set_array_string(db, key, json.dumps(data))
# Update server class
if FIRST.server and hasattr(FIRST.server, 'binary_info'):
FIRST.server = FIRST.Server(FIRST.config, md5, crc32, sha1, sha256)
@staticmethod
def get_file_details():
'''Returns details about the sample.
The MD5 and CRC32 fields will always be returned since IDA Pro
provides that information. If the IDB is created with the original
sample then the sample will be hashed to get the SHA1 and SHA256.
All tthe data is stored in the IDB to prevent getting the
information multiple times.
Returns:
dict. Dictionary of file hashes and CRC32.
'''
db = IDAW.get_array_id(FIRST_DB)
key = FIRST_INDEX['hashes']
if -1 != db:
data = IDAW.get_array_element(IDAW.AR_STR, db, key)
if 0 != data:
return json.loads(data)
else:
db = IDAW.create_array(FIRST_DB)
# Get hashes from file
data = {'md5' : IDAW.retrieve_input_file_md5().hex(),
'sha1' : None,
'sha256' : None,
'crc32' : IDAW.retrieve_input_file_crc32()}
file_path = IDAW.get_input_file_path()
if file_path and exists(file_path):
with open(file_path, 'rb') as f:
f_data = f.read()