forked from beaujeant/PwnAdventure3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinpatcher.py
189 lines (135 loc) · 5.54 KB
/
binpatcher.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
# -*- coding: utf-8 -*-
"""
Name: BinPatcher.py
Version: v1.0.0 (23/06/2017)
Date: 23/06/2017
Created By: Antonin Beaujeant
Description: BinPatcher is a Python script that allows you to patch a binary (one instruction only) at a given offset. More info: https://blog.keyidentity.com/2017/07/18/pwnadventure3-patching-binary/
Example:
$ python binpatcher.py -f libGameLogic.so -o 0x15ea64 -m 64 -i "movabs rax, 0x9"
"""
import argparse
import sys, os
from capstone import *
from keystone import *
def get_first_instruction_size( binary, offset ):
"""Get the data size of the first instruction of a given binary.
Retrieve the all the assembly instructions for a given binary blob (maximum)
64 bytes thanks to the Capstone framework. Takes the first instruction and
calculate the data size of it.
The size is important since we need to know if we have enough place to
overwrite the initial instruction with the new one(s).
Args:
binary: The binary to patch.
offset: The offset where the instruction to replace is located.
Returns:
The data size (int) of the first instruction located at the given offset.
"""
cpt = 0
size = 0
md = Cs( cs_arch, cs_mode )
# The longest instruction in x64 is 64 bytes
# We therefore need to take at least 64 bytes
# in order to find the size of the selected
# instruction
if args.verbose:
print ( "#######################" )
print ( "# ASSEMBLY CODE #" )
print ( "#######################\n" )
for i in md.disasm( binary[ offset : offset+64 ], offset ):
if not cpt:
if args.verbose:
print( "> 0x%x:\t%s\t%s\t" % (i.address, i.mnemonic, i.op_str) )
size = len(i.bytes)
else:
if args.verbose:
print( " 0x%x:\t%s\t%s" % (i.address, i.mnemonic, i.op_str) )
pass
cpt += 1
return size
def assemble( binins ):
"""Assemble instruction in binary format.
Assemble the given instruction(s) in assembly format to a binary format thanks
to the Keystone framework.
Args:
binins: Instruction in assembly format.
Returns:
The assembled (bin) instruction(s).
"""
if args.verbose:
print ( "\n#######################" )
print ( "# NEW INSTRUCTION #" )
print ( "#######################\n" )
try:
ks = Ks( ks_arch, ks_mode )
encoding, count = ks.asm( binins )
if args.verbose:
print( "%s = %s" % (binins, encoding) )
print( "Size: %i" % len( encoding ) )
except KsError as e:
print( "ERROR: %s" % e )
return encoding
def main( fpath, offset, mode, ins ):
"""Patch a binary file with a given set of instruction(s)
Replacing one instruction at a given offset by one or several instruction.
Args:
fpath: Path the binary to patch
offset: Offset where the instruction to replace is located
mode: 32bit or 64bit
ins: Instruction to replace with
Returns:
Save the patched binary. Return nothing.
"""
with open( fpath, 'rb' ) as f:
binary = f.read()
size = get_first_instruction_size( binary, offset )
if args.verbose:
print ( "\nSize: %i" % (size) )
if size:
binins = assemble( ins )
if len( binins ) <= size:
if args.verbose:
print ( "Enough space to fit the new instruction\n" )
# Padding with NOPs
binins = binins + [0x90]*( size - len(binins) )
# Overwritting the instruction
binary = binary[ : offset ] + ''.join( chr(c) for c in binins ) + binary[ offset+size : ]
# Saving the new patched file
if args.verbose:
print ( "Saving the patched file: %s" % (fpath + "_patched") )
with open( fpath + "_patched", 'wb' ) as f:
f.write( binary )
else:
print( "ERROR: Not enough space to fit the new instruction" )
else:
print( "ERROR: Couln't find instructions" )
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Patch a binary (one instruction only) at a given offset')
parser.add_argument('-f', "--file", required=True, help='binary file to patch')
parser.add_argument('-o', '--offset', required=True, help='the offset where the instruction to overwrite is located (e.g. 0x15ea64)')
parser.add_argument('-m', '--mode', required=True, type=int, help='processor mode: 32,64')
parser.add_argument('-i', '--instruction', required=True, help='the new instruction to write')
parser.add_argument('-v', "--verbose", help='debug mode', action="store_true")
args = parser.parse_args()
if not os.path.isfile( args.file ):
print( "ERROR: The file does not exist" )
sys.exit()
if args.offset[:2] == "0x":
offset = int( args.offset, 16 )
else:
print( "ERROR: Offset value should be hexadecimal, e.g. 0x1234" )
sys.exit()
if args.mode != 32 and args.mode != 64:
print( "ERROR: Mode should be either 32 or 64" )
sys.exit()
if args.mode == 64:
cs_mode = CS_MODE_64
cs_arch = CS_ARCH_X86
ks_mode = KS_MODE_64
ks_arch = KS_ARCH_X86
else:
cs_mode = CS_MODE_32
cs_arch = CS_ARCH_X86
ks_mode = KS_MODE_32
ks_arch = KS_ARCH_X86
main( args.file, offset, int( args.mode ), args.instruction )