-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathjuniEmul.py
executable file
·2728 lines (2225 loc) · 97.7 KB
/
juniEmul.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
#!/usr/bin/python
'''
JuniEmu - emulator interface for ARM 32-bit.
Using Unicorn framework for emulation, Capstone disassembly framework and
Python's standard GUI (Graphical User Interface) package - Tkinter.
'''
import sys
import os
from collections import namedtuple
import collections
import threading
import time
import signal
import struct
from capstone.arm import *
import binascii
import pdb
import platform
import socket
import multiprocessing
from unicorn import *
from unicorn.arm_const import *
from unicorn.unicorn_const import *
if sys.version_info[0] < 3:
from capstone import *
if sys.version_info[0] < 3:
import Tkinter as tk
import ttk as ttk
from tkFileDialog import askopenfilename
import tkFont
else:
import tkinter as tk
from tkinter import filedialog
import tkinter.ttk as ttk
import tkinter.messagebox as msg
import tkinter.font as tkFont
BACKGROUND_COLOR = "black"
TEXT_COLOR = "#C0C0C0"
FONT_FAMILY = "Courier New"
FONT_SIZE = 9
print ("Unicorn version: {}.{}.{}".format(UC_VERSION_MAJOR, UC_VERSION_MINOR, UC_VERSION_EXTRA))
##################################################################################################
# CONFIG
##################################################################################################
IMAGEBASE = 0x00020000
ENTRYPOINT = 0x0
IS_THUMB_MODE = 0 # start mode
# leave empty if you want to choose file via open dialog
TEST_FILENAME = ""
##################################################################################################
# Registers start value
##################################################################################################
INITIALIZE_REG_R0 = 0
INITIALIZE_REG_R1 = 0
INITIALIZE_REG_R2 = 0
INITIALIZE_REG_R3 = 0
INITIALIZE_REG_R4 = 0
INITIALIZE_REG_R5 = 0
INITIALIZE_REG_R6 = 0
INITIALIZE_REG_R7 = 0
INITIALIZE_REG_R8 = 0
INITIALIZE_REG_R9 = 0
INITIALIZE_REG_R10 = 0
INITIALIZE_REG_R11 = 0
INITIALIZE_REG_R12 = 0
##################################################################################################
#
##################################################################################################
MAX_INSTR_SIZE = 4
VIEW_MEMORY_DUMP_RANGE = 16
PRINT_TO_CONSOL = 0
PRINT_DASM_DECOMPOSED_PC = 0
PRINT_EMULATION_LOG = 0
program_exit = False
g_current_memory_view_frame_number = 0
TEST_CODE = "\x00\x00\x00\x00\x00\x00\x00\x01"
EMUL_FUNCTION_NOP = 0
EMUL_FUNCTION_STRLEN = 1
EMUL_FUNCTION_AES_CRYPT = 2
EMUL_ADDR_FUNCTIONS_GLOBAL_TAB = {}
# EMUL_ADDR_FUNCTIONS_GLOBAL_TAB[0xFFFFFFFFF] = EMUL_FUNCTION_STRLEN
##################################################################################################
# .CODE
##################################################################################################
IN_UC_ARCH = UC_ARCH_ARM
IN_CS_MODE = CS_ARCH_ARM
if IS_THUMB_MODE == 0:
IN_UC_ARCH_MODE = UC_MODE_ARM
IN_CS_ARCH_MODE = CS_MODE_ARM
print("Using ARM - ARM mode")
else:
IN_UC_ARCH_MODE = UC_MODE_THUMB
IN_CS_ARCH_MODE = CS_MODE_THUMB
print("Using ARM - THUMB mode")
print("Imagebase: 0x" + '{:08X}'.format(IMAGEBASE) + " Entrypoint: 0x" + '{:08X}'.format(ENTRYPOINT))
lock = threading.Lock()
_python3 = sys.version_info.major == 3
def to_hex(s):
if _python3:
return " ".join("0x{0:02x}".format(c) for c in s)
else:
return " ".join("0x{0:02x}".format(ord(c)) for c in s)
def to_hex2(s):
if _python3:
r = "".join("{0:02x}".format(c) for c in s)
else:
r = "".join("{0:02x}".format(ord(c)) for c in s)
while r[0] == '0': r = r[1:]
return r
def to_x(s):
from struct import pack
if not s: return '0'
x = pack(">q", s)
while x[0] in ('\0', 0): x = x[1:]
return to_hex2(x)
def to_x_32(s):
from struct import pack
if not s: return '0'
x = pack(">i", s)
while x[0] in ('\0', 0): x = x[1:]
return to_hex2(x)
def BREAK_HERE():
pdb.set_trace()
return
class Dasm(object):
def __init__(self):
self.abc = ""
self._set_dasm_mode()
def _set_dasm_mode(self):
self.md_lite = Cs(IN_CS_MODE, IN_CS_ARCH_MODE)
self.md_lite.detail = True
self.md_lite.imm_unsigned = True
self.md_lite.syntax = CS_OPT_SYNTAX_NOREGNAME
self.md_full = Cs(IN_CS_MODE, IN_CS_ARCH_MODE)
self.md_full.detail = True
self.md_full.imm_unsigned = True
self.md_full.syntax = CS_OPT_SYNTAX_NOREGNAME
def print_insn_detail(self, insn):
print("0x%x:\t%s\t%s" % (insn.address, insn.mnemonic, insn.op_str))
def print_detail(self, insn):
# print address, mnemonic and operands
print("0x%x:\t%s\t%s" % (insn.address, insn.mnemonic, insn.op_str))
# "data" instruction generated by SKIPDATA option has no detail
if insn.id == 0:
return
#
# example from http://www.capstone-engine.org/lang_python.html
#
if len(insn.regs_read) > 0:
print("\tImplicit registers read: "),
for r in insn.regs_read:
print("%s \n" % insn.reg_name(r))
if len(insn.regs_write) > 0:
print("\tImplicit registers write: "),
for r in insn.regs_write:
print("%s \n" % insn.reg_name(r))
if len(insn.operands) > 0:
print("\top_count: %u" % len(insn.operands))
c = 0
for i in insn.operands:
if i.type == ARM_OP_REG:
print("\t\toperands[%u].type: REG = %s" % (c, insn.reg_name(i.reg)))
if i.type == ARM_OP_IMM:
print("\t\toperands[%u].type: IMM = 0x%s" % (c, to_x_32(i.imm)))
if i.type == ARM_OP_PIMM:
print("\t\toperands[%u].type: P-IMM = %u" % (c, i.imm))
if i.type == ARM_OP_CIMM:
print("\t\toperands[%u].type: C-IMM = %u" % (c, i.imm))
if i.type == ARM_OP_FP:
print("\t\toperands[%u].type: FP = %f" % (c, i.fp))
if i.type == ARM_OP_SYSREG:
print("\t\toperands[%u].type: SYSREG = %u" % (c, i.reg))
if i.type == ARM_OP_SETEND:
if i.setend == ARM_SETEND_BE:
print("\t\toperands[%u].type: SETEND = be" % c)
else:
print("\t\toperands[%u].type: SETEND = le" % c)
if i.type == ARM_OP_MEM:
print("\t\toperands[%u].type: MEM" % c)
if i.mem.base != 0:
print("\t\t\toperands[%u].mem.base: REG = %s" % (c, insn.reg_name(i.mem.base)))
if i.mem.index != 0:
print("\t\t\toperands[%u].mem.index: REG = %s" % (c, insn.reg_name(i.mem.index)))
if i.mem.scale != 1:
print("\t\t\toperands[%u].mem.scale: %u" % (c, i.mem.scale))
if i.mem.disp != 0:
print("\t\t\toperands[%u].mem.disp: 0x%s" % (c, to_x_32(i.mem.disp)))
if i.shift.type != ARM_SFT_INVALID and i.shift.value:
print("\t\t\tShift: %u = %u" % (i.shift.type, i.shift.value))
if i.vector_index != -1:
print("\t\t\toperands[%u].vector_index = %u" % (c, i.vector_index))
if i.subtracted:
print("\t\t\toperands[%u].subtracted = True" % c)
c += 1
if insn.update_flags:
print("\tUpdate-flags: True")
if insn.writeback:
print("\tWrite-back: True")
if not insn.cc in [ARM_CC_AL, ARM_CC_INVALID]:
print("\tCode condition: %u" % insn.cc)
if insn.cps_mode:
print("\tCPSI-mode: %u" % (insn.cps_mode))
if insn.cps_flag:
print("\tCPSI-flag: %u" % (insn.cps_flag))
if insn.vector_data:
print("\tVector-data: %u" % (insn.vector_data))
if insn.vector_size:
print("\tVector-size: %u" % (insn.vector_size))
if insn.usermode:
print("\tUser-mode: True")
if insn.mem_barrier:
print("\tMemory-barrier: %u" % (insn.mem_barrier))
def disasm_buffer_light(self, base_addr, buf, dasm_mode):
self.md_lite.mode = dasm_mode
address = size = mnemonic = op_str = 0
try:
for (address, size, mnemonic, op_str) in self.md_lite.disasm_lite(buf, base_addr, 1):
break
except CsError as e:
assert (False)
print("ERROR: %s" % e)
return address, size, mnemonic, op_str
def disasm_buffer_full(self, base_addr, buf, dasm_mode):
self.md_full.mode = dasm_mode
try:
for insn in self.md_full.disasm(buf, base_addr, 1):
self.print_detail(insn)
except CsError as e:
assert (False)
print("ERROR: %s" % e)
return
class EmulatorCore(object):
def __init__(self):
self.filename = ""
self.last_error = ""
self.disasm_number_of_lines = 0
self.file_data = b''
self.threads = []
self._create_objects()
self.emul_data_waiting = False
self.update_mem_view = False
self.update_dasm_view = False
self.update_register_view = False
self.last_emul_ip = 0
self.tracking_curr_instr_ip = 0
self.highlight_line_num = -1
self.wait_for_user_input = False
self.go_emul = False
self.emulator_running = False
self.break_run = False
self.mem_view1_addr = 0
self.mem_view1_range = 0
self.mem_view1_buffer = b""
self.mem_view2_addr = 0
self.mem_view2_range = 0
self.mem_view2_buffer = b""
self.run_counter = 0
self.bp_settings_dict = {}
self.dasm_listing_dict = collections.OrderedDict()
self.last_hook_regs_data = {}
self.mem_map_region_rwx = []
self.disasm_mode = None
def set_disasm_number_of_lines(self, ln_count):
self.disasm_number_of_lines = ln_count
def _create_objects(self):
self.dasm = Dasm()
def load_binary_stream(self, bin_stream):
self.file_data = bin_stream
return len(bin_stream)
def load_input_file(self, fname):
if fname == "":
return 0
with open(fname, 'rb') as f:
self.file_data = f.read()
return len(self.file_data)
def fetch_org_bytes(self, offset, fetch_limit):
if (offset + fetch_limit) < len(self.file_data):
return self.file_data[offset: offset + fetch_limit]
elif offset < len(self.file_data):
rest = len(self.file_data) - offset
return self.file_data[offset: offset + rest]
else:
return ""
def is_emul_data_waiting(self):
global lock
with lock:
return self.emul_data_waiting
def reset_emul_data_waiting(self):
global lock
with lock:
self.emul_data_waiting = False
def set_emul_data_waiting(self):
global lock
with lock:
self.emul_data_waiting = True
def set_new_memory_view_addr_on_window_number(self, addr, window_view):
global lock
with lock:
if window_view == 0:
self.mem_view1_addr = addr
elif window_view == 1:
self.mem_view2_addr = addr
def set_mem_view_range(self, r, frame_num):
if frame_num == 0:
self.mem_view1_range = r
elif frame_num == 1:
self.mem_view2_range = r
else:
assert (False)
def get_mem_view1_addr_data(self):
global lock
with lock:
return self.mem_view1_addr, self.mem_view1_buffer
def get_mem_view2_addr_data(self):
global lock
with lock:
return self.mem_view2_addr, self.mem_view2_buffer
def get_disasm_listing_dict(self):
return self.dasm_listing_dict
def get_highlight_line_num(self):
if self.highlight_line_num == -1:
return -1
# text line number start from 1
return self.highlight_line_num + 1
def is_wait_for_user_input(self):
global lock
with lock:
return self.wait_for_user_input
def reset_wait_for_user_input(self):
global lock
with lock:
self.wait_for_user_input = False
def set_wait_for_user_input(self):
global lock
with lock:
self.wait_for_user_input = True
def is_update_mem_view(self):
global lock
with lock:
return self.update_mem_view
def reset_update_mem_view(self):
global lock
with lock:
self.update_mem_view = False
def set_update_mem_view(self):
global lock
with lock:
self.update_mem_view = True
def is_dasm_view_update(self):
global lock
with lock:
return self.update_dasm_view
def reset_dasm_view_update(self):
global lock
with lock:
self.update_dasm_view = False
def set_dasm_view_update(self):
global lock
with lock:
self.update_dasm_view = True
def is_register_view_update(self):
global lock
with lock:
return self.update_register_view
def reset_update_register_view(self):
global lock
with lock:
self.update_register_view = False
def set_update_register_view(self):
global lock
with lock:
self.update_register_view = True
def dasm_listing_index_to_addr(self, i):
global lock
with lock:
j = 0
for addr_key in self.dasm_listing_dict:
if i == j:
return True, addr_key
j = j + 1
return False, 0
def reset_run_counter(self):
self.run_counter = 0
def inc_run_counter(self):
self.run_counter = self.run_counter + 1
def set_register_data(self, reg_name, reg_val):
if not self.is_wait_for_user_input():
return False
if reg_name == 'r0':
self.uc.reg_write(UC_ARM_REG_R0, reg_val)
return True
elif reg_name == 'r1':
self.uc.reg_write(UC_ARM_REG_R1, reg_val)
return True
elif reg_name == 'r2':
self.uc.reg_write(UC_ARM_REG_R2, reg_val)
return True
elif reg_name == 'r3':
self.uc.reg_write(UC_ARM_REG_R3, reg_val)
return True
elif reg_name == 'r4':
self.uc.reg_write(UC_ARM_REG_R4, reg_val)
return True
elif reg_name == 'r5':
self.uc.reg_write(UC_ARM_REG_R5, reg_val)
return True
elif reg_name == 'r6':
self.uc.reg_write(UC_ARM_REG_R6, reg_val)
return True
elif reg_name == 'r7':
self.uc.reg_write(UC_ARM_REG_R7, reg_val)
return True
elif reg_name == 'r8':
self.uc.reg_write(UC_ARM_REG_R8, reg_val)
return True
elif reg_name == 'r9':
self.uc.reg_write(UC_ARM_REG_R9, reg_val)
return True
elif reg_name == 'r10' or reg_name == 'sl':
self.uc.reg_write(UC_ARM_REG_R10, reg_val)
return True
elif reg_name == 'r11':
self.uc.reg_write(UC_ARM_REG_R11, reg_val)
return True
elif reg_name == 'r12':
self.uc.reg_write(UC_ARM_REG_R12, reg_val)
return True
elif reg_name == 'r13' or reg_name == 'sp':
self.uc.reg_write(UC_ARM_REG_R13, reg_val)
return True
elif reg_name == 'r14' or reg_name == 'lr':
self.uc.reg_write(UC_ARM_REG_R14, reg_val)
return True
elif reg_name == 'r15' or reg_name == 'pc':
self.uc.reg_write(UC_ARM_REG_R15, reg_val)
return True
elif reg_name == 'psr':
self.uc.reg_write(UC_ARM_REG_CPSR, reg_val)
return True
return False
def get_register_last_data(self):
return self.last_hook_regs_data
def _save_register_last_data(self):
assert (self.is_wait_for_user_input() == False)
r0 = self.uc.reg_read(UC_ARM_REG_R0)
r1 = self.uc.reg_read(UC_ARM_REG_R1)
r2 = self.uc.reg_read(UC_ARM_REG_R2)
r3 = self.uc.reg_read(UC_ARM_REG_R3)
r4 = self.uc.reg_read(UC_ARM_REG_R4)
r5 = self.uc.reg_read(UC_ARM_REG_R5)
r6 = self.uc.reg_read(UC_ARM_REG_R6)
r7 = self.uc.reg_read(UC_ARM_REG_R7)
r8 = self.uc.reg_read(UC_ARM_REG_R8)
r9 = self.uc.reg_read(UC_ARM_REG_R9)
sl = r10 = self.uc.reg_read(UC_ARM_REG_R10)
fp = r11 = self.uc.reg_read(UC_ARM_REG_R11)
ip = r12 = self.uc.reg_read(UC_ARM_REG_R12)
sp = r13 = self.uc.reg_read(UC_ARM_REG_R13)
lr = r14 = self.uc.reg_read(UC_ARM_REG_R14)
pc = r15 = self.uc.reg_read(UC_ARM_REG_R15)
psr = self.uc.reg_read(UC_ARM_REG_CPSR)
self.last_hook_regs_data = {}
self.last_hook_regs_data['r0'] = r0
self.last_hook_regs_data['r1'] = r1
self.last_hook_regs_data['r2'] = r2
self.last_hook_regs_data['r3'] = r3
self.last_hook_regs_data['r4'] = r4
self.last_hook_regs_data['r5'] = r5
self.last_hook_regs_data['r6'] = r6
self.last_hook_regs_data['r7'] = r7
self.last_hook_regs_data['r8'] = r8
self.last_hook_regs_data['r9'] = r9
self.last_hook_regs_data['r10'] = r10
self.last_hook_regs_data['r11'] = r11
self.last_hook_regs_data['r12'] = r12
self.last_hook_regs_data['sp'] = sp
self.last_hook_regs_data['lr'] = lr
self.last_hook_regs_data['pc'] = pc
self.last_hook_regs_data['psr'] = psr
def get_register_data(self):
reg_data = {}
if not self.is_wait_for_user_input():
return reg_data
r0 = self.uc.reg_read(UC_ARM_REG_R0)
r1 = self.uc.reg_read(UC_ARM_REG_R1)
r2 = self.uc.reg_read(UC_ARM_REG_R2)
r3 = self.uc.reg_read(UC_ARM_REG_R3)
r4 = self.uc.reg_read(UC_ARM_REG_R4)
r5 = self.uc.reg_read(UC_ARM_REG_R5)
r6 = self.uc.reg_read(UC_ARM_REG_R6)
r7 = self.uc.reg_read(UC_ARM_REG_R7)
r8 = self.uc.reg_read(UC_ARM_REG_R8)
r9 = self.uc.reg_read(UC_ARM_REG_R9)
sl = r10 = self.uc.reg_read(UC_ARM_REG_R10)
fp = r11 = self.uc.reg_read(UC_ARM_REG_R11)
ip = r12 = self.uc.reg_read(UC_ARM_REG_R12)
sp = r13 = self.uc.reg_read(UC_ARM_REG_R13)
lr = r14 = self.uc.reg_read(UC_ARM_REG_R14)
pc = r15 = self.uc.reg_read(UC_ARM_REG_R15)
psr = self.uc.reg_read(UC_ARM_REG_CPSR)
reg_data['r0'] = r0
reg_data['r1'] = r1
reg_data['r2'] = r2
reg_data['r3'] = r3
reg_data['r4'] = r4
reg_data['r5'] = r5
reg_data['r6'] = r6
reg_data['r7'] = r7
reg_data['r8'] = r8
reg_data['r9'] = r9
reg_data['r10'] = r10
reg_data['r11'] = r11
reg_data['r12'] = r12
reg_data['sp'] = sp
reg_data['lr'] = lr
reg_data['pc'] = pc
reg_data['psr'] = psr
return reg_data
def set_break_run(self):
if self.is_emulator_running() and self.is_wait_for_user_input() == False:
self.break_run = True
def is_emulator_running(self):
return self.emulator_running
def stop_emulator(self):
if self.is_emulator_running() and not self.is_emul_data_waiting() and self.is_wait_for_user_input():
self.uc.emu_stop()
self.reset_wait_for_user_input()
def gogo_emulator(self):
if self.is_emulator_running() and not self.is_emul_data_waiting() and self.is_wait_for_user_input():
self.go_emul = True
self.reset_wait_for_user_input()
def single_step_emulator(self):
if self.is_emulator_running() and not self.is_emul_data_waiting() and self.is_wait_for_user_input():
self.reset_wait_for_user_input()
def worker(self):
print ("Emulator start: %s" % (time.ctime(time.time())))
self.set_emul_syscall_address_table()
self.run_emulator()
self.reset_emul()
def reset_emul(self):
self.emulator_running = False
self.threads = []
self.reset_emul_data_waiting()
self.reset_update_mem_view()
self.reset_dasm_view_update()
self.reset_update_register_view()
self.last_emul_ip = 0
self.tracking_curr_instr_ip = 0
self.highlight_line_num = -1
self.go_emul = False
self.break_run = False
self.mem_view1_addr = 0
self.mem_view1_buffer = b""
self.mem_view2_addr = 0
self.mem_view2_buffer = b""
self.dasm_listing_dict = collections.OrderedDict()
self.mem_map_region_rwx = []
def start_emul_thread(self):
self.emulator_running = True
self.last_error = ""
t = threading.Thread(target=self.worker)
self.threads.append(t)
t.start()
def read_emul_memory_range(self, address, mem_size):
emul_mem = self.uc.mem_read(address, mem_size)
return emul_mem
def write_test_data(self):
if self.is_wait_for_user_input():
pass
# bemem = b"\x00"
# self.uc.mem_write(self.stack_address, bemem)
# self.uc.mem_write(IMAGEBASE, b"\x31\x22")
def get_dump_memory(self, dump_begin, dump_range):
if not self.is_wait_for_user_input():
return
buffer = b""
ba = bytearray()
if dump_range == 0:
return ""
try:
ba = self.read_emul_memory_range(dump_begin, dump_range)
except UcError as e:
if e.errno == UC_ERR_FETCH_UNMAPPED:
print("get_dump_memory error")
for i in range(len(ba)):
b = ba[i]
buffer += struct.pack('B', b)
return buffer
def write_byte_at_memory_addr(self, target_addr, nibble, mask):
if self.is_wait_for_user_input():
mem_ba = self.uc.mem_read(target_addr, 1)
if len(mem_ba) == 0:
assert (False)
return
b = mem_ba[0]
if mask == 0x0F:
nn = (nibble << 4)
print (hex(b))
b = nn | (b & 0x0F)
elif mask == 0xF0:
b = (b & 0xF0) | (nibble & 0x0F)
else:
return
s = b""
s += struct.pack('B', b)
self.uc.mem_write(target_addr, s)
def reload_dasm_listing(self):
global program_exit
if program_exit:
return False
if not self.is_wait_for_user_input():
return False
dasm_listing_top_addr = 0
if len(self.dasm_listing_dict):
for key in self.dasm_listing_dict:
dasm_listing_top_addr = key
break
else:
return False
self.update_dasm_listing(dasm_listing_top_addr, self.last_emul_ip, self.disasm_mode)
return True
def get_dasm_listing_first_addr(self):
first_addr = None
for key in self.dasm_listing_dict:
first_addr = key
break
return first_addr
def get_dasm_listing_last_addr(self):
last_addr = None
for key in self.dasm_listing_dict:
last_addr = key
return last_addr
def update_buffer_view_memory1(self):
self.mem_view1_buffer = b""
ba = bytearray()
if self.mem_view1_range == 0:
return
try:
ba = self.read_emul_memory_range(self.mem_view1_addr, self.mem_view1_range)
except UcError as e:
if e.errno == UC_ERR_FETCH_UNMAPPED:
print("update_view_memory1 error")
for i in range(len(ba)):
b = ba[i]
self.mem_view1_buffer += struct.pack('B', b)
def update_buffer_view_memory2(self):
self.mem_view2_buffer = b""
ba = bytearray()
if self.mem_view2_range == 0:
return
try:
ba = self.read_emul_memory_range(self.mem_view2_addr, self.mem_view2_range)
except UcError as e:
if e.errno == UC_ERR_FETCH_UNMAPPED:
print("update_view_memory2 error")
for i in range(len(ba)):
b = ba[i]
self.mem_view2_buffer += struct.pack('B', b)
def update_dasm_listing(self, dasm_listing_view_top_first_addr, ip_address, dasm_mode):
global PRINT_TO_CONSOL
buffer = self.read_emul_memory_range(dasm_listing_view_top_first_addr,
self.disasm_number_of_lines * MAX_INSTR_SIZE)
buffer_str = b""
for i in range(len(buffer)):
b = buffer[i]
buffer_str += struct.pack('B', b)
self.dasm_listing_dict = collections.OrderedDict()
curr_addr = dasm_listing_view_top_first_addr
offset = 0
self.highlight_line_num = -1
for ln in range(self.disasm_number_of_lines):
t = self.dasm.disasm_buffer_light(curr_addr, buffer_str[offset:], dasm_mode)
(ln_dasm_address, inst_size, mnemonic, op_str) = t
if inst_size == 0:
if len(buffer_str[offset:]) >= 4:
inst_size = 4
ln_dasm_address = curr_addr
mnemonic = ""
op_str = ""
else:
break
if ln_dasm_address == ip_address:
self.highlight_line_num = ln
if PRINT_DASM_DECOMPOSED_PC:
self.dasm.disasm_buffer_full(curr_addr, buffer_str[offset:], dasm_mode)
hex_str = ""
for j in range(inst_size):
b = buffer_str[offset + j]
byte_str = '{:02X}'.format(ord(b))
hex_str += byte_str
inst_str = ""
inst_str = "{0}{1}{2}".format(mnemonic, str(" "), op_str)
# pdb.set_trace()
addr_str = '{:08X}'.format(ln_dasm_address)
line = addr_str + " " + hex_str.ljust(8) + " " + inst_str
if PRINT_TO_CONSOL:
print(line)
# replace address with syscall name
emul_syscall_str = self.addr_to_emul_syscall_instr_str(ln_dasm_address)
if emul_syscall_str != "":
addr_str = '{:08X}'.format(ln_dasm_address)
line = addr_str + " " + hex_str.ljust(8) + " " + "bl " + emul_syscall_str
self.dasm_listing_dict[curr_addr] = line
offset += inst_size
curr_addr += inst_size
def get_last_error(self):
return self.last_error
def toggle_bp_settings(self, bp_addr, bp_state):
global lock
with lock:
self.bp_settings_dict[bp_addr] = bp_state
def get_bp_settings(self):
global lock
with lock:
return self.bp_settings_dict
def get_bp_settings_for_addr(self, bp_addr):
global lock
with lock:
for key_addr in self.bp_settings_dict:
if key_addr == bp_addr:
return True, self.bp_settings_dict[key_addr]
return False, 0
def del_bp_addr(self, bp_addr):
global lock
with lock:
for key in self.bp_settings_dict:
if bp_addr == key:
self.bp_settings_dict.pop(key, None)
return 1
return 0
def del_all_bp_addr(self):
l = len(self.bp_settings_dict)
self.bp_settings_dict = {}
return l
def reload_dasm_listing_with_unassemble_from_addr(self, unasm_begin):
self.update_dasm_listing(unasm_begin, self.tracking_curr_instr_ip, self.disasm_mode)
def is_mem_region_mapped(self, mem_addr_test):
for i in range(len(self.mem_map_region_rwx)):
(mem_begin, mem_range) = self.mem_map_region_rwx[i]
if mem_begin <= mem_addr_test < (mem_begin + mem_range):
return True
return False
def find_prev_mem_begin_region(self, curr_addr):
ll = self.mem_map_region_rwx
ll = sorted(ll)
for i in range(len(ll)):
(mem_begin, mem_range) = ll[i]
if mem_begin <= curr_addr < (mem_begin + mem_range):
if i == 0:
(mem_begin, mem_range) = ll[i]
return mem_begin
else:
(mem_begin, mem_range) = ll[i - 1]
return mem_begin
return None
def find_mem_region_from_addr(self, curr_addr):
ll = self.mem_map_region_rwx
ll = sorted(ll)
for i in range(len(ll)):
(mem_begin, mem_range) = ll[i]
if mem_begin <= curr_addr < (mem_begin + mem_range):
(mem_begin, mem_range) = ll[i]
return mem_begin, mem_range
return None, None
# callback for tracing instructions
def all_instr_hook_code(self, uc, ip_address, size, user_data):
global program_exit
if program_exit:
return False
self.tracking_curr_instr_ip = ip_address
self._save_register_last_data()
# use Arm mode by default
self.disasm_mode = CS_MODE_ARM
if self.uc.query(UC_QUERY_MODE) == UC_MODE_THUMB:
self.disasm_mode = CS_MODE_THUMB
if PRINT_EMULATION_LOG:
print(">> THUMB mode on")
if ip_address in self.bp_settings_dict:
# BREAK_HERE()
print(">>> Breakpoint hit at 0x%x, instruction size = %u" % (ip_address, size))
self.go_emul = False
elif self.break_run:
self.go_emul = False
self.break_run = False
elif self.go_emul:
if PRINT_EMULATION_LOG:
print(">>> Tracing instruction at 0x%x, instruction size = %u" % (ip_address, size))
self.last_emul_ip = ip_address
return True
if PRINT_EMULATION_LOG:
print(">>> Tracing instruction at 0x%x, instruction size = %u" % (ip_address, size))
dasm_listing_top_addr = 0
if ip_address in self.dasm_listing_dict:
for key in self.dasm_listing_dict:
dasm_listing_top_addr = key
break
else:
dasm_listing_top_addr = ip_address
#
#
#
self.update_dasm_listing(dasm_listing_top_addr, ip_address, self.disasm_mode)
self.update_buffer_view_memory1()
self.update_buffer_view_memory2()
self.set_wait_for_user_input()
self.set_emul_data_waiting()
while self.is_emul_data_waiting():
time.sleep(0.01)
#
# wait for user input
#
self.last_emul_ip = ip_address
while self.is_wait_for_user_input():
time.sleep(0.01)
if program_exit:
return False
self.emul_syscall(ip_address)
return True
def emul_syscall(self, ip_address):
if ip_address in self.emul_syscall_addr_table:
syscall_number = self.emul_syscall_addr_table[ip_address]
if syscall_number == EMUL_FUNCTION_NOP:
pass
elif syscall_number == EMUL_FUNCTION_STRLEN:
self.emul_function_strlen()
elif syscall_number == EMUL_FUNCTION_AES_CRYPT:
assert False
else:
assert False
self.skip_current_instruction()
def emul_function_strlen(self):
r0 = self.uc.reg_read(UC_ARM_REG_R0)
if not self.is_mem_region_mapped(r0):
assert False
return