-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDisassemble.py
628 lines (560 loc) · 19.2 KB
/
Disassemble.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
import os
import codecs
import re
import sys
import subprocess
from __main__ import currentProgram
from ghidra.program.database import ProgramAddressFactory
from ghidra.program.model.address import AddressSet
from ghidra.framework import ApplicationConfiguration
from ghidra.app.services import ProgramManager
from docking.widgets.filechooser import GhidraFile
from ghidra.program.model.lang import LanguageID
from ghidra.program.util import DefaultLanguageService, ProgramLocation
from ghidra.app.util import SymbolPath
from ghidra.app.util import NamespaceUtils
from ghidra.program.model.address import Address
from java.io import File
scriptFolder = os.path.abspath(os.path.dirname(__file__))
mainFolder = os.path.join(scriptFolder,"..","..","..","..")
procFolder = os.path.join(mainFolder,"Ghidra","Processors")
radare2Folder = os.path.join(mainFolder,"radare2","bin")
outFolder = mainFolder
rabinPath = os.path.join(radare2Folder,"rabin2.exe")
disassembled = ""
disassembledData = ""
disassembledBss = ""
config = ApplicationConfiguration()
monitor = config.getTaskMonitor()
program = None
rng = None
api = None
path = None
fileSize = None
name = None
proc = None
file = None
entryPoint = None
lang = None
compilerSpec = None
arch = None
bits = None
endian = None
Addressor = None
programContext = None
memoryBlocks = None
memory = None
memoryStart = None
memoryView = None
listingObj = None
disassembled = None
disassembledData = None
disassembledBss = None
deps = [
[ currentProgram, None ]
]
symbolName = [ "main" ]
def IsThunked(fn):
if str(fn.getName())[0:5] == "thunk":
return True
return False
def GetThunkedFunction(addr):
global symbolName
global program
global rng
global api
global path
global fileSize
global name
global proc
global file
global entryPoint
global lang
global compilerSpec
global arch
global bits
global endian
global Addressor
global programContext
global memoryBlocks
global memory
global memoryStart
global memoryView
global listingObj
global disassembled
global disassembledData
global disassembledBss
global deps
externalLocation = getFunctionAt(addr).getThunkedFunction(True).getExternalLocation()
externalSymbol = externalLocation.getSymbol()
libPath = program.getExternalManager().getExternalLibrary(externalLocation.getLibraryName()).getAssociatedProgramPath()
projectData = state.getProject().getProjectData()
libFile = projectData.getFile(libPath)
externalProgram = libFile.getImmutableDomainObject(libFile, DomainFile.DEFAULT_VERSION, monitor)
label = externalLocation.getLabel()
symbolPath = SymbolPath(label)
sym = None
for x in NamespaceUtils.getSymbols(symbolPath, externalProgram):
if x.isExternalEntryPoint():
sym = x
loc = sym.getProgramLocation()
fn = externalProgram.getFunctionManager().getFunctionAt(loc.getAddress())
return fn
def ResolveExternalFunction(fCode):
global symbolName
global program
global rng
global api
global path
global fileSize
global name
global proc
global file
global entryPoint
global lang
global compilerSpec
global arch
global bits
global endian
global Addressor
global programContext
global memoryBlocks
global memory
global memoryStart
global memoryView
global listingObj
global disassembled
global disassembledData
global disassembledBss
global deps
adr = None
funcs = list(filter(IsThunked,list(program.getFunctionManager().getFunctions(True))))
for thnk in funcs:
externalLoc = thnk.getExternalLocation()
adr = externalLoc.getAddress()
_min = program.getMinAddress()
adr = adr.add( int(_min.toString(),16) )
fCode = fCode.zfill(16)
while Address.min( program.getMaxAddress(), adr ) == adr:
code = ""
bytes = iter(api.getBytes(adr,8))
for di in bytes:
if int(di) < 0:
di = di & (2**bits-1)
di = hex(di).replace("0x","").replace("L","")
di = di[len(di)-2:]
code += di.zfill(2)
print(fCode + " <=> " + code)
if code == fCode:
break
adr = adr.add(8)
if code == fCode:
break
tkd = GetThunkedFunction(adr)
retProg = tkd.getProgram()
retAddr = tkd.getBody()
dep = [
retProg,
retAddr
]
deps.append(dep)
symbolName.append( str(sym) )
def MemFix():
global symbolName
global program
global rng
global api
global path
global fileSize
global name
global proc
global file
global entryPoint
global lang
global compilerSpec
global arch
global bits
global endian
global Addressor
global programContext
global memoryBlocks
global memory
global memoryStart
global memoryView
global listingObj
global disassembled
global disassembledData
global disassembledBss
global deps
for block in memoryBlocks:
block.setWrite(False)
def Disassemble():
global symbolName
global program
global rng
global api
global path
global fileSize
global name
global proc
global file
global entryPoint
global lang
global compilerSpec
global arch
global bits
global endian
global Addressor
global programContext
global memoryBlocks
global memory
global memoryStart
global memoryView
global listingObj
global disassembled
global disassembledData
global disassembledBss
global deps
api.start()
api.analyzeAll(program)
api.end(True)
disassembled += "bits64\n"
disassembled += "\nglobal main\n"
disassembled += "\nsection .text\n"
disassembled += "\nmain:\njmp " + entryPoint + "\n"
api.start()
for addr in iter(memoryView.getAddresses(True)):
if addr.toString() == entryPoint:
for block in memoryBlocks:
if block.contains(addr):
api.disassemble(block.getStart())
break
break
api.end(True)
refs = []
instructionAddrs = []
refsIndirectAddrs = []
instructions = iter(listingObj.getInstructions(True))
for i in instructions:
cntx = i.getInstructionContext()
addr = cntx.getAddress()
codeUnit = listingObj.getCodeUnitAt(addr)
_refs = codeUnit.getReferencesFrom()
codeUnitStr = str(codeUnit)
for r in _refs:
a = r.getToAddress()
isData = r.getReferenceType().isData()
isIndirect = r.getReferenceType().isIndirect()
if isData:
refs.append(r)
elif isIndirect:
refs.append(r)
refsIndirectAddrs.append(a.toString())
codeUnitStr = codeUnitStr.lower()
codeUnitStr = codeUnitStr.replace("lab_","LAB_")
codeUnitStr = codeUnitStr.replace("[0x","[LAB_")
codeUnitStr = codeUnitStr.replace(" ptr "," ")
codeUnitStr = codeUnitStr.replace("xmmword "," ")
check1 = re.findall(r'\.lock?', codeUnitStr)
if len(check1) > 0:
codeUnitStr = "lock " + codeUnitStr.replace(".lock","")
check2 = re.findall(r'\.rep[n]?[ze]?', codeUnitStr)
if len(check2) > 0:
codeUnitStr = check2[0][1:] + " " + codeUnitStr.replace(check2[0],"")
check3 = re.findall(r'stos[bwdq]|lods[bwdq]', codeUnitStr)
if len(check3) > 0:
if check3[0] == "lodsb":
reg = codeUnitStr.replace("lodsb ","").replace("rep ","")
size = "al"
codeUnitStr = "mov " + size + ",[" + reg + "]\ninc " + reg
elif check3[0] == "lodsw":
reg = codeUnitStr.replace("lodsw ","").replace("rep ","")
size = "ax"
codeUnitStr = "mov " + size + ",[" + reg + "]\ninc " + reg
codeUnitStr += "\ninc " + reg
elif check3[0] == "lodsd":
reg = codeUnitStr.replace("lodsd ","").replace("rep ","")
size = "eax"
codeUnitStr = "mov " + size + ",[" + reg + "]\ninc " + reg
codeUnitStr += "\ninc " + reg
codeUnitStr += "\ninc " + reg
codeUnitStr += "\ninc " + reg
elif check3[0] == "lodsq":
reg = codeUnitStr.replace("lodsq ","").replace("rep ","")
size = "rax"
codeUnitStr = "mov " + size + ",[" + reg + "]\ninc " + reg
codeUnitStr += "\ninc " + reg
codeUnitStr += "\ninc " + reg
codeUnitStr += "\ninc " + reg
codeUnitStr += "\ninc " + reg
codeUnitStr += "\ninc " + reg
codeUnitStr += "\ninc " + reg
codeUnitStr += "\ninc " + reg
elif check3[0] == "stosb":
reg = codeUnitStr.replace("stosb ","").replace("rep ","")
size = "al"
codeUnitStr = "mov [ss:" + reg + "]," + size + "\ninc " + reg
elif check3[0] == "stosw":
reg = codeUnitStr.replace("stosw ","").replace("rep ","")
size = "ax"
codeUnitStr = "mov [ss:" + reg + "]," + size + "\ninc " + reg
codeUnitStr += "\ninc " + reg
elif check3[0] == "stosd":
reg = codeUnitStr.replace("stosd ","").replace("rep ","")
size = "eax"
codeUnitStr = "mov [ss:" + reg + "]," + size + "\ninc " + reg
codeUnitStr += "\ninc " + reg
codeUnitStr += "\ninc " + reg
codeUnitStr += "\ninc " + reg
elif check3[0] == "stosq":
reg = codeUnitStr.replace("stosq ","").replace("rep ","")
size = "rax"
codeUnitStr = "mov [ss:" + reg + "]," + size + "\ninc " + reg
codeUnitStr += "\ninc " + reg
codeUnitStr += "\ninc " + reg
codeUnitStr += "\ninc " + reg
codeUnitStr += "\ninc " + reg
codeUnitStr += "\ninc " + reg
codeUnitStr += "\ninc " + reg
codeUnitStr += "\ninc " + reg
check4 = re.findall(r'scas[bwdq]|ins[bwdq]|movs[bwdq]', codeUnitStr)
if len(check4) > 0:
codeUnitStr = check4[0]
check5 = re.findall( r' LAB_[0-9a-f]+' , codeUnitStr )
if len(check5) > 0:
codeUnitStr = codeUnitStr.replace(check5[0], " [" + check5[0][1:] + "]" )
check6 = re.findall(r'\[LAB_[0-9a-f]{1,7}\]|\[LAB_[0-9a-f]{1,7} ',codeUnitStr)
if len(check6) > 0:
codeUnitStr = codeUnitStr.replace( "LAB_" , "0x" )
codeUnitStr = codeUnitStr.replace("[[","[")
codeUnitStr = codeUnitStr.replace("]]","]")
check7 = re.findall( r'call 0x[0-9a-f]{8,}|j(mp|[n]?[zcsegl]{1,2}) 0x[0-9a-f]{8,}',codeUnitStr)
if len(check7) > 0:
codeUnitStr = codeUnitStr.replace( "0x" , "LAB_" )
disassembled += "\n; " + codeUnit.getMinAddress().toString() + " -> " + codeUnit.getMaxAddress().toString()
disassembled += "\nLAB_"+addr.toString() + ":\n" + codeUnitStr + "\n"
instructionAddrs.append(addr.toString())
shortLabels = []
disassembled2 = disassembled.split("\n")
disassembled3 = []
currentMemoryAddress = ""
firstMemoryAddress = ""
for line in disassembled2:
jumping = re.findall(r'(call|j(mp|[n]?[zcsegl]{1,2})) ([dq]?word|byte) (\[LAB_[0-9a-f]+\])', line)
if line.startswith("; "):
currentMemoryAddress = re.findall( r'[0-9a-f]+', line )[0]
if firstMemoryAddress == "":
firstMemoryAddress = currentMemoryAddress
if len(jumping) == 0:
disassembled3.append(line)
else:
stringAddress = re.findall(r'LAB_[0-9a-f]+', ' '.join([str(x) for x in jumping[0]]))[0].replace("LAB_","")
if stringAddress in instructionAddrs:
disassembled3.append(line)
elif stringAddress in refsIndirectAddrs:
oldAddress = Addressor.getAddress(stringAddress)
newAddress = ""
newAddressArr = []
newAddressBytesIter = iter(api.getBytes(oldAddress,8))
for byt in newAddressBytesIter:
if int(byt) < 0:
byt = byt & (2**bits-1)
byt = hex(byt).replace("0x","").replace("L","")
byt = byt[len(byt)-2:]
newAddress = byt.zfill(2) + newAddress
while newAddress.startswith('0'):
newAddress = newAddress[1:]
oldLabel = "LAB_" + stringAddress
newLabel = "LAB_" + newAddress
if len(newLabel) < 12:
shortLabels.append(newLabel)
line = line.replace(oldLabel,newLabel)
disassembled3.append(line)
else:
disassembled3.append("; "+line)
disassembled = "\n".join(disassembled3)
disassembledData += "\nsection .data\n"
lnks = []
for ref in refs:
addr = ref.getToAddress().toString()
if addr not in lnks:
lnks.append(addr)
bsses = []
for lnk in lnks:
if lnk in instructionAddrs:
continue
addr = Addressor.getAddress(lnk)
label = "LAB_" + lnk
if memoryView.contains(addr):
dataIter = iter(api.getBytes(addr,fileSize))
data = []
zerosCounter = 0
for di in dataIter:
if int(di) == 0:
data.append("00h")
zerosCounter += 1
if zerosCounter > 2:
break
continue
if int(di) < 0:
di = di & (2**bits-1)
di = hex(di).replace("0x","").replace("L","")
di = di[len(di)-2:]
data.append("0x"+di.zfill(2))
data = ",".join(data)
while data.endswith(',00h'):
data = data[:-4]
disassembledData += "\n" + label + ": db " + data + "\n"
else:
if lnk not in bsses:
bsses.append(lnk)
disassembledBss += "\nsection .bss\n"
for lnk in bsses:
if lnk in instructionAddrs:
continue
if len(re.findall(r'Stack', lnk)) == 0:
name = "LAB_" + lnk
disassembledBss += "\n" + name + ": resb 16\n"
for shortLabel in shortLabels:
extFunctionCode = shortLabel[4:]
ResolveExternalFunction(extFunctionCode)
disassembled += "\n; External Code..."
depPath = deps[ len(deps)-1 ][0].getExecutablePath().lstrip("/")
depName = os.path.splitext(os.path.basename(depPath))[0]
disassembled += "\n" + shortLabel + ":\n%include '" + depName + "_" + symbolName[ len(symbolName)-1 ] + "'\n"
def Prepare():
global symbolName
global program
global rng
global api
global path
global fileSize
global name
global proc
global file
global entryPoint
global lang
global compilerSpec
global arch
global bits
global endian
global Addressor
global programContext
global memoryBlocks
global memory
global memoryStart
global memoryView
global listingObj
global disassembled
global disassembledData
global disassembledBss
global deps
program = deps[0][0]
rng = deps[0][1]
disassembled = ""
disassembledData = ""
disassembledBss = ""
api = ghidra.program.flatapi.FlatProgramAPI(program,monitor)
path = program.getExecutablePath().lstrip("/")
fileSize = int(os.path.getsize(path))
print("Size: " + str(fileSize) + " bytes")
name = "code"
if program != currentProgram:
name = os.path.splitext(os.path.basename(path))[0]
print("Input: " + path)
proc = subprocess.Popen([ rabinPath, "-e", path ], stdout=subprocess.PIPE)
path = os.path.join(outFolder,os.path.basename(path))
file = File(path)
path = file.getAbsolutePath()
(entryPoint, err) = proc.communicate()
entryPoint = re.findall(r'0x[0-9a-fA-F]+', entryPoint)[0].replace("0x","LAB_")
print("Start: " + entryPoint)
lang = program.getLanguage()
compilerSpec = program.getCompilerSpec()
arch = re.findall(r'[^:]+:', str(program.getLanguageID()))[0][0:-1]
bits = int(re.findall(r':\d+:', str(program.getLanguageID()))[0][1:-1])
endian = "LE"
if str(program.getLanguageID()).replace(":BE:","") != str(program.getLanguageID()):
endian = "BE"
print("Arch: " + arch + " " + endian + " (" + str(bits) + " bit)")
Addressor = ProgramAddressFactory(lang,compilerSpec)
programContext = ghidra.program.util.ProgramContextImpl(lang)
memoryBlocks = api.getMemoryBlocks()
memory = program.getMemory()
memoryStart = program.getMinAddress()
memoryView = memory.getAllInitializedAddressSet()
if rng != None:
memory = rng
memoryStart = rng.getMinAddress()
memoryView = rng
listingObj = program.getListing()
def Export():
global symbolName
global program
global rng
global api
global path
global fileSize
global name
global proc
global file
global entryPoint
global lang
global compilerSpec
global arch
global bits
global endian
global Addressor
global programContext
global memoryBlocks
global memory
global memoryStart
global memoryView
global listingObj
global disassembled
global disassembledData
global disassembledBss
global deps
assemblyContent = disassembled + disassembledData + disassembledBss
lowOut = os.path.join( outFolder, name + "_" + symbolName[0] + ".asm" )
print("Output: " + os.path.normpath(lowOut))
low = codecs.open(lowOut, "w","utf-8")
low.write(assemblyContent)
low.close()
def main():
global symbolName
global program
global rng
global api
global path
global fileSize
global name
global proc
global file
global entryPoint
global lang
global compilerSpec
global arch
global bits
global endian
global Addressor
global programContext
global memoryBlocks
global memory
global memoryStart
global memoryView
global listingObj
global disassembled
global disassembledData
global disassembledBss
global deps
while len(deps) > 0:
Prepare()
MemFix()
Disassemble()
Export()
del deps[0]
del symbolName[0]
return 0
if __name__ == "__main__":
main()