forked from CrackerCat/lgk10exploit
-
Notifications
You must be signed in to change notification settings - Fork 1
/
partdump.py
88 lines (70 loc) · 2.51 KB
/
partdump.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
from argparse import ArgumentParser
import mmap
from struct import unpack
MAGIC = 0x58881688
EXT_MAGIC = 0x58891689
def get_next_partition(buffer, offset):
magic = unpack('<I', buffer[0:4])[0]
if magic != MAGIC:
raise RuntimeError('invalid magic')
alignment = 16
image_list_end = 0
header_size = 512
data_size = unpack('<I', buffer[4:8])[0]
if unpack('<I', buffer[48:52])[0] == EXT_MAGIC:
header_size = unpack('<I', buffer[52:56])[0]
image_list_end = unpack('<I', buffer[64:68])[0]
alignment = unpack('<I', buffer[68:72])[0]
data_size |= unpack('<I', buffer[72:76])[0] << 32
if image_list_end:
return None
else:
new_offset = offset + header_size + data_size
if new_offset % alignment != 0:
new_offset += (alignment - new_offset) % alignment
return new_offset
def extract_partition2(buffer, output, with_header: bool):
magic = unpack('<I', buffer[0:4])[0]
if magic != MAGIC:
raise RuntimeError('invalid magic')
header_size = 512
data_size = unpack('<I', buffer[4:8])[0]
alignment = 0
if unpack('<I', buffer[48:52])[0] == EXT_MAGIC:
header_size = unpack('<I', buffer[52:56])[0]
data_size |= unpack('<I', buffer[72:76])[0] << 32
alignment = unpack('<I', buffer[68:72])[0]
f = open(output, 'wb')
if not with_header:
f.write(buffer[header_size:header_size+data_size])
else:
data_size += header_size
data_size += (alignment - (data_size) % alignment)
f.write(buffer[:data_size])
f.close()
def extract_partition(buffer, index, output, with_header: bool):
i = 0
offset = 0
while True:
if i == index:
extract_partition2(buffer[offset:], output, with_header)
break
else:
n = get_next_partition(buffer[offset:], offset)
if n == None:
raise RuntimeError('no such partition: {}'.format(index))
assert isinstance(n, int)
offset = n
i += 1
def main():
parser = ArgumentParser()
parser.add_argument('-H', '--with-header', action='store_true')
parser.add_argument('input')
parser.add_argument('index', type=int)
parser.add_argument('output')
args = parser.parse_args()
input = open(args.input, 'rb')
input_buffer = mmap.mmap(input.fileno(), 0, access=mmap.ACCESS_READ)
extract_partition(input_buffer, args.index, args.output, args.with_header)
if __name__ == '__main__':
main()