-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathcodegen.py
663 lines (551 loc) · 25.9 KB
/
codegen.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
'''
CodeGen
'''
import sys
import os
import binascii
python2=False
if sys.version_info[0] < 3:
python2=True
try:
from binaryninja import *
except:
print ("[+] Not running in BinaryNinja")
class callConv(object):
def __init__(self, name, arch):
self.name = name
self.arch = arch
def gen_arg_number(self, argno):
pass
def genPointer(self, arg, regs, indent):
pass
def dumpContext(self, indent):
pass
class x64callConv(callConv):
# TODO Stack based arguments
def __init__(self, name, arch):
self.name = name
self.arch = arch
self.platform = ''
self.regs = ["UC_X86_REG_RAX", "UC_X86_REG_RBP", "UC_X86_REG_RBX", "UC_X86_REG_RCX",\
"UC_X86_REG_RDI", "UC_X86_REG_RDX", "UC_X86_REG_RSI", "UC_X86_REG_RSP",\
"UC_X86_REG_RIP", "UC_X86_REG_R8", "UC_X86_REG_R9", "UC_X86_REG_R10",\
"UC_X86_REG_R11", "UC_X86_REG_R12", "UC_X86_REG_R13", "UC_X86_REG_R14",\
"UC_X86_REG_R15"]
def gen_arg_number(self, argno, indent=1):
print ("X64")
if self.platform == "win":
return self.msft(argno, indent)
return self.systemV(argno, indent)
def genPointer(self, arg, regs, indent):
ret = ' ' * (indent * 4) + "argAddr_%x = (%d * 0x1000)\n" % (arg.num, arg.num+1)
ret += ' ' * (indent * 4) + "self.mu.mem_write(argAddr_%x, arg_%x)\n" % (arg.num, arg.num)
ret += ' ' * (indent * 4) + "self.mu.reg_write(%s, argAddr_%x)\n" % (regs[arg.num], arg.num)
return ret
def msft(self, arg, indent):
regs = ["UC_X86_REG_RCX", "UC_X86_REG_RDX", "UC_X86_REG_R8", "UC_X86_REG_R9"]
if arg.num < len(regs):
return "self.mu.reg_write(%s, arg_%x)\n" % (regs[argno], argno)
return self.genPointer(arg, regs, indent)
def systemV(self, arg, indent):
regs = ["UC_X86_REG_RDI", "UC_X86_REG_RSI", "UC_X86_REG_RDX", "UC_X86_REG_RCX",\
"UC_X86_REG_R8", "UC_X86_REG_R9"]
if arg.num <= len(regs):
if (arg.pointerDepth == 0 or arg.pointerDepth > 1):
return ' ' * (indent*4) + "self.mu.reg_write(%s, arg_%x)\n" % (regs[arg.num], arg.num)
return self.genPointer(arg, regs, indent)
def dumpContext(self, indent):
ret = ' ' * (indent * 4) + ("print ('[!] Exception occured - Emulator state (x64):')\n")
for r in self.regs:
ret += ' ' * (indent * 4) + ("print (\"%s : %%016X\" %% (self.mu.reg_read(%s)))\n" % (r,r))
return ret
class x86callConv(callConv):
def __init__(self, name, arch):
self.name = name
self.arch = arch
self.regs = ["UC_X86_REG_EAX", "UC_X86_REG_EBP", "UC_X86_REG_EBX", "UC_X86_REG_ECX",\
"UC_X86_REG_EDI", "UC_X86_REG_EDX", "UC_X86_REG_ESI", "UC_X86_REG_ESP",\
"UC_X86_REG_EIP"]
def genPointer(self, arg, indent):
ret = ' ' * (indent * 4) + "argAddr_%x = (%d * 0x1000)\n" % (arg.num, arg.num + 1)
ret += ' ' * (indent * 4) + "self.mu.mem_write(argAddr_%x, arg_%x)\n" % (arg.num, arg.num)
ret += ' ' * (indent * 4) + "self.mu.mem_write(self.mu.reg_read(UC_X86_REG_ESP) + %d, struct.pack('<i', argAddr_%x))\n" % ( (arg.num * 4) + 4, arg.num)
return ret
# TODO Other calling conventions
def gen_arg_number(self, arg, indent):
if arg.pointerDepth == 0 or arg.pointerDepth > 1:
return ' ' * (indent * 4) + "self.mu.mem_write(self.mu.reg_read(UC_X86_REG_ESP) + %d, struct.pack('<i', arg_%x))\n" % ( (arg.num * 4) + 4, arg.num)
return self.genPointer(arg, indent)
def dumpContext(self, indent):
ret = ' ' * (indent * 4) + ("print ('[!] Exception occured - Emulator state (x86):')\n")
for r in self.regs:
ret += ' ' * (indent * 4) + ("print (\"%s : %%08X\" %% (self.mu.reg_read(%s)))\n" % (r,r))
return ret
class armcallConv(callConv):
def __init__(self, name, arch):
self.name = name
self.arch = arch
self.regs = ["UC_ARM_REG_R0", "UC_ARM_REG_R1", "UC_ARM_REG_R2", "UC_ARM_REG_R3",\
"UC_ARM_REG_R4", "UC_ARM_REG_R5", "UC_ARM_REG_R6", "UC_ARM_REG_R7",\
"UC_ARM_REG_R8", "UC_ARM_REG_R9", "UC_ARM_REG_R10", "UC_ARM_REG_R11",\
"UC_ARM_REG_R12", "UC_ARM_REG_R13", "UC_ARM_REG_R14", "UC_ARM_REG_R15"]
def genPointer(self, arg, regs, indent):
ret = ' ' * (indent * 4) + "argAddr_%x = (%d * 0x1000)\n" % (arg.num, arg.num+1)
ret += ' ' * (indent * 4) + "self.mu.mem_write(argAddr_%x, arg_%x)\n" % (arg.num, arg.num)
ret += ' ' * (indent * 4) + "self.mu.reg_write(%s, argAddr_%x)\n" % (regs[arg.num], arg.num)
return ret
def gen_arg_number(self, arg, indent):
regs = ["UC_ARM_REG_R0", "UC_ARM_REG_R1", "UC_ARM_REG_R2", "UC_ARM_REG_R3"]
if arg.num < len(regs):
if arg.pointerDepth == 0 or arg.pointerDepth > 1:
return ' ' * (indent *4 ) + "self.mu.reg_write(%s, arg_%x)\n" % (regs[arg.num], arg.num)
return self.genPointer(arg, regs, indent)
def dumpContext(self, indent):
ret = ' ' * (indent * 4) + ("print ('[!] Exception occured - Emulator state (arm):')\n")
for r in self.regs:
ret += ' ' * (indent * 4) + ("print (\"%s : %%X\" %% (self.mu.reg_read(%s)))\n" % (r,r))
return ret
class arm64callConv(callConv):
def __init__(self, name, arch):
self.name = name
self.arch = arch
self.regs = ["UC_ARM64_REG_X0", "UC_ARM64_REG_X1", "UC_ARM64_REG_X2", "UC_ARM64_REG_X3",\
"UC_ARM64_REG_X4", "UC_ARM64_REG_X5", "UC_ARM64_REG_X6", "UC_ARM64_REG_X7",\
"UC_ARM64_REG_X8", "UC_ARM64_REG_X9", "UC_ARM64_REG_X10", "UC_ARM64_REG_X11",\
"UC_ARM64_REG_X12", "UC_ARM64_REG_X13", "UC_ARM64_REG_X14", "UC_ARM64_REG_X15",\
"UC_ARM64_REG_X16", "UC_ARM64_REG_X17", "UC_ARM64_REG_X18", "UC_ARM64_REG_X19",\
"UC_ARM64_REG_X20", "UC_ARM64_REG_X21", "UC_ARM64_REG_X22", "UC_ARM64_REG_X23",\
"UC_ARM64_REG_X24", "UC_ARM64_REG_X25", "UC_ARM64_REG_X26", "UC_ARM64_REG_X27",\
"UC_ARM64_REG_X28", "UC_ARM64_REG_X29", "UC_ARM64_REG_X30"]
def genPointer(self, arg, regs, indent):
ret = ' ' * (indent * 4) + "argAddr_%x = (%d * 0x1000)\n" % (arg.num, arg.num+1)
ret += ' ' * (indent * 4) + "self.mu.mem_write(argAddr_%x, arg_%x)\n" % (arg.num, arg.num)
ret += ' ' * (indent * 4) + "self.mu.reg_write(%s, argAddr_%x)\n" % (regs[arg.num], arg.num)
return ret
def gen_arg_number(self, arg, indent):
regs = ["UC_ARM64_REG_X0", "UC_ARM64_REG_X1", "UC_ARM64_REG_X2", "UC_ARM64_REG_X3"]
if arg.num < len(regs):
if arg.pointerDepth == 0 or arg.pointerDepth > 1:
return ' ' * (indent *4 ) + "self.mu.reg_write(%s, arg_%x)\n" % (regs[arg.num], arg.num)
return self.genPointer(arg, regs, indent)
def dumpContext(self, indent):
ret = ' ' * (indent * 4) + ("print ('[!] Exception occured - Emulator state (arm64):')\n")
for r in self.regs:
ret += ' ' * (indent * 4) + ("print (\"%s : %%X\" %% (self.mu.reg_read(%s)))\n" % (r,r))
return ret
class codeSlice(object):
'''
A container class for a slice of code.
'''
def __init__(self, code, address):
self.code_bytes = code
self.address = address
class genwrapper(object):
'''
A storage area for different kinds of things we need to do to setup
unicorn such that it can emulate the selected code.
Regions we need to mmap
Data we need to write
Registers that need to be populated
etc
Args:
Name: The name for this code
engine: The analysis engine to be used.
Attributes:
mmap: Ranges we need to map
data: List of data we need to copy into mappings
code: List of codeSlice objects which need to be copied into memory
arch: Architecture of this package
saved_ranges:
startaddr: Starting PC address for this package
codelen: Length of code
name: Name of the generated class
conPass: Dictionary of applicable convenience passes (set by packager)
impCallTargets: List of targets of imported calls to catch and hook
'''
def __init__(self, name, isFunc=True):
self.mmap = {}
# List of (address, data)
self.data = []
# List of codeSlice Objects
self.code = []
# Dict of regname:regvalue
self.regs = {}
self.arch = ''
self.saved_ranges = []
self.startaddr = 0
self.codelen = 0
self.name = name
self.pagesize = self.get_pagesize()
self.conPass = {}
self.conPass['ret'] = False
self.impCallTargets = []
self.callConv = None
self.isFunc = isFunc
def setArch(self,a):
self.arch=a
if self.arch == 'x64':
self.callConv = x64callConv("linux", "x64")
elif self.arch == 'x86':
self.callConv = x86callConv("linux", "x86")
elif self.arch == 'arm':
self.callConv =armcallConv("linux", "arm")
elif self.arch == 'arm64':
self.callConv =armcallConv("linux", "arm64")
def data_saved(self, addr):
return any(lowaddr <= addr <= highaddr for (lowaddr, highaddr) in self.saved_ranges)
# Wrappers for manipulating data structures
def add_mmap(self, addr, len=0x4000):
self.mmap[(addr & ~(self.pagesize - 1))] = len
def add_data(self, data, addr):
if (self.data_saved(addr)):
print ("[Warning] Trying to map data twice!")
return
self.data.append((addr, data))
self.saved_ranges.append((addr, addr + len(data)))
def add_code(self, cSlice):
if (self.data_saved(cSlice.address)):
print ("[Warning] Trying to map data twice")
self.code.append(cSlice)
self.saved_ranges.append((cSlice.address, cSlice.address + len(cSlice.code_bytes)))
def get_pagesize(self):
if self.arch == 'x86':
return 4096
return 4096
def generate_argument_mmaps(self, indent=1):
'''
Map a page for each argument with a pointerDepth of 1.
'''
out = ''
for arg in self.conPass['args']:
if arg.pointerDepth == 1:
out += ' ' * (indent * 4) + "self.mu.mem_map(0x1000 * %d, 0x1000)\n" % (arg.num + 1)
return out
# Unicorn API generation helpers
def generate_mmap(self, indent = 1):
out = ''
for addr in self.mmap:
out += ' ' * (indent * 4) + "self.mu.mem_map(%s,%s)\n" % (hex(addr), hex(self.mmap[addr]))
# Map pages for arguments if applicable
if 'args' in self.conPass.keys():
out += self.generate_argument_mmaps(indent=indent)
return out
def generate_data_vars(self, indent = 1):
global python2
out = ''
for i in range(0, len(self.data)):
if python2==True:
cc=binascii.hexlify(self.data[i][1])
else:
cc=binascii.hexlify(self.data[i][1]).decode('utf-8')
out += ' ' * (indent * 4) + "self.data_%s = binascii.unhexlify('%s') \n" % (str(i), cc)
return out
def generate_code_vars(self, indent = 1):
global python2
out = ''
i = 0
for cSlice in self.code:
if python2==True:
cc=binascii.hexlify(cSlice.code_bytes)
else:
cc=binascii.hexlify(cSlice.code_bytes).decode('utf-8')
out += ' ' * (indent * 4) + "self.code_%s = binascii.unhexlify('%s') \n" % (str(i), cc)
i += 1
return out
def generate_stack_initialization(self, indent = 1):
if self.arch == 'x86':
self.add_mmap(0x7ffff000, 1024*1024 * 2)
out = ' ' * (indent * 4) + "self.mu.reg_write(UC_X86_REG_ESP, 0x7fffff00)\n"
elif self.arch == 'x64':
self.add_mmap(0x7ffff000, 1024*1024 * 2)
out = ' ' * (indent * 4) + "self.mu.reg_write(UC_X86_REG_RSP, 0x7fffff00)\n"
elif self.arch == 'arm':
self.add_mmap(0x7ffff000, 1024*1024 * 2)
out = ' ' * (indent * 4) + "self.mu.reg_write(UC_ARM_REG_SP, 0x7fffff00)\n"
elif self.arch == 'arm64':
self.add_mmap(0x7ffff000, 1024*1024 * 2)
out = ' ' * (indent * 4) + "self.mu.reg_write(UC_ARM64_REG_SP, 0x7fffff00)\n"
## TODO Add support for other architectures supported by Unicorn and Binja
else:
print ("[ripr] Error, Unsupported Architecture")
return out
def generate_mem_writes(self, indent = 1):
out = ''
for i in range(0, len(self.data)):
out += ' ' * (indent * 4) + "self.mu.mem_write(%s, self.data_%s)\n" % (hex(self.data[i][0]), i)
for i in range(0, len(self.code)):
out += ' ' * (indent * 4) + "self.mu.mem_write(%s, self.code_%s)\n" % (hex(self.code[i].address), i)
return out
def generate_emuinit(self, indent = 1):
'''
Decide how to initialize the emulator based on CPU Architecture.
'''
if self.arch == "x86":
return ' ' * (indent * 4) + "self.mu = Uc(UC_ARCH_X86, UC_MODE_32)\n"
# TODO Support Other Archs
elif self.arch == "x64":
return ' ' * (indent * 4) + "self.mu = Uc(UC_ARCH_X86, UC_MODE_64)\n"
elif self.arch == "arm":
return ' ' * (indent * 4) + "self.mu = Uc(UC_ARCH_ARM, UC_MODE_ARM)\n"
elif self.arch == "arm64":
return ' ' * (indent * 4) + "self.mu = Uc(UC_ARCH_ARM64, UC_MODE_ARM)\n"
def generate_emustart(self, indent = 1):
out = ' ' * (indent * 4) + "try:\n"
out += ' ' * ((indent + 1) * 4) + "self.mu.emu_start(startaddr, 0)\n"
out += ' ' * (indent * 4) + "except Exception as e:\n"
if self.isFunc:
out += self.generate_return_guard(indent=indent+1)
else:
out += self.generate_hook_lookup(indent=indent+1)
return out
def generate_start_unicorn_func(self, indent = 1):
'''
This function wraps starting the unicorn emulator and dealing with exceptions if applicable.
'''
decl = ' ' * (indent * 4) + 'def _start_unicorn(self, startaddr):\n'
body = self.generate_emustart(indent=2)
return decl+body+"\n"
def generate_return_guard_marker(self, indent=1):
'''
Generate code that will result in the emulator returning to a marker value at the end of a
successfull function emulation. This is caught by code in generate_return_guard and indicates
that the function behaved normally.
'''
out = ''
if self.arch in ['x86', 'x64']:
out += ' ' * (indent *4) + "self.mu.mem_write(0x7fffff00, '\\x01\\x00\\x00\\x00')\n"
elif self.arch == 'arm':
out += ' ' * (indent *4) + "self.mu.reg_write(UC_ARM_REG_LR, 0x4)\n"
elif self.arch == 'arm64':
out += ' ' * (indent *4) + "self.mu.reg_write(UC_ARM64_REG_LR, 0x4)\n"
else:
print ("Unsupported Arch")
return out
def generate_restore_exec(self, indent=1):
'''
Generate code that will adjust the cpu context so it matches expected behaviour after
a hooked call.
'''
out = ''
if self.arch == 'x64':
out += ' ' * (indent * 4) + "self.mu.reg_write(UC_X86_REG_RSP, self.mu.reg_read(UC_X86_REG_RSP) + 8)\n"
out += ' ' * (indent * 4) + "self._start_unicorn(retAddr)\n"
elif self.arch == 'x86':
out += ' ' * (indent * 4) + "self.mu.reg_write(UC_X86_REG_ESP, self.mu.reg_read(UC_X86_REG_ESP) + 4)\n"
out += ' ' * (indent * 4) + "self._start_unicorn(retAddr)\n"
elif self.arch == 'arm':
out += ' ' * (indent * 4) + "self._start_unicorn(retAddr)\n"
pass
elif self.arch == 'arm64':
out += ' ' * (indent * 4) + "self._start_unicorn(retAddr)\n"
pass
else:
print ("Unsupported Arch")
return out
def generate_hook_lookup(self, indent=1):
if self.arch == 'x64':
retAddr = ' ' * (indent * 4) + "retAddr = struct.unpack(\"<q\", self.mu.mem_read(self.mu.reg_read(UC_X86_REG_RSP), 8))[0]\n"
elif self.arch == 'x86':
retAddr = ' ' * (indent * 4) + "retAddr = struct.unpack(\"<i\", self.mu.mem_read(self.mu.reg_read(UC_X86_REG_ESP), 4))[0]\n"
elif self.arch == 'arm':
retAddr = ' ' * (indent * 4) + "retAddr = self.mu.reg_read(UC_ARM_REG_LR)\n"
elif self.arch == 'arm64':
retAddr = ' ' * (indent * 4) + "retAddr = self.mu.reg_read(UC_ARM64_REG_LR)\n"
else:
print ("Unsupported Architecture")
retAddr = ' ' * (indent * 4) + "retAddr = 0\n"
chk_hookdict = ' ' * (indent * 4) + "if retAddr in self.hookdict.keys():\n"
getattr_call = ' ' * ( (indent+1) * 4) + "getattr(self, self.hookdict[retAddr][0])()\n"
restore = self.generate_restore_exec(indent=indent+1)
return retAddr + chk_hookdict + getattr_call + restore
def generate_return_guard(self, indent=1):
'''
Generate code to catch the "crash" that will happen after a packaged function hits a
''return'' instruction or imported call.
We use 0x1 as a marker to say the function has hit a return as expected.
'''
out = ''
if (self.arch == 'x64'):
out += ' ' * (indent * 4) + "if self.mu.reg_read(UC_X86_REG_RIP) == 1:\n"
elif (self.arch == 'x86'):
out += ' ' * (indent * 4) + "if self.mu.reg_read(UC_X86_REG_EIP) == 1:\n"
elif (self.arch == 'arm'):
out += ' ' * (indent * 4) + "if self.mu.reg_read(UC_ARM_REG_PC) == 4:\n"
else:
print ("[ripr] Unsupported Arch...")
# Return if PC has landed on the marker value
out += ' ' * ((indent + 1) * 4) + "return\n"
# Check if this crash is the result of an imported Call and execute the hook if applicable
if (self.impCallTargets):
out += self.generate_hook_lookup(indent=indent)
# Raise original exception if PC is not equal to the appropriate marker value or imported call marker
out += ' ' * (indent * 4) + "else:\n"
if self.callConv is not None:
out += self.callConv.dumpContext(indent+1)
out += ' ' * ((indent+1) * 4) + "raise e"
return out + "\n\n"
def generate_return_conv(self, indent=1):
'''
Generate code for the ''return-value recovery'' convenience pass.
The 'run()' function will return whatever the architecture specific return register typically
is rather than requiring the user to manually query the emulator state.
'''
if self.arch == 'x64':
return ' ' * (indent * 4) + "return self.mu.reg_read(UC_X86_REG_RAX)\n"
elif self.arch == 'x86':
return ' ' * (indent * 4) + "return self.mu.reg_read(UC_X86_REG_EAX)\n"
elif self.arch == 'arm':
return ' ' * (indent * 4) + "return self.mu.reg_read(UC_ARM_REG_R0)\n"
elif self.arch == 'arm64':
return ' ' * (indent * 4) + "return self.mu.reg_read(UC_ARM64_REG_X0)\n"
else:
print ('[ripr] Unsupported Arch')
def generate_run_with_args(self, indent=1):
decl = ' ' * 4 + "def run(self"
args = self.conPass['args']
for i in range(0, len(args)):
decl += ", arg_%x" % i
decl += '):\n'
return decl+"\n"
def generate_fill_in_args(self, indent=1):
decl = ''
args = self.conPass['args']
# TODO Determine calling convention/Platform
if self.arch == 'x64':
cc = x64callConv("linux", "x64")
for i in range(0, len(args)):
decl += cc.gen_arg_number(args[i], indent)
elif self.arch == 'x86':
cc = x86callConv("linux", "x86")
for i in range(0, len(args)):
decl += cc.gen_arg_number(args[i], indent)
elif self.arch == 'arm':
cc =armcallConv("linux", "arm")
for i in range(0, len(args)):
decl += cc.gen_arg_number(args[i], indent)
elif self.arch == 'arm64':
cc =armcallConv("linux", "arm")
for i in range(0, len(args)):
decl += cc.gen_arg_number(args[i], indent)
return decl
def generate_run_functions(self, indent = 1):
out = ''
if 'args' in self.conPass.keys():
decl = self.generate_run_with_args()
else:
decl = ' ' * 4 + "def run(self):\n"
stk = self.generate_stack_initialization(indent=2)
initArgs = ''
if 'args' in self.conPass.keys():
initArgs = self.generate_fill_in_args(indent=2)
if self.isFunc:
marker = self.generate_return_guard_marker(indent=2)
else:
marker = ''
emus = ' ' * ((indent) * 4) + "self._start_unicorn(%s)\n" % (hex(self.startaddr))
out += decl + stk + marker + initArgs + emus
# Check for return value recovery convenience
if (self.conPass['ret'] == True):
out += self.generate_return_conv(indent=2)
return out+"\n"
def imp_consts(self):
'''
Return an import string depending on what arch you are using.
'''
if self.arch in ('x86', 'x64'):
return "from unicorn.x86_const import *\n\n"
elif self.arch == 'arm':
return "from unicorn.arm_const import *\n\n"
elif self.arch == 'arm64':
return "from unicorn.arm64_const import *\n\n"
elif self.arch in ('mips32', 'mips64'):
return "from unicorn.mips_const import *\n\n"
elif self.arch in ('m68k'):
return "from unicorn.m68k_const import *\n\n"
elif self.arch in ('sparc'):
return "from unicorn.sparc_const import *\n\n"
# Code "Builders"
def generate_default_hookFunc(self, name, indent=1):
'''
The default python hook for imported calls should do nothing.
'''
out = ' ' * (indent * 4) + """def hook_%s(self):
print ("[!] %s hook not implemented!")
pass\n\n""" % (name, name)
return out
def _build_impCall_hook_dict(self, indent=1):
'''
Build a dictionary of return address --> hook function for dynamic
imported call handling.
'''
ret = ''
out = {}
instlen = {}
build_funcs = []
# Get a list of names for hook functions
for impCall in self.impCallTargets:
if str(impCall.symbol) not in build_funcs:
build_funcs.append(str(impCall.symbol))
out[impCall.address+impCall.inst_len] = "['hook_%s',%d]" % (str(impCall.symbol),impCall.inst_len)
# Generate stubs for the hooked functions
for func in build_funcs:
ret += self.generate_default_hookFunc(func)
return (ret, out)
def generate_hookdict(self, hookd, indent=1):
hookstr="self.hookdict = {"
for hook in hookd:
hookstr+="0x%x: %s," % (hook,hookd[hook])
hookstr=hookstr[:-1]+"}\n"
return ' ' * (indent * 4) + hookstr
def generate_unset_var_comments(self):
out = '# Variables listed below should be filled in: \n'
vs = self.conPass['unset_vars']
for v in vs:
out += "# %s %s --> %s \n" % (v.var.type, v.var, v.srcOperation)
return out
def generate_class(self):
global python2
'''
Wrap this chunk of code into a python class
'''
self.code = sorted(self.code, key=lambda x: x.address)
comments = ''
if "unset_vars" in self.conPass.keys():
comments += self.generate_unset_var_comments()
# Static Strings
if python2:
name=self.name
else:
name=self.name.decode('utf-8')
defn = "class %s(object):\n" % name
imp = "from unicorn import *\n" + self.imp_consts() + "import struct\nimport binascii\n"
init = ' ' * 4 + "def __init__(self):\n"
run = ' ' * 4 + "def run(self):\n"
# Dyanmic Strings
emuinit = self.generate_emuinit(indent = 2)
codevars = self.generate_code_vars(indent = 2)
datavars = self.generate_data_vars(indent = 2)
# Generate run function
runfns = self.generate_run_functions(indent=2)
if (self.impCallTargets):
# Build list of Return Addresses to Hooked Functions
hooks = self._build_impCall_hook_dict()
hookdict = self.generate_hookdict(hooks[1], indent=2)
hooks = hooks[0]
else:
hooks = ''
hookdict = ''
hookdict=hookdict
# mmaps and writes must be generated at the end
mmaps = self.generate_mmap(indent = 2)
writes = self.generate_mem_writes(indent = 2)
start_unicorn = self.generate_start_unicorn_func()
argf=""
if "args" in self.conPass.keys():
for i in range(0,len(self.conPass['args'])):
argf+="0,"
argf=argf[:-1]
# Put the pieces together
self.final = comments + imp + defn + init + emuinit + codevars + datavars + mmaps + writes \
+ hookdict + "\n" + hooks + start_unicorn + runfns + "\n" + ("x = %s()" % name) \
+"\n"+"print (x.run("+argf+"))\n"