Skip to content

Commit e50cd5b

Browse files
committed
MNT: protect from out-of-bounds data access at the c level
As suggested by @cgohlke
1 parent 1c06de3 commit e50cd5b

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import pytest
2+
import numpy as np
3+
from matplotlib import pyplot as plt
4+
from matplotlib.backends import _tkagg
5+
6+
7+
@pytest.mark.backend('TkAgg')
8+
def test_blit():
9+
def evil_blit(photoimage, aggimage, offsets, bboxptr):
10+
data = np.asarray(aggimage)
11+
height, width = data.shape[:2]
12+
dataptr = (height, width, data.ctypes.data)
13+
_tkagg.blit(
14+
photoimage.tk.interpaddr(), str(photoimage), dataptr, offsets,
15+
bboxptr)
16+
17+
fig, ax = plt.subplots()
18+
for bad_boxes in ((-1, 2, 0, 2),
19+
(2, 0, 0, 2),
20+
(1, 6, 0, 2),
21+
(0, 2, -1, 2),
22+
(0, 2, 2, 0),
23+
(0, 2, 1, 6),
24+
):
25+
with pytest.raises(ValueError):
26+
print(bad_boxes)
27+
evil_blit(fig.canvas._tkphoto,
28+
np.ones((4, 4, 4)),
29+
(0, 1, 2, 3),
30+
bad_boxes)

src/_tkagg.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,12 @@ static PyObject *mpl_tk_blit(PyObject *self, PyObject *args)
6767
PyErr_SetString(PyExc_ValueError, "Failed to extract Tk_PhotoHandle");
6868
goto exit;
6969
}
70+
if (0 > y1 || y1 > y2 || y2 > height ||
71+
0 > x1 || x1 > x2 || x2 > width ) {
72+
PyErr_SetString(PyExc_ValueError, "Attempting to draw out of bounds");
73+
goto exit;
74+
}
75+
7076
block.pixelPtr = data_ptr + 4 * ((height - y2) * width + x1);
7177
block.width = x2 - x1;
7278
block.height = y2 - y1;

0 commit comments

Comments
 (0)