-
Notifications
You must be signed in to change notification settings - Fork 262
/
Copy pathpatch-sections-4xx.py
355 lines (312 loc) · 10.6 KB
/
patch-sections-4xx.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
#!/usr/bin/python
import argparse
import io
import os
import struct
import re
import lief
import idb
# Indices
INDEX_NULL = 0
INDEX_INTERP = 1
INDEX_DYNSYM = 2
INDEX_DYNSTR = 3
INDEX_TEXT = 4
INDEX_DYNAMIC = 5
INDEX_SHSTRTAB = 6
# Dynamic tags
DT_SCE_UNK_SYSCALLTAB = 0x6100002F
DT_SCE_UNK_SYSCALLTABSZ = 0x61000031
# Utilities
class Section(object):
def __init__(self):
self.name_idx = 0
self.type = lief.ELF.SECTION_TYPES.NULL
self.flags = lief.ELF.SECTION_FLAGS.NONE
self.virtual_address = 0
self.offset = 0
self.size = 0
self.link = 0
self.information = 0
self.alignment = 0
self.entry_size = 0
# Helpers
self.name = ""
self.content = b""
def serialize(self):
section_fmt = 'IIQQQQIIQQ'
assert struct.calcsize(section_fmt) == 0x40
return struct.pack(section_fmt,
self.name_idx,
int(self.type),
int(self.flags),
self.virtual_address,
self.offset,
self.size,
self.link,
self.information,
self.alignment,
self.entry_size)
class Symbol(object):
fmt = 'IBBHQQ'
def __init__(self, data=None):
if not data:
return
assert struct.calcsize(self.fmt) == 0x18
fields = struct.unpack(self.fmt, data)
self.name = fields[0]
self.info = fields[1]
self.other = fields[2]
self.shndx = fields[3]
self.value = fields[4]
self.size = fields[5]
# Helpers
self.content = b""
def serialize(self):
assert struct.calcsize(self.fmt) == 0x18
return struct.pack(self.fmt,
self.name,
self.info,
self.other,
self.shndx,
self.value,
self.size)
def patch_i08(stream, offset, value):
data = struct.pack('B', value)
stream.seek(offset)
stream.write(data)
def patch_i16(stream, offset, value):
data = struct.pack('H', value)
stream.seek(offset)
stream.write(data)
def patch_i32(stream, offset, value):
data = struct.pack('I', value)
stream.seek(offset)
stream.write(data)
def patch_i64(stream, offset, value):
data = struct.pack('Q', value)
stream.seek(offset)
stream.write(data)
def read_i32(elf, addr):
data = bytes(elf.get_content_from_virtual_address(addr, 4))
value = struct.unpack('I', data)[0]
return value
def get_load_segment(elf, index=0):
for segment in elf.segments:
if segment.type != lief.ELF.SEGMENT_TYPES.LOAD:
continue
if index == 0:
return segment
index -= 1
raise Exception("Segment not found")
def get_dynamic_segment(elf, index=0):
for segment in elf.segments:
if segment.type == lief.ELF.SEGMENT_TYPES.DYNAMIC:
return segment
raise Exception("Segment not found")
def get_dynamic_entry(elf, tag):
for de in elf.dynamic_entries:
if de.tag == tag:
return de
raise Exception("Segment not found")
def parse_map_symbols(path_map):
with open(path_map, 'r') as f:
for i in range(4):
f.readline()
for line in f.readlines():
match = re.search("[0-9A-F]{8}:([0-9A-F]{16})\s+(.*)", line)
if not match: break
g = match.groups()
yield g[1], int(g[0],16), 0
# Sections
def create_section_null():
return Section()
def create_section_interp(elf):
section = Section()
section.name = ".interp"
section.type = lief.ELF.SECTION_TYPES.PROGBITS
section.flags = lief.ELF.SECTION_FLAGS.ALLOC
section.link = 0
section.information = 0
section.alignment = 1
section.entry_size = 0
section.size = len(elf.dynamic_entries) * section.entry_size
# Assume it appears after Ehdr+Phdr's of the first LOAD segment
hdr = elf.header
assert hdr.header_size == hdr.program_header_offset
segment = get_load_segment(elf, index=0)
section.virtual_address = segment.virtual_address
section.virtual_address += hdr.header_size
section.virtual_address += hdr.numberof_segments * hdr.program_header_size
section.offset = elf.virtual_address_to_offset(segment.virtual_address)
# Assume it appears before the DT_INIT function
init_vaddr = get_dynamic_entry(elf, lief.ELF.DYNAMIC_TAGS.INIT).value
assert init_vaddr > section.virtual_address
section.size = init_vaddr - section.virtual_address
return section
def create_section_dynsym(elf, path_idb=None, path_map=None):
section = Section()
section.name = ".dynsym"
section.type = lief.ELF.SECTION_TYPES.DYNSYM
section.flags = lief.ELF.SECTION_FLAGS.ALLOC
section.link = INDEX_DYNSTR
section.information = 0
section.alignment = 8
section.offset = 0
section.entry_size = 0
section.size = 0
section.virtual_address = 0
section.entry_size = 0x18
index = 1
sym = Symbol()
if path_idb:
with idb.from_file(path_idb) as db:
api = idb.IDAPython(db)
for ea in api.idautils.Functions():
name = api.idc.GetFunctionName(ea)
sym.name = index
sym.info = 0x12
sym.other = 0
sym.shndx = 0x0 # TODO
sym.value = ea
sym.size = api.idc.GetFunctionAttr(ea, api.idc.FUNCATTR_END) - ea
section.content += sym.serialize()
section.size += section.entry_size
index += len(name) + 1
elif path_map:
sym = Symbol()
for name, addr, size in parse_map_symbols(path_map):
sym.name = index
sym.info = 0x12
sym.other = 0
sym.shndx = 0x0 # TODO
sym.value = addr
sym.size = 0x10000 # TODO
section.content += sym.serialize()
section.size += section.entry_size
index += len(name) + 1
return section
def create_section_dynstr(elf, path_idb=None, path_map=None):
section = Section()
section.name = ".dynstr"
section.type = lief.ELF.SECTION_TYPES.STRTAB
section.flags = lief.ELF.SECTION_FLAGS.ALLOC
section.link = 0
section.information = 0
section.alignment = 1
section.offset = 0
section.entry_size = 0
section.size = 0
section.virtual_address = 0
if path_idb:
section.content = b"\x00"
with idb.from_file(path_idb) as db:
api = idb.IDAPython(db)
for ea in api.idautils.Functions():
section.content += api.idc.GetFunctionName(ea).encode('ascii')
section.content += b"\x00"
elif path_map:
section.content = b"\x00"
for name, _, _ in parse_map_symbols(path_map):
section.content += name.encode('ascii')
section.content += b"\x00"
return section
def create_section_text(elf):
section = Section()
section.name = ".text"
section.type = lief.ELF.SECTION_TYPES.PROGBITS
section.flags = lief.ELF.SECTION_FLAGS.ALLOC | lief.ELF.SECTION_FLAGS.EXECINSTR
section.link = 0
section.information = 0
section.alignment = 16
section.entry_size = 0
section.size = len(elf.dynamic_entries) * section.entry_size
# TODO
segment = get_load_segment(elf, index=0)
section.virtual_address = segment.virtual_address
section.offset = elf.virtual_address_to_offset(section.virtual_address)
section.size = segment.virtual_size
return section
def create_section_dynamic(elf):
section = Section()
section.name = ".dynamic"
section.type = lief.ELF.SECTION_TYPES.DYNAMIC
section.flags = lief.ELF.SECTION_FLAGS.WRITE | lief.ELF.SECTION_FLAGS.ALLOC
section.link = INDEX_DYNSTR
section.information = 0
section.entry_size = 0x10
segment = get_dynamic_segment(elf)
section.virtual_address = segment.virtual_address
section.offset = elf.virtual_address_to_offset(segment.virtual_address)
section.size = segment.physical_size
section.alignment = segment.alignment
return section
def create_section_shstrtab(sections):
section = Section()
section.name = ".shstrtab"
section.type = lief.ELF.SECTION_TYPES.STRTAB
section.flags = lief.ELF.SECTION_FLAGS.NONE
section.link = 0
section.information = 0
section.alignment = 1
section.offset = 0
section.entry_size = 0
section.size = 0
section.content = b''
for other_section in sections:
other_section.name_idx = len(section.content)
section.content += other_section.name.encode('ascii') + b'\x00'
section.name_idx = len(section.content)
section.content += section.name.encode('ascii') + b'\x00'
return section
def patch_sections(path_in, path_out, path_idb=None, path_map=None):
elf = lief.parse(path_in)
assert len(elf.sections) == 0, "Expected an executable without sections"
sections = []
sections.append(create_section_null())
sections.append(create_section_interp(elf))
sections.append(create_section_dynsym(elf, path_idb, path_map))
sections.append(create_section_dynstr(elf, path_idb, path_map))
sections.append(create_section_text(elf))
sections.append(create_section_dynamic(elf))
sections.append(create_section_shstrtab(sections))
e_shentsize = 0x40
e_shoff = os.path.getsize(path_in)
e_shnum = len(sections)
e_shstrndx = INDEX_SHSTRTAB
with open(path_out, 'wb') as f:
with open(path_in, 'rb') as binary:
f.write(binary.read())
patch_i64(f, 0x28, e_shoff)
patch_i08(f, 0x3A, e_shentsize)
patch_i08(f, 0x3C, e_shnum)
patch_i08(f, 0x3E, e_shstrndx)
f.seek(0, io.SEEK_END)
offset = e_shoff + (e_shnum * e_shentsize)
for section in sections:
if section.content:
section.offset = offset
section.size = len(section.content)
offset += len(section.content)
f.write(section.serialize())
for section in sections:
f.write(section.content)
def main():
parser = argparse.ArgumentParser(
description='Generate ELF sections from dynamic entries in PS4 4.xx/5.xx kernels.')
parser.add_argument('--idb',
metavar='input.idb', help='Path to IDA database',
)
parser.add_argument('--map',
metavar='input.map', help='Path to MAP file (fallback)',
)
parser.add_argument('input',
metavar='input.elf', help='Path to input file',
)
parser.add_argument('output',
metavar='output.elf', help='Path to output file',
)
args = parser.parse_args()
patch_sections(args.input, args.output, args.idb, args.map)
if __name__ == '__main__':
main()