forked from mandiant/flare-emu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flare_emu.py
executable file
·2079 lines (1886 loc) · 109 KB
/
flare_emu.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
############################################
# Copyright (C) 2018 FireEye, Inc.
#
# Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
# http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-BSD-3-CLAUSE or
# https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be
# copied, modified, or distributed except according to those terms.
#
# Author: James T. Bennett
#
# flare-emu combines Unicorn and a choice of binary analysis engine to provide emulation support for
# reverse engineers
# Currently supports 32-bit and 64-bit x86, ARM, and ARM64
# Dependencies:
# https://github.com/unicorn-engine/unicorn
############################################
from __future__ import print_function
import unicorn
import unicorn.x86_const
import unicorn.arm_const
import unicorn.arm64_const
from copy import deepcopy
import logging
import struct
import re
import flare_emu_hooks
import types
import sys
PAGESIZE = 0x1000
PAGEALIGNCHECK = 0xfff
X86NOP = b"\x90"
ARMTHUMBNOP = b"\x00\xbf"
ARMNOP = b"\x00\xf0\x20\xe3"
ARM64NOP = b"\x1f\x20\x03\xd5"
MAX_ALLOC_SIZE = 10 * 1024 * 1024
MAXCODEPATHS = 20
MAXNODESEARCH = 100000
try:
long # Python 2
except NameError:
long = int # Python 3
# parent class to provide binary analysis engine support for EmuHelper class
# subclassed by Radare2AnalysisHelper and IdaProAnalysisHelper
class AnalysisHelper(object):
def __init__(self):
self.o_reg = 1
self.o_mem = 2
self.o_phrase = 3
self.o_displ = 4
self.o_imm = 5
self.o_far = 6
self.o_near = 7
def getFuncStart(self, addr):
pass
def getFuncEnd(self, addr):
pass
def getFuncName(self, addr):
pass
def getMnem(self, addr):
pass
# gets address of last instruction in the basic block containing addr
def getBlockEndInsnAddr(self, addr):
pass
def skipJumpTable(self, addr):
pass
def getMinimumAddr(self):
pass
def getMaximumAddr(self):
pass
def getBytes(self, addr, size):
pass
def getCString(self, addr):
pass
def getOperand(self, addr, opndNum):
pass
def getWordValue(self, addr):
pass
def getDwordValue(self, addr):
pass
def getQWordValue(self, addr):
pass
def isThumbMode(self, addr):
pass
# for segment/section related functions, IDA Pro calls everything segments
# while Radare2 maintains the distinction. PE's do not have segments, but sections,
# while ELFs and Mach-Os have both. We will maintain the distinction when the underlying
# framework supports it.
def getSegmentName(self, addr):
pass
def getSegmentStart(self, addr):
pass
def getSegmentEnd(self, addr):
pass
# gets the number of defined bytes in the segment containing addr.
# used when loading the binary to determine how many bytes to copy
# to emulator memory from each segment, because IDA Pro may have
# undefined bytes.
def getSegmentDefinedSize(self, addr):
pass
def getSegmentSize(self, addr):
pass
def getSegments(self):
pass
def getSectionName(self, addr):
pass
def getSectionStart(self, addr):
pass
def getSectionEnd(self, addr):
pass
def getSectionSize(self, addr):
pass
def getSections(self):
pass
# gets disassembled instruction with names and comments as a string
def getDisasmLine(self, addr):
pass
def getName(self, addr):
pass
def getNameAddr(self, name):
pass
def getOpndType(self, addr, opndNum):
pass
def getOpndValue(self, addr, opndNum):
pass
def makeInsn(self, addr):
pass
def createFunction(self, addr):
pass
def getFlowChart(self, addr):
pass
def getSpDelta(self, addr):
pass
def getXrefsTo(self, addr):
pass
def getBlockByAddr(self, addr, flowchart):
pass
def getArch(self):
pass
def getBitness(self):
pass
def getFileType(self):
pass
def getInsnSize(self, addr):
pass
def isTerminatingBB(self, addr):
pass
def getTerminatingBBs(self, flowchart):
term_bbs = []
for bb in flowchart:
if self.isTerminatingBB(bb):
term_bbs.append(bb)
return term_bbs
def getStartBB(self, addr, flowchart):
funcStart = self.getFuncStart(addr)
for bb in flowchart:
if bb.start_ea == funcStart:
return bb
def getBlockIdByVA(self, targetVA, flowchart):
return self.getBlockByVA(targetVA, flowchart).id
def getBlockByVA(self, targetVA, flowchart):
for bb in flowchart:
if targetVA >= bb.start_ea and targetVA < bb.end_ea:
return bb
def getBlockById(self, id, flowchart):
for bb in flowchart:
if bb.id == id:
return bb
def skipJumpTable(self, addr):
pass
def normalizeFuncName(self, funcName, extra=False):
pass
def setName(self, addr, name, size=0):
pass
def setComment(self, addr, comment):
pass
class EmuHelper():
def __init__(self, verbose=0, emuHelper=None, samplePath=None):
self.verbose = verbose
self.stack = 0
self.stackSize = 0x2000
self.size_DWORD = 4
self.size_pointer = 0
self.callMnems = ["CALL", "BL", "BLX", "BLR",
"BLXEQ", "BLEQ", "BLREQ"]
self.paths = {}
self.filetype = "UNKNOWN"
self.uc = None
self.h_userhook = None
self.h_memaccesshook = None
self.h_codehook = None
self.h_memhook = None
self.h_inthook = None
self.enteredBlock = False
if samplePath is not None:
try:
import flare_emu_radare
except Exception as e:
print("error importing flare_emu_radare: %s" % e)
return
# copy Radare2AnalysisHelper to skip reanalyzing binary and save time
if emuHelper is not None:
self.analysisHelper = emuHelper.analysisHelper
self.analysisHelper.eh = self
else:
self.analysisHelper = flare_emu_radare.Radare2AnalysisHelper(samplePath, self)
self.analysisHelperFramework = "Radare2"
else:
try:
import flare_emu_ida
except:
print("error importing flare_emu_ida: specify samplePath to use radare2 or run under IDA Pro 7+")
return
self.analysisHelper = flare_emu_ida.IdaProAnalysisHelper(self)
self.analysisHelperFramework = "IDA Pro"
import idaapi
self.initEmuHelper()
if emuHelper is not None:
self._cloneEmuMem(emuHelper)
else:
self.reloadBinary()
# startAddr: address to start emulation
# endAddr: address to end emulation, this instruction is not executed.
# if not provided, emulation stops when starting function is exited
# (function must end with a return instruction)
# registers: a dict whose keys are register names and values are
# register values, all unspecified registers will be initialized to 0
# stack: a list of values to be setup on the stack before emulation.
# if X86 you must account for SP+0 (return address).
# for the stack and registers parameters, specifying a string will
# allocate memory, write the string to it, and write a pointer to that
# memory in the specified register/arg
# instructionHook: instruction hook func that runs AFTER emulateRange's hook
# hookData: user-defined data to be made available in instruction hook
# function, care must be taken to not use key names already used by
# flare_emu in userData dictionary
# skipCalls: emulator will skip over call instructions and adjust the
# stack accordingly, defaults to True
# emulateRange will always skip over calls to empty memory
# callHook: callback function that will be called whenever the emulator
# encounters a "call" instruction. keep in mind your skipCalls value
# and that emulateRange will always skip over calls to empty memory
# memAccessHook: hook function that runs when the emulator encounters a
# memory read or write
# hookApis: set to False if you don't want flare-emu to emulate common
# runtime memory and string functions, defaults to True
# returns the emulation object in its state after the emulation completes
# strict: checks branch destinations to ensure the disassembler expects
# instructions, otherwise skips branch instruction. if disabled,
# will make code in disassembler as it emulates (DISABLE WITH CAUTION).
# enabled by default
# count: Value passed to unicorn's uc_emu_start to indicate max number of
# instructions to emulate, Defaults to 0 (all code available).
def emulateRange(self, startAddr, endAddr=None, registers=None, stack=None, instructionHook=None, callHook=None,
memAccessHook=None, hookData=None, skipCalls=True, hookApis=True, strict=True, count=0):
if registers is None:
registers = {}
if stack is None:
stack = []
userData = {"EmuHelper": self, "funcStart": self.analysisHelper.getFuncStart(startAddr),
"funcEnd": self.analysisHelper.getFuncEnd(startAddr), "skipCalls": skipCalls, "strict": strict,
"endAddr": endAddr, "callHook": callHook, "hookApis": hookApis, "count": count}
if hookData:
userData.update(hookData)
if userData["funcEnd"] is None:
userData["funcEnd"] = userData["endAddr"]
mu = self.uc
self._prepEmuContext(registers, stack)
self.resetEmuHooks()
self.h_codehook = mu.hook_add(
unicorn.UC_HOOK_CODE, self._emulateRangeCodeHook, userData)
if instructionHook:
self.h_userhook = mu.hook_add(unicorn.UC_HOOK_CODE, instructionHook, userData)
if memAccessHook:
self.h_memaccesshook = self.uc.hook_add(unicorn.UC_HOOK_MEM_READ | unicorn.UC_HOOK_MEM_WRITE,
memAccessHook, userData)
self.h_memhook = mu.hook_add(unicorn.UC_HOOK_MEM_READ_UNMAPPED | unicorn.UC_HOOK_MEM_WRITE_UNMAPPED |
unicorn.UC_HOOK_MEM_FETCH_UNMAPPED, self._hookMemInvalid, userData)
self.h_inthook = mu.hook_add(
unicorn.UC_HOOK_INTR, self._hookInterrupt, userData)
if self.arch == unicorn.UC_ARCH_ARM:
userData["changeThumbMode"] = True
mu.emu_start(startAddr, userData["funcEnd"], count=count)
return mu
# call emulateRange using selected instructions in IDA Pro as start/end addresses
def emulateSelection(self, registers=None, stack=None, instructionHook=None, callHook=None,
memAccessHook=None, hookData=None, skipCalls=True, hookApis=True, count=0):
import idaapi
try:
selection = idaapi.read_selection()
except TypeError:
selection = idaapi.read_range_selection(None)
if selection[0]:
self.emulateRange(selection[1], selection[2], registers, stack, instructionHook,
callHook, memAccessHook, hookData, skipCalls, hookApis, count=count)
else:
print("emulateSelection is only available for IDA Pro")
# target: finds first path through function to target using depth first
# search for each address in list, if a single address is specified,
# does so for each xref to target address
# emulates each target's function, forcing path to target, then
# executes callback function providing emu object and arguments
# instructionHook: user-defined instruction hook to run AFTER guidedHook that
# forces execution
# hookData: user-defined data to be made available in instruction hook
# function, care must be taken to not use key names already used by
# flare_emu in userData dictionary
# preEmuCallback: a callback that is called BEFORE each emulation run
# callHook: a callback that is called whenever the emulator encounters a
# "call" instruction. hook or no, after a call instruction, the
# program counter is advanced to the next instruction and the stack is
# automatically cleaned up
# resetEmuMem: if set to True, unmaps all allocated emulator memory and
# reloads the binary from the IDB into emulator memory before each
# emulation run. can significantly increase script run time, defaults
# to False
# hookApis: set to False if you don't want flare-emu to emulate common
# runtime memory and string functions, defaults to True
# memAccessHook: hook function that runs when the emulator encounters a
# memory read or write
def iterate(self, target, targetCallback, preEmuCallback=None, callHook=None, instructionHook=None,
hookData=None, resetEmuMem=False, hookApis=True, memAccessHook=None):
if target is None:
return
targetInfo = {}
if type(target) in [int, long]:
logging.debug("iterate target function: %s" %
self.hexString(target))
xrefs = self.analysisHelper.getXrefsTo(target)
for i, x in enumerate(xrefs):
# get unique functions from xrefs that we need to emulate
funcStart = self.analysisHelper.getFuncStart(x)
if funcStart == None:
continue
if self.analysisHelper.getMnem(x).upper() not in ["CALL", "JMP", "BL", "BLX", "B", "BLR"]:
continue
logging.debug("getting a path to %s, %d of %d" %
(self.hexString(x), i + 1, len(xrefs)))
flow, paths = self.getPath(x)
if flow is not None:
targetInfo[x] = (flow, paths)
elif isinstance(target, list):
for i, t in enumerate(target):
logging.debug("getting a path to %s, %d of %d" %
(self.hexString(t), i + 1, len(target)))
flow, paths = self.getPath(t)
if flow is not None:
targetInfo[t] = (flow, paths)
if len(targetInfo) <= 0:
logging.debug("no targets to iterate")
return
userData = {}
userData["targetInfo"] = targetInfo
userData["targetCallback"] = targetCallback
userData["callHook"] = callHook
userData["EmuHelper"] = self
userData["hookApis"] = hookApis
if hookData:
userData.update(hookData)
self.resetEmuHooks()
self.h_codehook = self.uc.hook_add(
unicorn.UC_HOOK_CODE, self._guidedHook, userData)
if instructionHook:
self.h_userhook = self.uc.hook_add(unicorn.UC_HOOK_CODE, instructionHook, userData)
if memAccessHook:
self.h_memaccesshook = self.uc.hook_add(unicorn.UC_HOOK_MEM_READ | unicorn.UC_HOOK_MEM_WRITE,
memAccessHook, userData)
self.h_memhook = self.uc.hook_add(unicorn.UC_HOOK_MEM_READ_UNMAPPED | unicorn.UC_HOOK_MEM_WRITE_UNMAPPED |
unicorn.UC_HOOK_MEM_FETCH_UNMAPPED, self._hookMemInvalid, userData)
self.h_inthook = self.uc.hook_add(
unicorn.UC_HOOK_INTR, self._hookInterrupt, userData)
self.blockIdx = 0
cnt = 1
# read targets from dict to go from higher to lower addresses
# this is done to optimize loop by allowing hook to check for and remove other targets visited en route to
# current target
while len(userData["targetInfo"]) > 0:
userData["targetVA"] = targetVA = sorted(
userData["targetInfo"].keys(), reverse=True)[0]
flow, paths = userData["targetInfo"][targetVA]
funcStart = flow[0][0]
self.pathIdx = 0
numTargets = len(userData["targetInfo"])
logging.debug("run #%d, %d targets remaining: %s (%d paths)" % (
cnt, numTargets, self.hexString(targetVA), len(paths)))
cnt2 = 1
numPaths = len(paths)
for path in paths:
logging.debug("emulating path #%d of %d from %s to %s via basic blocks: %s" % (
cnt2, numPaths, self.hexString(funcStart), self.hexString(targetVA), repr(path)))
for reg in self.regs:
self.uc.reg_write(self.regs[reg], 0)
if resetEmuMem:
self.reloadBinary()
self.uc.reg_write(self.regs["sp"], self.stack)
self.enteredBlock = False
userData["visitedTargets"] = []
if preEmuCallback:
preEmuCallback(self, userData, funcStart)
if self.arch == unicorn.UC_ARCH_ARM:
userData["changeThumbMode"] = True
self.uc.emu_start(funcStart, self.analysisHelper.getFuncEnd(funcStart))
self.pathIdx += 1
self.blockIdx = 0
cnt2 += 1
# remove visited targets during this run from our dict
for addr in userData["visitedTargets"]:
del(userData["targetInfo"][addr])
cnt += 1
# target: iterates paths through a function
# targetCallback: a callback that is called when target (function end)
# is hit, providing arguments and userData
# preEmuCallback: a callback that is called BEFORE each emulation run
# callHook: a callback that is called whenever the emulator encounters a
# "call" instruction. hook or no, after a call instruction, the
# program counter is advanced to the next instruction and the stack is
# automatically cleaned up
# instructionHook: user-defined instruction hook to run AFTER guidedHook that
# forces execution
# hookData: user-defined data to be made available in instruction hook
# function, care must be taken to not use key names already used by
# flare_emu in userData dictionary
# resetEmuMem: if set to True, unmaps all allocated emulator memory and
# reloads the binary from the IDB into emulator memory before each
# emulation run. can significantly increase script run time, defaults
# to False
# hookApis: set to False if you don't want flare-emu to emulate common
# runtime memory and string functions, defaults to True
# memAccessHook: hook function that runs when the emulator encounters a
# memory read or write
# maxPaths: maximum number of paths to discover and emulate for a function
# maxNodes: maximum number of nodes to go through before giving up
def iterateAllPaths(self, target, targetCallback, preEmuCallback=None, callHook=None, instructionHook=None,
hookData=None, resetEmuMem=False, hookApis=True, memAccessHook=None, maxPaths=MAXCODEPATHS,
maxNodes=MAXNODESEARCH):
flowchart = self.analysisHelper.getFlowChart(target)
# targets are all function ends
targets = [self.analysisHelper.getBlockEndInsnAddr(bb.start_ea, flowchart) for bb
in self.analysisHelper.getTerminatingBBs(flowchart)]
targetInfo = {}
for i, t in enumerate(targets):
logging.debug("getting paths to %s, %d of %d targets" %
(self.hexString(t), i + 1, len(targets)))
flow, paths = self.getPathsToTarget(t, maxPaths, maxNodes)
if flow and paths:
targetInfo[t] = (flow, paths)
if len(targetInfo) <= 0:
logging.debug("no targets to iterate")
return
userData = {}
userData["targetInfo"] = targetInfo
userData["targetCallback"] = targetCallback
userData["callHook"] = callHook
userData["EmuHelper"] = self
userData["hookApis"] = hookApis
if hookData:
userData.update(hookData)
self.internalRun = False
self.resetEmuHooks()
self.h_codehook = self.uc.hook_add(
unicorn.UC_HOOK_CODE, self._guidedHook, userData)
if instructionHook:
self.h_userhook = self.uc.hook_add(unicorn.UC_HOOK_CODE, instructionHook, userData)
if memAccessHook:
self.h_memaccesshook = self.uc.hook_add(unicorn.UC_HOOK_MEM_READ | unicorn.UC_HOOK_MEM_WRITE,
memAccessHook, userData)
self.h_memhook = self.uc.hook_add(unicorn.UC_HOOK_MEM_READ_UNMAPPED | unicorn.UC_HOOK_MEM_WRITE_UNMAPPED |
unicorn.UC_HOOK_MEM_FETCH_UNMAPPED, self._hookMemInvalid, userData)
self.h_inthook = self.uc.hook_add(
unicorn.UC_HOOK_INTR, self._hookInterrupt, userData)
self.blockIdx = 0
cnt = 1
for targetVA in sorted(userData["targetInfo"].keys(), reverse=True):
userData["targetVA"] = targetVA
flow, paths = userData["targetInfo"][targetVA]
funcStart = flow[0][0]
self.pathIdx = 0
numTargets = len(userData["targetInfo"])
logging.debug("run #%d, %d targets remaining: %s (%d paths)" % (
cnt, numTargets, self.hexString(targetVA), len(paths)))
cnt2 = 1
numPaths = len(paths)
for path in paths:
logging.debug("emulating path #%d of %d from %s to %s via basic blocks: %s" % (
cnt2, numPaths, self.hexString(funcStart), self.hexString(targetVA), repr(path)))
for reg in self.regs:
self.uc.reg_write(self.regs[reg], 0)
if resetEmuMem:
self.reloadBinary()
self.uc.reg_write(self.regs["sp"], self.stack)
self.enteredBlock = False
userData["visitedTargets"] = []
if preEmuCallback:
preEmuCallback(self, userData, funcStart)
if self.arch == unicorn.UC_ARCH_ARM:
userData["changeThumbMode"] = True
self.uc.emu_start(funcStart, self.analysisHelper.getFuncEnd(funcStart))
self.pathIdx += 1
self.blockIdx = 0
cnt2 += 1
cnt += 1
# simply emulates to the end of whatever bytes are provided
# these bytes are not loaded into IDB, only emulator memory
# analysisHelper APIs are not available for use in hooks here
def emulateBytes(self, bytes, registers=None, stack=None, baseAddr=0x400000, instructionHook=None,
memAccessHook=None, hookData=None):
if registers is None:
registers = {}
if stack is None:
stack = []
userData = {}
if hookData:
userData.update(hookData)
baseAddr = self.loadBytes(bytes, baseAddr)
endAddr = baseAddr + len(bytes)
userData["endAddr"] = endAddr
mu = self.uc
self._prepEmuContext(registers, stack)
self.resetEmuHooks()
self.h_codehook = mu.hook_add(
unicorn.UC_HOOK_CODE, self._emulateBytesCodeHook, userData)
if instructionHook:
self.h_userhook = mu.hook_add(unicorn.UC_HOOK_CODE, instructionHook, userData)
if memAccessHook:
self.h_memaccesshook = self.uc.hook_add(unicorn.UC_HOOK_MEM_READ | unicorn.UC_HOOK_MEM_WRITE,
memAccessHook, userData)
self.h_memhook = mu.hook_add(unicorn.UC_HOOK_MEM_READ_UNMAPPED | unicorn.UC_HOOK_MEM_WRITE_UNMAPPED |
unicorn.UC_HOOK_MEM_FETCH_UNMAPPED, self._hookMemInvalid, userData)
self.h_inthook = mu.hook_add(
unicorn.UC_HOOK_INTR, self._hookInterrupt, userData)
mu.emu_start(baseAddr, endAddr)
return mu
# emulates from startAddr continually
# must specify conditions under which emulation is stopped such as the "count" param
# or making a call to eh.stopEmulation from one of your hooks
# startAddr: address to start emulation
# registers: a dict whose keys are register names and values are
# register values, all unspecified registers will be initialized to 0
# stack: a list of values to be setup on the stack before emulation.
# if X86 you must account for SP+0 (return address).
# for the stack and registers parameters, specifying a string will
# allocate memory, write the string to it, and write a pointer to that
# memory in the specified register/arg
# instructionHook: instruction hook func that runs AFTER emulateFrom's hook
# hookData: user-defined data to be made available in instruction hook
# function, care must be taken to not use key names already used by
# flare_emu in userData dictionary
# skipCalls: emulator will skip over call instructions and adjust the
# stack accordingly, defaults to True
# emulateFrom will always skip over calls to empty memory
# callHook: callback function that will be called whenever the emulator
# encounters a "call" instruction. keep in mind your skipCalls value
# and that emulateFrom will always skip over calls to empty memory
# memAccessHook: hook function that runs when the emulator encounters a
# memory read or write
# hookApis: set to False if you don't want flare-emu to emulate common
# runtime memory and string functions, defaults to True
# returns the emulation object in its state after the emulation completes
# strict: checks branch destinations to ensure the disassembler expects
# instructions, otherwise skips branch instruction. if disabled,
# will make code in disassembler as it emulates (DISABLE WITH CAUTION).
# enabled by default
# count: Value passed to unicorn's uc_emu_start to indicate max number of
# instructions to emulate, Defaults to 0 (all code available).
def emulateFrom(self, startAddr, registers=None, stack=None, instructionHook=None, callHook=None,
memAccessHook=None, hookData=None, skipCalls=True, hookApis=True, strict=True, count=0):
if registers is None:
registers = {}
if stack is None:
stack = []
userData = {"EmuHelper": self, "skipCalls": skipCalls, "callHook": callHook,
"hookApis": hookApis, "strict": strict, "count": count}
if hookData:
userData.update(hookData)
mu = self.uc
self._prepEmuContext(registers, stack)
self.resetEmuHooks()
self.h_codehook = mu.hook_add(
unicorn.UC_HOOK_CODE, self._emulateRangeCodeHook, userData)
if instructionHook:
self.h_userhook = mu.hook_add(unicorn.UC_HOOK_CODE, instructionHook, userData)
if memAccessHook:
self.h_memaccesshook = self.uc.hook_add(unicorn.UC_HOOK_MEM_READ | unicorn.UC_HOOK_MEM_WRITE,
memAccessHook, userData)
self.h_memhook = mu.hook_add(unicorn.UC_HOOK_MEM_READ_UNMAPPED | unicorn.UC_HOOK_MEM_WRITE_UNMAPPED |
unicorn.UC_HOOK_MEM_FETCH_UNMAPPED, self._hookMemInvalid, userData)
self.h_inthook = mu.hook_add(
unicorn.UC_HOOK_INTR, self._hookInterrupt, userData)
if self.arch == unicorn.UC_ARCH_ARM:
userData["changeThumbMode"] = True
mu.emu_start(startAddr, self.analysisHelper.getMaximumAddr(), count=count)
return mu
def writeEmuMem(self, addr, data):
self.uc.mem_write(addr, bytes(data))
def hexString(self, va):
if va > 0xffffffff:
return "%016X" % va
else:
return "%08X" % va
def pageAlignUp(self, v):
if v & PAGEALIGNCHECK != 0:
v += PAGESIZE - (v % PAGESIZE)
return v
# determines if the instruction at addr is for returning from a function call
def isRetInstruction(self, addr):
if self.analysisHelper.getMnem(addr)[:3].lower() == "ret":
return True
if (self.analysisHelper.getMnem(addr).lower() in ["bx", "b"] and
self.analysisHelper.getOperand(addr, 0).lower() == "lr"):
return True
if (self.analysisHelper.getMnem(addr).lower() == "pop" and
"pc" in self.analysisHelper.getDisasmLine(addr).lower()):
return True
return False
# call from an emulation hook to skip the current instruction, moving pc to next instruction
# useAnalysisHelper option added to handle cases where IDA folds multiple instructions (Radare2 doesn't do this)
# do not call multiple times in a row, depends on userData being updated by hook
def skipInstruction(self, userData, useAnalysisHelper=False):
if self.arch == unicorn.UC_ARCH_ARM:
userData["changeThumbMode"] = True
if useAnalysisHelper:
self.uc.reg_write(self.regs["pc"],
userData["currAddr"] + self.analysisHelper.getInsnSize(userData["currAddr"]))
else:
self.uc.reg_write(
self.regs["pc"], userData["currAddr"] + userData["currAddrSize"])
# get SP delta value for next instruction to adjust stack accordingly since we are skipping
# this instruction
self.uc.reg_write(self.regs["sp"], self.getRegVal(
"sp") + self.analysisHelper.getSpDelta(userData["currAddr"] +
self.analysisHelper.getInsnSize(userData["currAddr"])))
# call from an emulation hook to change program counter
def changeProgramCounter(self, userData, newPC):
if self.arch == unicorn.UC_ARCH_ARM:
userData["changeThumbMode"] = True
self.uc.reg_write(self.regs["pc"], newPC)
# retrieves the value of a register, handling subregister addressing
def getRegVal(self, regName):
regVal = self.uc.reg_read(self.regs[regName])
# handle various subregister addressing
if self.arch == unicorn.UC_ARCH_X86:
if regName[:-1] in ["l", "b"]:
regVal = regVal & 0xFF
elif regName[:-1] == "h":
regVal = (regVal & 0xFF00) >> 8
elif len(regName) == 2 and regName[:-1] == "x":
regVal = regVal & 0xFFFF
elif self.arch == unicorn.UC_ARCH_ARM64:
if regName[0] == "W":
regVal = regVal & 0xFFFFFFFF
return regVal
def stopEmulation(self, userData):
self.enteredBlock = False
if "visitedTargets" in userData and userData["targetVA"] not in userData["visitedTargets"]:
userData["visitedTargets"].append(
userData["targetVA"])
self.uc.emu_stop()
def resetEmuHooks(self):
if self.uc is None:
logging.debug(
"resetEmuHooks: no hooks to reset, emulator has not been initialized yet")
return
if self.h_userhook:
self.uc.hook_del(self.h_userhook)
self.h_userhook = None
if self.h_memaccesshook:
self.uc.hook_del(self.h_memaccesshook)
self.h_memaccesshook = None
if self.h_codehook:
self.uc.hook_del(self.h_codehook)
self.h_codehook = None
if self.h_memhook:
self.uc.hook_del(self.h_memhook)
self.h_memhook = None
if self.h_inthook:
self.uc.hook_del(self.h_inthook)
self.h_inthook = None
# for debugging purposes
def getEmuState(self):
if self.arch == unicorn.UC_ARCH_X86:
if self.uc._mode == unicorn.UC_MODE_64:
out = "RAX: %016X\tRBX: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_RAX), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_RBX))
out += "RCX: %016X\tRDX: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_RCX), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_RDX))
out += "RDI: %016X\tRSI: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_RDI), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_RSI))
out += "R8: %016X\tR9: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_R8), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_R9))
out += "RBP: %016X\tRSP: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_RBP), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_RSP))
out += "RIP: %016X\n" % (self.uc.reg_read(unicorn.x86_const.UC_X86_REG_RIP))
elif self.uc._mode == unicorn.UC_MODE_32:
out = "EAX: %016X\tEBX: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_EAX), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_EBX))
out += "ECX: %016X\tEDX: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_ECX), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_EDX))
out += "EDI: %016X\tESI: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_EDI), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_ESI))
out += "EBP: %016X\tESP: %016X\n" % (self.uc.reg_read(
unicorn.x86_const.UC_X86_REG_EBP), self.uc.reg_read(unicorn.x86_const.UC_X86_REG_ESP))
out += "EIP: %016X\n" % (self.uc.reg_read(unicorn.x86_const.UC_X86_REG_EIP))
elif self.arch == unicorn.UC_ARCH_ARM64:
out = "X0: %016X\tX1: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X0), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X1))
out += "X2: %016X\tX3: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X2), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X3))
out += "X4: %016X\tX5: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X4), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X5))
out += "X6: %016X\tX7: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X6), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X7))
out += "X8: %016X\tX9: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X8), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X9))
out += "X10: %016X\tX11: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X10), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X11))
out += "X12: %016X\tX13: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X12), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X13))
out += "X14: %016X\tX15: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X14), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X15))
out += "X16: %016X\tX17: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X16), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X17))
out += "X18: %016X\tX19: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X18), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X19))
out += "X20: %016X\tX21: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X20), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X21))
out += "X22: %016X\tX23: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X22), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X23))
out += "X24: %016X\tX25: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X24), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X25))
out += "X26: %016X\tX27: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X26), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X27))
out += "X28: %016X\tX29: %016X\n" % (self.uc.reg_read(
unicorn.arm64_const.UC_ARM64_REG_X28), self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X29))
out += "X30: %016X\n" % (self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_X30))
out += "PC: %016X\n" % (self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_PC))
out += "SP: %016X\n" % (self.uc.reg_read(unicorn.arm64_const.UC_ARM64_REG_SP))
elif self.arch == unicorn.UC_ARCH_ARM:
out = "R0: %08X\tR1: %08X\n" % (self.uc.reg_read(
unicorn.arm_const.UC_ARM_REG_R0), self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R1))
out += "R2: %08X\tR3: %08X\n" % (self.uc.reg_read(
unicorn.arm_const.UC_ARM_REG_R2), self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R3))
out += "R4: %08X\tR5: %08X\n" % (self.uc.reg_read(
unicorn.arm_const.UC_ARM_REG_R4), self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R5))
out += "R6: %08X\tR7: %08X\n" % (self.uc.reg_read(
unicorn.arm_const.UC_ARM_REG_R6), self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R7))
out += "R8: %08X\tR9: %08X\n" % (self.uc.reg_read(
unicorn.arm_const.UC_ARM_REG_R8), self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R9))
out += "R10: %08X\tR11: %08X\n" % (self.uc.reg_read(
unicorn.arm_const.UC_ARM_REG_R10), self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R11))
out += "R12: %08X\tR13: %08X\n" % (self.uc.reg_read(
unicorn.arm_const.UC_ARM_REG_R12), self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R13))
out += "R14: %08X\tR15: %08X\n" % (self.uc.reg_read(
unicorn.arm_const.UC_ARM_REG_R14), self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R15))
out += "PC: %08X\n" % self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R15)
out += "SP: %08X\n" % self.uc.reg_read(unicorn.arm_const.UC_ARM_REG_R13)
else:
return ""
return out
# returns null-terminated string of bytes from the emulator's memory, starting at addr, do not necessarily need
# to be printable characters
def getEmuString(self, addr):
# return a bytearray object , if you want to get a str object ,you must decode it by latin1
out = bytearray()
while self.uc.mem_read(addr, 1) != b"\x00":
out += self.uc.mem_read(addr, 1)
addr += 1
return out
def getEmuWideString(self, addr):
# return a bytearray object , if you want to get a str object ,you must decode it by utf-16le
out = bytearray()
while self.uc.mem_read(addr, 2) != b"\x00\x00":
out += self.uc.mem_read(addr, 2)
addr += 2
return out
# returns a <size> bytearray of bytes read from <addr>
def getEmuBytes(self, addr, size):
return self.uc.mem_read(addr, size)
# reads pointer value in emulator's memory
def getEmuPtr(self, va):
return struct.unpack(self.pack_fmt, self.uc.mem_read(va, self.size_pointer))[0]
# writes a pointer value in emulator's memory
def writeEmuPtr(self, va, value):
self.writeEmuMem(va, struct.pack(self.pack_fmt, value))
# gets the signed integer value of the unsigned integer value given the bitness of the architecture
def getSignedValue(self, value):
return struct.unpack(self.pack_fmt_signed, struct.pack(self.pack_fmt, value))[0]
def pageAlign(self, addr):
return addr & 0xfffffffffffff000
# get first path to target found during exploration
def getPath(self, targetVA):
flowchart = self.analysisHelper.getFlowChart(targetVA)
target_bb = self.analysisHelper.getBlockByVA(targetVA, flowchart)
start_bb = self.analysisHelper.getStartBB(targetVA, flowchart)
if target_bb.id != 0:
if self.verbose > 0:
logging.debug("exploring function with %d blocks" % len(flowchart))
graph = self._explore(start_bb, target_bb)
if graph is None:
logging.debug(
"graph for target %s could not be traversed, skipping" % self.hexString(targetVA))
return None, None
if self.verbose > 0:
logging.debug("graph for target:\n%s" % repr(graph))
path = [0]
if not self._findPathFromGraph(path, graph, 0, target_bb.id):
logging.debug(
"path for target %s could not be discovered, skipping" % self.hexString(targetVA))
return None, None
else:
path = [0]
if self.verbose > 0:
logging.debug("code path to target: %s" % repr(path))
# create my own idaapi.FlowChart-like object to optimize calculating block end addrs
flow = {}
for bb in flowchart:
flow[bb.id] = (bb.start_ea, self.analysisHelper.getBlockEndInsnAddr(bb.start_ea, flowchart))
return flow, [path]
# get up to maxPaths path to target
# for some complex functions, may give up before finding a path
def getPathsToTarget(self, targetVA, maxPaths=MAXCODEPATHS, maxNodes=MAXNODESEARCH):
flowchart = self.analysisHelper.getFlowChart(targetVA)
target_bb = self.analysisHelper.getBlockByVA(targetVA, flowchart)
start_bb = self.analysisHelper.getStartBB(targetVA, flowchart)
if target_bb.id != 0:
if self.verbose > 0:
logging.debug("exploring function with %d blocks" % len(flowchart))
graph = self._explore(start_bb)
if graph is None:
logging.debug(
"graph for target %s could not be traversed, skipping" % self.hexString(targetVA))
return None, None
if self.verbose > 0:
logging.debug("graph for target:\n%s" % repr(graph))
path = [0]
paths = []
targets = [target_bb.id]
self._findPathsFromGraph(paths, path, graph, 0, targets, maxPaths, 0 , maxNodes)
if len(paths) == 0:
logging.debug(
"path for target %s could not be discovered, skipping" % self.hexString(targetVA))
return None, None
else:
paths = [[0]]
if self.verbose > 0:
logging.debug("code paths to target: %s" % repr(paths))
# create my own idaapi.FlowChart object so it can be pickled for debugging purposes
flow = {}
for bb in flowchart:
flow[bb.id] = (bb.start_ea, self.analysisHelper.getBlockEndInsnAddr(bb.start_ea, flowchart))
return flow, paths
# get up to maxPaths paths from function start to any terminating basic block
# for some complex functions, may give up before finding a path
def getPaths(self, fva, maxPaths=MAXCODEPATHS, maxNodes=MAXNODESEARCH):
flowchart = self.analysisHelper.getFlowChart(fva)
term_bbs_ids = [bb.id for bb in self.analysisHelper.getTerminatingBBs(flowchart)]
start_bb = self.analysisHelper.getStartBB(fva, flowchart)
if term_bbs_ids != [0]:
if self.verbose > 0:
logging.debug("exploring function with %d blocks" % len(flowchart))
graph = self._explore(start_bb)
if graph is None:
logging.debug(
"graph for target %s could not be traversed, skipping" % self.hexString(fva))
return None, None
if self.verbose > 0:
logging.debug("graph for target:\n%s" % repr(graph))
path = [0]
paths = []
self._findPathsFromGraph(paths, path, graph, 0, term_bbs_ids, maxPaths, 0, maxNodes)
if len(paths) == 0:
logging.debug(
"paths for target %s could not be discovered, skipping" % self.hexString(fva))
return None, None
else:
paths = [[0]]
if self.verbose > 0:
logging.debug("code paths to target: %s" % repr(paths))
# create my own idaapi.FlowChart object so it can be pickled for debugging purposes
flow = {}
for bb in flowchart:
flow[bb.id] = (bb.start_ea, self.analysisHelper.getBlockEndInsnAddr(bb.start_ea, flowchart))
return flow, paths
# sets up arch/mode specific variables, initializes emulator
def initEmuHelper(self):
arch = self.analysisHelper.getArch()