-
-
Notifications
You must be signed in to change notification settings - Fork 41
/
hashdb.py
2245 lines (1909 loc) · 90.2 KB
/
hashdb.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
########################################################################################
##
## This plugin is the client for the HashDB lookup service operated by OALABS:
##
## https://hashdb.openanalysis.net/
##
## _ _ _ ____________
## | | | | | | | _ \ ___ \
## | |_| | __ _ ___| |__ | | | | |_/ /
## | _ |/ _` / __| '_ \| | | | ___ \
## | | | | (_| \__ \ | | | |/ /| |_/ /
## \_| |_/\__,_|___/_| |_|___/ \____/
##
## HashDB is a community-sourced library of hashing algorithms used in malware.
## New hash algorithms can be added here: https://github.com/OALabs/hashdb
##
## Updated for IDA 7.xx and Python 3
##
## To install:
## Copy script into plugins directory, i.e: C:\Program Files\<ida version>\plugins
##
## To run:
## Configure Settings:
## Edit->Plugins->HashDB
## click `Refresh Algorithms` to pull a list of hash algorithms
## select the hash algorithm you need from the drop-down
## OK
## Lookup Hash:
## Highlight constant in IDA disassembly or psuedocode view
## Right-click -> HashDB Lookup
## If a hash is found it will be added to an enum controlled in the settings
## Right-click on the constant again -> Enum -> Select new hash enum
##
########################################################################################
__AUTHOR__ = '@herrcore'
PLUGIN_NAME = "HashDB"
PLUGIN_HOTKEY = 'Alt+`'
VERSION = '1.10.0'
import sys
import time
import idaapi
#--------------------------------------------------------------------------
# IDA Python version madness
#--------------------------------------------------------------------------
major, minor = map(int, idaapi.get_kernel_version().split("."))
assert (major > 6),"ERROR: HashDB plugin requires IDA v7+"
assert (sys.version_info >= (3, 5)), "ERROR: HashDB plugin requires Python 3.5"
# We need to make some adjustments for IDA 9
IDA_9 = major >= 9
if IDA_9:
import ida_ida
else:
import ida_enum
import idc
import ida_kernwin
import ida_name
import ida_bytes
import ida_netnode
import ida_typeinf
# Imports for the exception handler
import traceback
import json
import webbrowser
import urllib.parse
#--------------------------------------------------------------------------
# Setup IDA 9 globals
#--------------------------------------------------------------------------
if IDA_9:
BITS = 32 if not ida_ida.inf_is_64bit() else 64
BWN_DISASM = ida_kernwin.BWN_DISASM
BWN_PSEUDOCODE = ida_kernwin.BWN_PSEUDOCODE
SETMENU_APP = ida_kernwin.SETMENU_APP
else:
BITS = 32 if not idaapi.get_inf_structure().is_64bit() else 64
BWN_DISASM = idaapi.BWN_DISASMS
BWN_PSEUDOCODE = idaapi.BWN_PSEUDOCODE
SETMENU_APP = idaapi.SETMENU_APP
def get_enum(enum_name: str):
if IDA_9:
return idc.get_enum(enum_name)
else:
return ida_enum.get_enum(enum_name)
def import_type(idx: int, enum_name: str):
if IDA_9:
return idc.import_type(idx, enum_name)
else:
return ida_typeinf.import_type(ida_typeinf.get_idati(), idx, enum_name, 0)
def attach_action_to_popup(widget, popup_handle, name, popuppath=None, flags=0):
if IDA_9:
return ida_kernwin.attach_action_to_popup(widget, popup_handle, name, popuppath, flags)
else:
return idaapi.attach_action_to_popup(widget, popup_handle, name, popuppath, flags)
def get_enum_member_by_name(enum_value_name: str):
if IDA_9:
return idc.get_enum_member_by_name(enum_value_name)
else:
return ida_enum.get_enum_member_by_name(enum_value_name)
#--------------------------------------------------------------------------
# Global exception hook to detect plugin exceptions until
# we implement a proper test-driven development setup
# Note: minimum Python version support is 3.5
#--------------------------------------------------------------------------
HASHDB_REPORT_BUG_URL = "https://github.com/OALabs/hashdb-ida/issues/new"
def hashdb_exception_hook(exception_type, value, traceback_object):
is_hashdb_exception = False
frame_data = {
"user_data": {
"platform": sys.platform,
"python_version": '.'.join([str(sys.version_info.major), str(sys.version_info.minor), str(sys.version_info.micro)]),
"plugin_version": VERSION,
"ida": {
"kernel_version": ida_kernwin.get_kernel_version(),
"bits": BITS
}
},
"exception_data": {
"exception_type": exception_type.__name__,
"exception_value": str(value)
},
"frames": []}
frame_summaries = traceback.StackSummary.extract(traceback.walk_tb(traceback_object), capture_locals=True)
for frame_index, frame_summary in enumerate(frame_summaries):
file_name = frame_summary.filename
if "__file__" in globals():
if not file_name == __file__:
continue
is_hashdb_exception = True
# Save frame data
frame_data["frames"].append({
"frame_index": frame_index,
"line_number": frame_summary.lineno,
"function_name": frame_summary.name,
"line": frame_summary.line,
"locals": frame_summary.locals
})
if is_hashdb_exception:
class crash_detection_form(ida_kernwin.Form):
def __init__(self):
form = "BUTTON YES* Yes\nBUTTON CANCEL No\nHashDB Error!\n\n{format}"
controls = {
"format": super().StringLabel(
"""<center>
<p style="margin: 0; font-size: 20px; color: #F44336"><b>HashDB has detected an internal error.</b><p>
<p style="margin: 0; font-size: 12px">Would you like to submit a stack trace to the developers?</p>
<ol style="font-size: 11px; text-align: left">
<li>Selecting "Yes" will open a feedback dialogue and redirect you to:
<p style="margin: 0 4px 0 0;"><b><i>github.com/OALabs/hashdb-ida</i></b></p>
</li>
<li>All personally identifiable information will be removed.</li>
<li>Afterwards, you will be asked if you want to unload the plugin.</li>
</ol>
</center>""", super().FT_HTML_LABEL)
}
super().__init__(form, controls)
# Compile
self.Compile()
# Execute the crash detection form on the main thread
crash_form = crash_detection_form()
crash_button_selected = ida_kernwin.execute_sync(crash_form.Execute, ida_kernwin.MFF_FAST)
crash_form.Free()
# Did the user allow us to submit a request?
if crash_button_selected == 1: # Yes button
# Setup the body
body = "## Steps to reproduce:\n1. \n\n## Stack trace:\n```\n{}\n```".format(json.dumps(frame_data))
# Open the tab
global HASHDB_REPORT_BUG_URL
webbrowser.open_new_tab(HASHDB_REPORT_BUG_URL + "?" + urllib.parse.urlencode({
"title": "[BUG]: ",
"body": body
}))
# Ask the user if they want to terminate the plugin
class unload_plugin_form(ida_kernwin.Form):
def __init__(self):
form = "BUTTON YES* Yes\nBUTTON CANCEL No\nHashDB\n\n{format}"
controls = {
"format": super().StringLabel(
"""<center>
<p style="margin: 0; font-size: 20px; color: #F44336"><b>Would you like to unload the plugin?</b><p>
<p>This action will make the plugin unusable until IDA is restarted.</p>
</center>""", super().FT_HTML_LABEL)
}
super().__init__(form, controls)
# Compile
self.Compile()
unload_form = unload_plugin_form()
unload_button_selected = ida_kernwin.execute_sync(unload_form.Execute, ida_kernwin.MFF_FAST)
unload_form.Free()
if unload_button_selected == 1: # Yes button
global HASHDB_PLUGIN_OBJECT
ida_kernwin.execute_sync(HASHDB_PLUGIN_OBJECT.term, ida_kernwin.MFF_FAST)
sys.__excepthook__(exception_type, value, traceback_object)
sys.excepthook = hashdb_exception_hook
# Rest of the imports
import re
import functools
import requests
from typing import Union
# These imports are specific to the Worker implementation
import inspect
import logging
import threading
from threading import Thread
from dataclasses import dataclass, field
from typing import Callable
#--------------------------------------------------------------------------
# Global settings/variables
#--------------------------------------------------------------------------
HASHDB_API_URL ="https://hashdb.openanalysis.net"
HASHDB_USE_XOR = False
HASHDB_XOR_VALUE = 0
HASHDB_ALGORITHM = None
HASHDB_ALGORITHM_SIZE = 0
ENUM_PREFIX = "hashdb_strings"
NETNODE_NAME = "$hashdb"
# Variables for async operations
HASHDB_REQUEST_TIMEOUT = 15 # Limit to 15 seconds
HASHDB_REQUEST_LOCK = threading.Lock()
#--------------------------------------------------------------------------
# Setup Icon
#--------------------------------------------------------------------------
HASH_ICON_DATA = b"".join([b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08',
b'\x04\x00\x00\x00\xb5\xfa7\xea\x00\x00\x00\x04gAMA\x00\x00\xb1\x8f\x0b\xfca',
b'\x05\x00\x00\x00 cHRM\x00\x00z&\x00\x00\x80\x84\x00\x00\xfa\x00\x00\x00\x80',
b'\xe8\x00\x00u0\x00\x00\xea`\x00\x00:\x98\x00\x00\x17p\x9c\xbaQ<\x00\x00\x00',
b'\x02bKGD\x00\xff\x87\x8f\xcc\xbf\x00\x00\x00\tpHYs\x00\x00\x0b\x13\x00\x00',
b'\x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07tIME\x07\xe5\t\x18\x12\x18(\xba',
b'\xecz-\x00\x00\x01#IDAT(\xcfm\xd1\xbdJ\x9ba\x18\xc6\xf1_\xde<\xd5d\x08\xc1',
b'\xb46\x967!\x1d,\x88\xd0\xa1P\xe8\x01\x14\x0c\xb8\xbbt\xa9\xa3\x07\xd0\xb9',
b'\xab \x1e\x83s\x87R\xa4]K\xe8".*NEpJZL\x9b\xa2V\x90\xc6\xa4\xc6\xc7%\x92\xa0',
b'\xfe\xd7\xeb\xe6\xe6\xfa`\x9c\x8c\x82\x04\xe4\xe4\xdd\xc3\xb4\x0fV\x95\xf0',
b'\xd6\x17\x0bw\x0f\xeaz\xf6<\xf4\xc0\xa6h\x05\xc3\x877,\x98\xf0\xd5\xb1g^i\xfb',
b'\x06\x01AY\x10\x15\xbdv\xe9\xbb\x19\x8bf4\x0c\xa4~g\x90\xfa\xa8\xeaJ\xd6c\x89',
b'\x8e\xbe\xa2\xa2s\x7f\xb5\xbcI\xc6\x12\x94\x04\'\xfa\xf2\x8azNen\xa4\xac\'*^8',
b'\xd0\xb5\xa4\xec\xbd\xe8\xb3\xa7\xaaR!\x08\xca\x12\x03\xb3j\x9a\x0e\xe5\xbc',
b'\xc4\x8e\xbe\xa8c@\xcd\x96\x9f\x9a\xfe\x88\xbaZZ.D\x1d?lKG1\'\x94\\:\x11M\x99t',
b'\xa6;r\x10\xa4*\x96\xfd\xb7\xef\xb9Y\r\xd1;\xa9\x9aT\x18U\xb4&Z\xc7\x9c#m\xf3',
b'\xb7+~dOO\x1d+\xa2M\x93#);\xdc\xae\xec\x97\r\xff\x94L\xf9d\xf7\xeeL\x89\xc2',
b'\xd0V^n\\\xb8\x06\xd6\xa1L\xe6_H\xbf\xfc\x00\x00\x00%tEXtdate:create\x00202',
b'1-09-24T18:24:40+00:00\xd7;f\xf5\x00\x00\x00%tEXtdate:modify\x002021-09-24T',
b'18:24:40+00:00\xa6f\xdeI\x00\x00\x00WzTXtRaw profile type iptc\x00\x00x\x9c',
b'\xe3\xf2\x0c\x08qV((\xcaO\xcb\xccI\xe5R\x00\x03#\x0b.c\x0b\x13#\x13K\x93\x14',
b'\x03\x13 D\x804\xc3d\x03#\xb3T \xcb\xd8\xd4\xc8\xc4\xcc\xc4\x1c\xc4\x07\xcb',
b'\x80H\xa0J.\x00\xea\x17\x11t\xf2B5\x95\x00\x00\x00\x00IEND\xaeB`\x82'])
HASH_ICON = ida_kernwin.load_custom_icon(data=HASH_ICON_DATA, format="png")
XOR_ICON_DATA = b"".join([b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x04',
b'\x00\x00\x00\xb5\xfa7\xea\x00\x00\x00\x04gAMA\x00\x00\xb1\x8f\x0b\xfca\x05\x00',
b'\x00\x00 cHRM\x00\x00z&\x00\x00\x80\x84\x00\x00\xfa\x00\x00\x00\x80\xe8\x00\x00',
b'u0\x00\x00\xea`\x00\x00:\x98\x00\x00\x17p\x9c\xbaQ<\x00\x00\x00\x02bKGD\x00\xff',
b'\x87\x8f\xcc\xbf\x00\x00\x00\tpHYs\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a',
b'\x9c\x18\x00\x00\x00\x07tIME\x07\xe5\t\x18\x12\x0b";\xd6\xd2\xa1\x00\x00\x00\xc3',
b'IDAT(\xcf\xa5\xd01N\x02\x01\x14\x04\xd0\x07B01\x9a\x10b\x89%\t\x8dg\xa0\xd0f-\xb8',
b'\x80x\x86\x8d\r\xd9#X\xee\x05(\x94\x0b\xd0\xd0@A\xcb\t4\xdb\x98\xd8Z\x90\xacv\x82',
b'Z,\xac\xab1P0\xdd\xfc\xcc\x9f\xcc\x0c\xfb\xa2\xf4\x8bU\x9c \xb5\xfcOPu\xe9F\x0b',
b'\x89{\x13\x1f\xd9\xf9 \xff\xbd\x15\x99;\xf2.\x11\xaa\x99\xfb,\x9a_y\x12 \x16#X3',
b'\x94\xd7>\xd7F\xc6\xb9|l\xa4\x97\xb9g\x19\xea\xa6^=*\xe9`\xe6K\xdb\xa9\x0b\x8b',
b'\x8d\xc3\x16T@*\xf1\xa2\x8f\x18!\xee\x9cI\x7f2\xac\x0cu7\xb1\x10\xe8z\xb0*\xd6',
b'|v(\xd2\xd4\xd6p.40\xccj\xee\x1c\xea\xef\xd4\xc7x+N\xbd?\xbe\x01\xa7\xee.6\xd9',
b'\xf6\xa5\xd2\x00\x00\x00%tEXtdate:create\x002021-09-24T18:11:34+00:00Vz\xe6\xba',
b'\x00\x00\x00%tEXtdate:modify\x002021-09-24T18:11:34+00:00\'\'^\x06\x00\x00\x00',
b'WzTXtRaw profile type iptc\x00\x00x\x9c\xe3\xf2\x0c\x08qV((\xcaO\xcb\xccI\xe5R',
b'\x00\x03#\x0b.c\x0b\x13#\x13K\x93\x14\x03\x13 D\x804\xc3d\x03#\xb3T \xcb\xd8\xd4',
b'\xc8\xc4\xcc\xc4\x1c\xc4\x07\xcb\x80H\xa0J.\x00\xea\x17\x11t\xf2B5\x95\x00\x00',
b'\x00\x00IEND\xaeB`\x82'])
XOR_ICON = ida_kernwin.load_custom_icon(data=XOR_ICON_DATA, format="png")
HUNT_ICON_DATA = b"".join([b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x04',
b'\x00\x00\x00\xb5\xfa7\xea\x00\x00\x00\x04gAMA\x00\x00\xb1\x8f\x0b\xfca\x05\x00',
b'\x00\x00 cHRM\x00\x00z&\x00\x00\x80\x84\x00\x00\xfa\x00\x00\x00\x80\xe8\x00\x00u0',
b'\x00\x00\xea`\x00\x00:\x98\x00\x00\x17p\x9c\xbaQ<\x00\x00\x00\x02bKGD\x00\xff\x87',
b'\x8f\xcc\xbf\x00\x00\x00\tpHYs\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a\x9c\x18',
b'\x00\x00\x00\x07tIME\x07\xe5\t\x1d\x10#"R\xd1XW\x00\x00\x01.IDAT(\xcf\x8d\xd1;K\x9b',
b'\x01\x18\xc5\xf1\x9fI\xa8C\xbd\xf1\x0e\xdd\xd2\xc5NJ\x07;h\xd5\xa1\xf1\x0bT\xd4M',
b'\x14//\x82\xad\x8b\x83\x93`\xf1\x02~\x84\x08-b\x1c\xea\xe6\xe2 \x08^\x9aAQ\x07\x87',
b'R\x9d:\x99Atx\x15\xab`\xbc\xd0\x0eitS\xcf\xf2\xc0\xe1\xf0\x1c\xf8\x9f\x12\x0f*Q!@',
b'\xe4\xdc\xdf\x07\xb3xkuz\xe7\x05\xae\xedY\xb0_\x08\x15\x02\t=\x06l\xdap\x89\x97Z4',
b'\xfbf\xde-\t\xd0#4\xa1J\xef\xff\x8aE\xab\xc60[\xf8\xf0\xd6W\x93\xde\xfb`\xce!^\xeb',
b'\x93\xb5\xed\x8b\x01\xbf\xe2\x18v\xe4T\xbbQ\xcd\xba\xa4\\I\xebw\xe0N\x8d\xb5\x98Ju~h',
b'\x93\xd1\xaa\xda\xb8q\xd5>\xcah\x93U\xa72&P\xeaB \xa7\xde\x8cA\x83f4\xc8\t\xfcQ*\x88yB',
b'\t\x91\xbc2\x91\xa4]\x9f\xa4\xf1\xd9\x8e\xa4H\xb9\xbc(.\xaf\xd6\x1b\xebBi\xaftK\xf9i',
b'\xc9\x88\xef\x1a\xe5,\xc7ql\xc8\x8a;\xa1UK\xb2n\x8c\xc8\xfa\xad\xcb\xb4\x93\x02\xc9PhJ',
b'\x95\x8e{Pg\xc6\xcc\x16A\x15Qo\xd9p\x812-\x9a\x8a\xa8\x9f9\xd6#s\xff\x03\xabm^\xab\xaf',
b'\xe8z\xc0\x00\x00\x00%tEXtdate:create\x002021-09-29T16:35:34+00:00\xf4Q\xb1\xe8\x00\x00',
b'\x00%tEXtdate:modify\x002021-09-29T16:35:34+00:00\x85\x0c\tT\x00\x00\x00WzTXtRaw prof',
b'ile type iptc\x00\x00x\x9c\xe3\xf2\x0c\x08qV((\xcaO\xcb\xccI\xe5R\x00\x03#\x0b.c\x0b',
b'\x13#\x13K\x93\x14\x03\x13 D\x804\xc3d\x03#\xb3T \xcb\xd8\xd4\xc8\xc4\xcc\xc4\x1c',
b'\xc4\x07\xcb\x80H\xa0J.\x00\xea\x17\x11t\xf2B5\x95\x00\x00\x00\x00IEND\xaeB`\x82'])
HUNT_ICON = ida_kernwin.load_custom_icon(data=HUNT_ICON_DATA, format="png")
SCAN_ICON_DATA = b"".join([b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x04\x00\x00',
b'\x00\xb5\xfa7\xea\x00\x00\x00\x04gAMA\x00\x00\xb1\x8f\x0b\xfca\x05\x00\x00\x00 cHRM',
b'\x00\x00z&\x00\x00\x80\x84\x00\x00\xfa\x00\x00\x00\x80\xe8\x00\x00u0\x00\x00\xea`\x00',
b'\x00:\x98\x00\x00\x17p\x9c\xbaQ<\x00\x00\x00\x02bKGD\x00\xff\x87\x8f\xcc\xbf\x00\x00',
b'\x00\tpHYs\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a\x9c\x18\x00\x00\x00\x07tIME\x07',
b'\xe5\n\x08\x17\x1c\x04\xfd*<n\x00\x00\x01#IDAT(\xcfe\xd1\xb1K\xe2\x01\x18\xc6\xf1\x8f',
b'\xf6\xcb\xeb\xd0\x04\xc7 \xa8Ii\x89\xa2\xed~\x16\xc4m\xd6\xbf\xd0\x18\xed\xd1m\x07F-ECK',
b'\xa0K\xc49_\rACk\x10\xdc\x12\x04\x91qR\xd2\xd0PS\xd7\xa0h\x905\xe8\x85\xd9\xf7\x1d\xdfgx',
b'\xdf\xe7K\x9b@\xa8\xa8\xa2aO\x9f.\x02\x90\xb2l\xc9\x80\xb2s\'ZzH)i\xda\x17\x8a\x8b\x89',
b'\xf6\xae\xa3\xd65m\x88\xcbXud\xa57\x12z\xf0[\xc2\xbc\xaa\xbaK?{\x03EO\xa6e\\\xbb\x94',
b'\x93\xfcx"\xfc\xf5GB^MN\xca\x8a\x1f\x86\x0c\xf8\xda\x99\xfe\xc0\xb0s\xcf\xa6T\x9dZ\xb4',
b'\xe5\xc5\x82G-\x11Q-\xd5\xc0g^}1\xe9\x9f\x8aq\x13\x81;#b\xce|\x97\xb5\x8bW\xbf\xcc*)',
b'\xd8q,A\xe1\xfd\xc8\xb2\x9c\xa4\xa49W\xae\xa5\xcdxR t\xdfy\xf3F\xdd\x85\x0bu7\xe6\r:p/',
b'\xec.*-\xef\xd0\xa1\xbc\xb4\x84MMk\xedN\xfeW\x9d\x15\x17\x13\x13\x97u\xa0\xa9$E\xe4\x83',
b'\xac+\xb7\x185\xa6\xa1h\xdbc\xb7\xd5\xb6\xee\x9a\x9a\x8a\xa2o\x1d\xcf\xde\x00\x9fhY\xc0',
b'\x9b\x9d\xab^\x00\x00\x00%tEXtdate:create\x002021-10-08T23:28:04+00:00\xee\x90\xd3~\x00',
b'\x00\x00%tEXtdate:modify\x002021-10-08T23:28:04+00:00\x9f\xcdk\xc2\x00\x00\x00WzTXtRaw ',
b'profile type iptc\x00\x00x\x9c\xe3\xf2\x0c\x08qV((\xcaO\xcb\xccI\xe5R\x00\x03#\x0b.c\x0b',
b'\x13#\x13K\x93\x14\x03\x13 D\x804\xc3d\x03#\xb3T \xcb\xd8\xd4\xc8\xc4\xcc\xc4\x1c\xc4\x07',
b'\xcb\x80H\xa0J.\x00\xea\x17\x11t\xf2B5\x95\x00\x00\x00\x00IEND\xaeB`\x82'])
SCAN_ICON = ida_kernwin.load_custom_icon(data=SCAN_ICON_DATA, format="png")
#--------------------------------------------------------------------------
# Error class
#--------------------------------------------------------------------------
class HashDBError(Exception):
pass
#--------------------------------------------------------------------------
# Worker implementation
#--------------------------------------------------------------------------
@dataclass(unsafe_hash=True)
class Worker(Thread):
"""The worker implementation for multi-threading support."""
target: Callable
args: tuple = field(default_factory=tuple, compare=False)
done_callback: Callable = None
error_callback: Callable = None
def __post_init__(self):
"""Required to initialize the base class (Thread)."""
super().__init__(target=self.__wrapped_target, args=self.args, daemon=True)
def __wrapped_target(self, *args, **kwargs):
"""
Wraps the target function to allow callbacks and error handling.
@raise Exception: if an unhandled exception is encountered it will
be raised
"""
try:
# Execute the target
results = self.target(*args, **kwargs)
# Execute the done callback, if it exists
if self.done_callback is not None:
# Call the function based on the amount of arguments it expects
argument_spec = inspect.getfullargspec(self.done_callback)
argument_count = len(argument_spec.args)
if argument_count > 1:
self.done_callback(*results)
elif argument_count == 1 and results is not None:
self.done_callback(results)
else:
self.done_callback()
except Exception as exception:
# Execute the error callback, if it exits;
# otherwise raise the exception (unhandled)
if self.error_callback is not None:
# Call the function based on the amount of arguments it expects
argument_spec = inspect.getfullargspec(self.error_callback)
argument_count = len(argument_spec.args)
if argument_count == 1:
self.error_callback(exception)
else:
self.error_callback()
else:
raise exception
finally:
# Cleanup the callbacks (decrease reference counts)
if self.done_callback is not None:
del self.done_callback
if self.error_callback is not None:
del self.error_callback
#--------------------------------------------------------------------------
# HashDB API
#--------------------------------------------------------------------------
def get_algorithms(api_url='https://hashdb.openanalysis.net', timeout=None):
# Handle an empty timeout
global HASHDB_REQUEST_TIMEOUT
if timeout is None:
timeout = HASHDB_REQUEST_TIMEOUT
algorithms_url = api_url + '/hash'
r = requests.get(algorithms_url, timeout=timeout)
if not r.ok:
raise HashDBError("Get algorithms API request failed, status %s" % r.status_code)
results = r.json()
algorithms = []
for algorithm in results.get('algorithms',[]):
size = determine_algorithm_size(algorithm.get('type', None))
if size == 'Unknown':
idaapi.msg("ERROR: Unknown algorithm type encountered when fetching algorithms: %s" % size)
algorithms.append([algorithm.get('algorithm'), size])
return algorithms
def get_strings_from_hash(algorithm, hash_value, xor_value=0, api_url='https://hashdb.openanalysis.net', timeout=None):
# Handle an empty timeout
global HASHDB_REQUEST_TIMEOUT
if timeout is None:
timeout = HASHDB_REQUEST_TIMEOUT
hash_value ^= xor_value
hash_url = api_url + '/hash/%s/%d' % (algorithm, hash_value)
r = requests.get(hash_url, timeout=timeout)
if not r.ok:
raise HashDBError("Get hash API request failed, status %s" % r.status_code)
results = r.json()
# Remove null bytes from non-api strings
hashes = results.get('hashes',[])
out_hashes = []
for hash_info in hashes:
if not hash_info.get('string',{}).get('is_api',True):
hash_info['string']['string'] = hash_info['string']['string'].replace('\x00','')
out_hashes.append(hash_info)
return {'hashes':out_hashes}
def get_module_hashes(module_name, algorithm, permutation, api_url='https://hashdb.openanalysis.net', timeout=None):
# Handle an empty timeout
global HASHDB_REQUEST_TIMEOUT
if timeout is None:
timeout = HASHDB_REQUEST_TIMEOUT
module_url = api_url + '/module/%s/%s/%s' % (module_name, algorithm, permutation)
r = requests.get(module_url, timeout=timeout)
if not r.ok:
raise HashDBError("Get hash API request failed, status %s" % r.status_code)
results = r.json()
return results
def hunt_hash(hash_value, api_url='https://hashdb.openanalysis.net', timeout = None):
# Handle an empty timeout
global HASHDB_REQUEST_TIMEOUT
if timeout is None:
timeout = HASHDB_REQUEST_TIMEOUT
matches = []
hash_list = [hash_value]
module_url = api_url + '/hunt'
r = requests.post(module_url, json={"hashes": hash_list}, timeout=timeout)
if not r.ok:
print(module_url)
print(hash_list)
print(r.json())
raise HashDBError("Get hash API request failed, status %s" % r.status_code)
for hit in r.json().get('hits',[]):
algo = hit.get('algorithm',None)
if (algo != None) and (algo not in matches):
matches.append(algo)
return matches
#--------------------------------------------------------------------------
# Save and restore settings
#--------------------------------------------------------------------------
def load_settings():
global HASHDB_API_URL
global HASHDB_USE_XOR, HASHDB_XOR_VALUE
global HASHDB_ALGORITHM, ENUM_PREFIX
global NETNODE_NAME
node = ida_netnode.netnode(NETNODE_NAME)
if ida_netnode.exist(node):
if bool(node.hashstr("HASHDB_API_URL")):
HASHDB_API_URL = node.hashstr("HASHDB_API_URL")
if bool(node.hashstr("HASHDB_USE_XOR")):
if node.hashstr("HASHDB_USE_XOR").lower() == "true":
HASHDB_USE_XOR = True
else:
HASHDB_USE_XOR = False
if bool(node.hashstr("HASHDB_XOR_VALUE")):
HASHDB_XOR_VALUE = int(node.hashstr("HASHDB_XOR_VALUE"))
if bool(node.hashstr("HASHDB_ALGORITHM")) and bool(node.hashstr("HASHDB_ALGORITHM_SIZE")):
successful = set_algorithm(node.hashstr("HASHDB_ALGORITHM"), node.hashstr("HASHDB_ALGORITHM_SIZE"))
if not successful:
idaapi.msg("HashDB failed to set the algorithm when parsing the saved config!\n")
if bool(node.hashstr("ENUM_PREFIX")):
ENUM_PREFIX = node.hashstr("ENUM_PREFIX")
idaapi.msg("HashDB configuration loaded!\n")
else:
idaapi.msg("No saved HashDB configuration\n")
return
def save_settings():
global HASHDB_API_URL
global HASHDB_USE_XOR, HASHDB_XOR_VALUE
global HASHDB_ALGORITHM, ENUM_PREFIX
global NETNODE_NAME
# Check if our netnode already exists, otherwise create a new one
node = ida_netnode.netnode(NETNODE_NAME)
if not ida_netnode.exist(node):
node = ida_netnode.netnode()
if not node.create(NETNODE_NAME):
idaapi.msg("ERROR: Unable to save HashDB settings, failed to create the netnode.\n")
return
if HASHDB_API_URL != None:
node.hashset_buf("HASHDB_API_URL", str(HASHDB_API_URL))
if HASHDB_USE_XOR != None:
node.hashset_buf("HASHDB_USE_XOR", str(HASHDB_USE_XOR))
if HASHDB_XOR_VALUE != None:
node.hashset_buf("HASHDB_XOR_VALUE", str(HASHDB_XOR_VALUE))
if HASHDB_ALGORITHM != None:
node.hashset_buf("HASHDB_ALGORITHM", str(HASHDB_ALGORITHM))
if HASHDB_ALGORITHM_SIZE != None:
node.hashset_buf("HASHDB_ALGORITHM_SIZE", str(HASHDB_ALGORITHM_SIZE))
if ENUM_PREFIX != None:
node.hashset_buf("ENUM_PREFIX", str(ENUM_PREFIX))
idaapi.msg("HashDB settings saved\n")
#--------------------------------------------------------------------------
# Settings form
#--------------------------------------------------------------------------
class hashdb_settings_t(ida_kernwin.Form):
"""Global settings form for hashdb"""
class algorithm_chooser_t(ida_kernwin.Choose):
"""
A simple chooser to be used as an embedded chooser
"""
def __init__(self, algo_list):
ida_kernwin.Choose.__init__(
self,
"",
[
["Algorithm", 15],
["Size (Bits)", 5]
],
flags=0,
embedded=True,
width=30,
height=6)
self.items = algo_list
self.icon = None
def OnGetLine(self, n):
return self.items[n]
def OnGetSize(self):
return len(self.items)
def __init__(self, algorithms):
self.__n = 0
F = ida_kernwin.Form
F.__init__(self,
r"""BUTTON YES* Ok
BUTTON CANCEL Cancel
HashDB Settings
{FormChangeCb}
<##API URL :{iServer}>
<##Enum Prefix :{iEnum}>
<Enable XOR:{rXor}>{cXorGroup}> | <##:{iXor}>(hex)
<Select algorithm :{cAlgoChooser}><Refresh Algorithms:{iBtnRefresh}>
""", { 'FormChangeCb': F.FormChangeCb(self.OnFormChange),
'iServer': F.StringInput(),
'iEnum': F.StringInput(),
'cXorGroup': F.ChkGroupControl(("rXor",)),
'iXor': F.NumericInput(tp=F.FT_RAWHEX),
'cAlgoChooser' : F.EmbeddedChooserControl(hashdb_settings_t.algorithm_chooser_t(algorithms)),
'iBtnRefresh': F.ButtonInput(self.OnBtnRefresh),
})
def OnBtnRefresh(self, code=0):
api_url = self.GetControlValue(self.iServer)
algorithms = []
try:
ida_kernwin.show_wait_box("HIDECANCEL\nPlease wait...")
algorithms = get_algorithms(api_url=api_url)
except Exception as e:
idaapi.msg("ERROR: HashDB API request failed: %s\n" % e)
finally:
ida_kernwin.hide_wait_box()
# Sort the algorithms by algorithm name (lowercase)
sorted_algorithms = sorted(algorithms, key = lambda algorithm: algorithm[0].lower())
self.cAlgoChooser.chooser.items = sorted_algorithms
self.RefreshField(self.cAlgoChooser)
def OnFormChange(self, fid):
if fid == -1:
# Form is initialized
# Hide Xor input if dissabled
if self.GetControlValue(self.cXorGroup) == 1:
self.EnableField(self.iXor, True)
else:
self.EnableField(self.iXor, False)
self.SetFocusedField(self.cAlgoChooser)
elif fid == self.cXorGroup.id:
if self.GetControlValue(self.cXorGroup) == 1:
self.EnableField(self.iXor, True)
else:
self.EnableField(self.iXor, False)
else:
pass
#print("Unknown fid %r" % fid)
return 1
@staticmethod
def show(api_url="https://hashdb.openanalysis.net",
enum_prefix="hashdb_strings",
use_xor=False,
xor_value=0,
algorithms=[]):
global HASHDB_API_URL
global HASHDB_USE_XOR
global HASHDB_XOR_VALUE
global HASHDB_ALGORITHM
global ENUM_PREFIX
# Sort the algorithms
sorted_algorithms = sorted(algorithms, key = lambda algorithm: algorithm[0].lower())
f = hashdb_settings_t(sorted_algorithms)
f, args = f.Compile()
# Set default values
f.iServer.value = api_url
f.iEnum.value = enum_prefix
if use_xor:
f.rXor.checked = True
else:
f.rXor.checked = False
f.iXor.value = xor_value
# Show form
ok = f.Execute()
if ok == 1:
# Save default settings first
HASHDB_USE_XOR = f.rXor.checked
HASHDB_XOR_VALUE = f.iXor.value
HASHDB_API_URL = f.iServer.value
ENUM_PREFIX = f.iEnum.value
# Check if algorithm is selected
if f.cAlgoChooser.selection == None:
# No algorithm selected bail!
idaapi.msg("HashDB: No algorithm selected!\n")
f.Free()
return False
# Set the algorithm
algorithm = f.cAlgoChooser.chooser.items[f.cAlgoChooser.selection[0]]
set_algorithm(algorithm[0], algorithm[1]) # Error messages handled inside of set_algorithm
f.Free()
return True
else:
f.Free()
return False
#--------------------------------------------------------------------------
# Hash collision select form
#--------------------------------------------------------------------------
class match_select_t(ida_kernwin.Form):
"""Simple form to select string match during hash collision"""
def __init__(self, collision_strings):
self.__n = 0
F = ida_kernwin.Form
F.__init__(self,
r"""BUTTON YES* Ok
HashDB Hash Collision
{FormChangeCb}
More than one string matches this hash!
<Select the correct string :{cbCollisions}>
""", { 'FormChangeCb': F.FormChangeCb(self.OnFormChange),
'cbCollisions': F.DropdownListControl(
items=collision_strings,
readonly=True,
selval=0),
})
def OnFormChange(self, fid):
if fid == -1:
# Form is initialized
self.SetFocusedField(self.cbCollisions)
elif fid == self.cbCollisions.id:
sel_idx = self.GetControlValue(self.cbCollisions)
else:
pass
#print("Unknown fid %r" % fid)
return 1
@staticmethod
def show(collision_strings):
global HASHDB_API_URL
global HASHDB_USE_XOR
global HASHDB_XOR_VALUE
global HASHDB_ALGORITHM
f = match_select_t(collision_strings)
f, args = f.Compile()
# Show form
ok = f.Execute()
if ok == 1:
string_selection = f.cbCollisions[f.cbCollisions.value]
f.Free()
return string_selection
else:
f.Free()
return None
#--------------------------------------------------------------------------
# Hash hunt results form
#--------------------------------------------------------------------------
class hunt_result_form_t(ida_kernwin.Form):
class algorithm_chooser_t(ida_kernwin.Choose):
"""
A simple chooser to be used as an embedded chooser
"""
def __init__(self, algo_list):
ida_kernwin.Choose.__init__(
self,
"",
[
["Algorithm", 10],
["Size (Bits)", 5]
],
flags=0,
embedded=True,
width=30,
height=6)
self.items = algo_list
self.icon = None
def OnGetLine(self, n):
return self.items[n]
def OnGetSize(self):
return len(self.items)
def __init__(self, algo_list, msg):
self.invert = False
F = ida_kernwin.Form
F.__init__(
self,
r"""BUTTON YES* OK
Matched Algorithms
{FormChangeCb}
{cStrStatus}
<:{cAlgoChooser}>
""", {
'cStrStatus': F.StringLabel(msg),
'FormChangeCb': F.FormChangeCb(self.OnFormChange),
'cAlgoChooser' : F.EmbeddedChooserControl(hunt_result_form_t.algorithm_chooser_t(algo_list))
})
def OnFormChange(self, fid):
if fid == -1:
# Hide algorithm chooser if empty
if self.cAlgoChooser.chooser.items == []:
self.ShowField(self.cAlgoChooser, False)
return 1
def show(algo_list):
global HASHDB_API_URL
global HASHDB_USE_XOR
global HASHDB_XOR_VALUE
global HASHDB_ALGORITHM
# Set default values
if len(algo_list) == 0:
msg = "No algorithms matched the hash."
f = hunt_result_form_t(algo_list, msg)
else:
msg = "The following algorithms contain a matching hash.\nSelect an algorithm to set as the default for HashDB."
f = hunt_result_form_t(algo_list, msg)
f, args = f.Compile()
# Show form
ok = f.Execute()
if ok == 1:
if f.cAlgoChooser.selection == None:
# No algorithm selected bail!
f.Free()
return False
# Set the algorithm
algorithm = f.cAlgoChooser.chooser.items[f.cAlgoChooser.selection[0]]
set_algorithm(algorithm[0], algorithm[1]) # Error messages handled inside of set_algorithm
f.Free()
return True
else:
f.Free()
return False
#--------------------------------------------------------------------------
# Module import select form
#--------------------------------------------------------------------------
class api_import_select_t(ida_kernwin.Form):
"""Simple form to select module to import apis from"""
def __init__(self, string_value, module_list):
self.__n = 0
F = ida_kernwin.Form
F.__init__(self,
r"""BUTTON YES* Import
BUTTON CANCEL No
HashDB Bulk Import
{FormChangeCb}
{cStr1}
Do you want to import all function hashes from this module?
<Select module :{cbModules}>
""", { 'FormChangeCb': F.FormChangeCb(self.OnFormChange),
'cStr1': F.StringLabel("<span style='float:left;'>The hash for <b>"+string_value+"</b> is a module function.<span>", tp=F.FT_HTML_LABEL),
'cbModules': F.DropdownListControl(
items=module_list,
readonly=True,
selval=0),
})
def OnFormChange(self, fid):
if fid == -1:
# Form is initialized
self.SetFocusedField(self.cbModules)
elif fid == self.cbModules.id:
sel_idx = self.GetControlValue(self.cbModules)
else:
pass
#print("Unknown fid %r" % fid)
return 1
@staticmethod
def show(string_value, module_list):
f = api_import_select_t(string_value, module_list)
f, args = f.Compile()
# Show form
ok = f.Execute()
if ok == 1:
module_selection = f.cbModules[f.cbModules.value]
f.Free()
return module_selection
else:
f.Free()
return None
#--------------------------------------------------------------------------
# Unqualified name replacement form
# Logic: When an unqualified name is encountered, the user is asked to
# provide a replacement.
# Example: "-path" is an unqualified name, the user should replace it with
# a qualified name such as "_path"
#--------------------------------------------------------------------------
class unqualified_name_replace_t(ida_kernwin.Form):
def __init__(self, unqualified_name: str, invalid_characters: list) -> None:
form = "BUTTON YES* Replace\n" \
"BUTTON CANCEL Skip\n" \
"HashDB: Please replace the invalid characters\n\n" \
"{form_change_callback}\n" \
"Some of the characters in the hashed string are invalid (highlighted red):\n" \
"{unqualified_name}\n" \
"<##New name\: :{new_name}>"
invalid_characters_html = "<span style=\"font-size: 16px\">{}</span>"
controls = {
"form_change_callback": super().FormChangeCb(self.form_changed),
"unqualified_name": super().StringLabel(
invalid_characters_html.format(html_format_invalid_characters(
unqualified_name, invalid_characters)),
super().FT_HTML_LABEL),
# value -> initial value
"new_name": super().StringInput(value=unqualified_name)
}
super().__init__(form, controls)
# Compile
self.Compile()
def form_changed(self, field_id: int) -> int:
# Form initialized, focus to the new name text field
if field_id == -1:
self.SetFocusedField(self.new_name)
return 1
@staticmethod
def show(unqualified_name: str, invalid_characters: list) -> str:
"""
Show the unqualified name replace form and return
the new user-defined name, or None if
the user decides to skip.
"""
# Construct and compile the form
unqualified_name_form = unqualified_name_replace_t(unqualified_name, invalid_characters)
# Execute/show the form
selected_button = unqualified_name_form.Execute()
new_name = unqualified_name_form.new_name.value
# Free the form
unqualified_name_form.Free()
if selected_button == 1: # Replace button
return new_name
return None
#--------------------------------------------------------------------------
# IDA helper functions
#--------------------------------------------------------------------------
def get_invalid_characters(string: str) -> list:
invalid_characters = []
# Is the string empty?
if not string:
return invalid_characters
# Is the first character a digit?
if string[0].isdigit():
invalid_characters.append(0)
# Iterate through the characters in the string,
# and check if they are valid using
# ida_name.is_ident_cp
for index, character in enumerate(string):
if not ida_name.is_ident_cp(ord(character)):
invalid_characters.append(index)
# Return the invalid characters
return invalid_characters
def html_format_invalid_characters(string: str, invalid_characters: list, color: str = "#F44336") -> str:
# Are there any invalid characters in the string?
if not invalid_characters:
return string
# Format the invalid characters
formatted_string = ""
for index, character in enumerate(string):
if index in invalid_characters and color:
formatted_string += "<span style=\"color: {}\">{}</span>".format(color, character)
else:
formatted_string += character
# Return the formatted string
return formatted_string
def get_existing_enum_values(enum_name):
# Check if the enum exists
if get_enum(enum_name) == idaapi.BADNODE:
return {}
# Fetch the type definition
values = ida_typeinf.get_named_type(ida_typeinf.get_idati(), enum_name, ida_typeinf.NTF_TYPE)
if values is None:
return {}
_, type_str, fields_str, _, _, _, _ = values
type_definition = ida_typeinf.idc_print_type(type_str, fields_str, enum_name, 0)
# Parse the type definition