-
Notifications
You must be signed in to change notification settings - Fork 6
/
run.py
236 lines (197 loc) · 8.05 KB
/
run.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
import argparse
import re
import logging
STOP_CODE = "00"
RETURN_CODE = "f3"
JUMPDEST_CODE = "5b"
PUSH2_CODE = "61"
REVERT_CODE = "fd"
class BytecodeInjector:
def __init__(self, base_bin, inject_bin):
self.base_bin = self.process_bin_str(base_bin)
self.inject_bin = self.process_bin_str(inject_bin)
# Split bin into two-character bytes
self.base_bytes = [
self.base_bin[i:i+2] for i in range(0, len(self.base_bin), 2)
]
self.inject_bytes = [
self.inject_bin[i:i+2] for i in range(0, len(self.inject_bin), 2)
]
self.L = len(self.base_bytes)
self.K = len(self.inject_bytes)
self.debug_print()
self.stop_sections = self.get_stop_sections_in_base_bytes()
print("[get_stop_sections_in_base_bytes]", self.stop_sections)
self.valid_jumpdests = self.get_valid_jumpdests_in_inject_bytes()
print("[get_valid_jumpdests_in_inject_bytes]", self.valid_jumpdests)
def process_bin_str(self, bin_str):
bin_str = bin_str.strip()
if bin_str[:2] == "0x":
bin_str = bin_str[2:]
# Get CBOR length from last two bytes
length = int(bin_str[-4:], 16)
print("CBOR length:", length, " bytes")
# Truncate metadata hash
bin_str = bin_str[:-2*(length+2)]
return bin_str
def get_stop_sections_in_base_bytes(self):
"""
Returns list of indices (i, j) corresponding to sections of
(JUMPDEST ... STOP) in base_bytes
Returns: List[Tuple[Int, Int]]
"""
stop_sections = []
last_jumpdest = -1
last_pushx = -1
last_x = -1
i = 0
while i < self.L:
opcode = self.base_bytes[i]
if opcode == JUMPDEST_CODE:
last_jumpdest = i
elif opcode[0] == '6' or opcode[0] == '7':
# Corresponds to PUSHX instruction, so jump forward
opcode_val = int("0x" + opcode, 16) # Eval in base 10
last_pushx = i
last_x = opcode_val - 0x60 + 1
i += last_x
elif (
opcode == STOP_CODE
and last_jumpdest != -1
and (i == self.L-1 or self.base_bytes[i+1] != STOP_CODE)
and (self.base_bytes[i-1] != STOP_CODE)
):
stop_sections.append((last_jumpdest, i))
i += 1
return stop_sections
def get_valid_jumpdests_in_inject_bytes(self):
"""
Returns list of tuples (i, occurrences = [j1, j2...]) for all indices
i where there is a JUMPDEST at index i of inject_bytes and all
occurrences of string "PUSH2 <JUMPDEST_LOC>" in inject_bin
Returns: List[Tuple[Int, List]]
"""
valid_jumpdests = []
for i in range(self.K):
if self.inject_bytes[i] == JUMPDEST_CODE: #0x5b
# Get the current location in hex
jumpdest_loc = self.format_hex_loc(i)
push_jumpdest_instr = PUSH2_CODE + jumpdest_loc # PUSH2 <JUMPDEST_LOC>
# ========= DEBUG =========
print("[get_valid_jumpdests_in_inject_bytes] Found at loc", i, "=", jumpdest_loc)
# ========= DEBUG =========
occurrences = [
m.start() for m in re.finditer(push_jumpdest_instr, self.inject_bin)
]
if len(occurrences) > 0:
valid_jumpdests.append((i, occurrences))
else:
# ========= DEBUG =========
print("[get_valid_jumpdests_in_inject_bytes] Did not find for", i)
# ========= DEBUG =========
return valid_jumpdests
def build_mod_bin(self):
concat_bin = self.base_bin[:]
curr_inject_offset = self.L
inject_offsets = []
# Append inject_bin once for each [JUMPDEST...STOP) section of base_bin
for i in range(len(self.stop_sections)):
inject_offsets.append(curr_inject_offset)
a, b = self.stop_sections[i]
# Get modified inject_bin where each jump location is offset
# by the current inject_offset
mod_inject_bin = self.replace_jumplocs_with_offsets(
self.inject_bin, self.valid_jumpdests, curr_inject_offset + b-a
)
snippet = self.base_bin[2*a:2*b]
print("[build_mod_bin] Append [JUMPDEST...STOP) snippet from base bin:", snippet)
injection = self.base_bin[2*a:2*b] + mod_inject_bin
print("[build_mod_bin] Inject code:", injection)
concat_bin += injection
curr_inject_offset = len(concat_bin) // 2
# Modify base_bin to jump to inject_offsets
mod_base_bin = self.base_bin[:]
for i in range(len(self.stop_sections)):
a, b = self.stop_sections[i] # (JUMPDEST_ind, STOP_ind)
mod_base_bin = self.replace_hex_index(mod_base_bin, a, inject_offsets[i])
result = mod_base_bin + concat_bin[2 * self.L:]
print("==========")
print("Bytecode injection complete!")
print("==========")
return result
def replace_hex_index(self, bytestring, find_index, replace_index):
"""
Modify a hex bytestring to replace 2-byte hex find_index with
2-byte hex replace_index
Returns: str
"""
find_hex = self.format_hex_loc(find_index)
replace_hex = self.format_hex_loc(replace_index)
print("[replace_hex_index in base_bin]: Replace", find_hex, ">>", replace_hex)
return bytestring.replace(find_hex, replace_hex)
def replace_jumplocs_with_offsets(self, bytestring, valid_jumpdests, offset_value):
"""
Return a modified bytestring where valid jump locations are offset
Returns: str
"""
mod_bytestring = bytestring[:]
for _, jump_occurrences in valid_jumpdests:
for j in jump_occurrences:
original_loc_hex = bytestring[j+2:j+6]
original_loc = int(original_loc_hex, 16)
new_loc = original_loc + offset_value
new_loc_hex = self.format_hex_loc(new_loc)
########## DEBUG ##########
print("[replace_jumplocs_with_offsets] Replacing", j+2, ": ", original_loc_hex, ">>", new_loc_hex)
########## DEBUG ##########
mod_bytestring = (
mod_bytestring[:j+2] +
new_loc_hex +
mod_bytestring[j+6:]
)
return mod_bytestring
def format_hex_loc(self, index):
"""
Returns index formatted as 2-byte hex string location, e.g. "05ac"
Returns: 4-character str
"""
return "{0:#0{1}x}".format(index,6)[2:]
def debug_print(self):
print("========== DEBUG ==========")
print("Base bin = ", self.base_bin)
print("Inject bin = ", self.inject_bin)
print("L = ", self.L)
print("K = ", self.K)
parser = argparse.ArgumentParser()
parser.add_argument(
'--base_bin_fname',
dest='base_bin_fname',
help="Input filename containing original bin-runtime bytecode",
# default="DeployedGetter.bin-runtime"
default="contracts/DarkForestGetter/Getter.bin-runtime"
)
parser.add_argument(
'--inject_bin_fname',
dest='inject_bin_fname',
help="Input filename containing to-be-injected bin-runtime bytecode",
default="contracts/InjectedAssert/InjectedAssert.bin-runtime"
)
parser.add_argument(
'--output_bin_fname',
dest='output_bin_fname',
help="Input filename for output bin-runtime bytecode",
default="BytecodeInjectorOutput.bin-runtime"
)
args = parser.parse_args()
f = open(args.base_bin_fname)
base_bin_str = f.read()
f.close()
f = open(args.inject_bin_fname)
inject_bin_str = f.read()
f.close()
injecter = BytecodeInjector(base_bin_str, inject_bin_str)
f = open(args.output_bin_fname, "w")
mod_bin_str = injecter.build_mod_bin()
print("Writing result to file...")
f.write(mod_bin_str)
f.close()