diff -r 8befb15024b5 Lib/test/test_random.py --- a/Lib/test/test_random.py Fri Jul 10 22:26:44 2015 +0300 +++ b/Lib/test/test_random.py Sun Jul 12 23:01:38 2015 +0300 @@ -338,6 +338,11 @@ class MersenneTwister_TestBasicOps(TestB self.assertRaises(TypeError, self.gen.setstate, (2, ('a',)*625, None)) # Last element s/b an int also self.assertRaises(TypeError, self.gen.setstate, (2, (0,)*624+('a',), None)) + # Last element s/b between 0 and 624 + with self.assertRaises((ValueError, OverflowError)): + self.gen.setstate((2, (1,)*624+(625,), None)) + with self.assertRaises((ValueError, OverflowError)): + self.gen.setstate((2, (1,)*624+(-1,), None)) # Little trick to make "tuple(x % (2**32) for x in internalstate)" # raise ValueError. I cannot think of a simple way to achieve this, so diff -r 8befb15024b5 Modules/_randommodule.c --- a/Modules/_randommodule.c Fri Jul 10 22:26:44 2015 +0300 +++ b/Modules/_randommodule.c Sun Jul 12 23:01:38 2015 +0300 @@ -335,6 +335,10 @@ random_setstate(RandomObject *self, PyOb index = PyLong_AsLong(PyTuple_GET_ITEM(state, i)); if (index == -1 && PyErr_Occurred()) return NULL; + if (index < 0 || index > N) { + PyErr_SetString(PyExc_ValueError, "invalid state"); + return NULL; + } self->index = (int)index; Py_INCREF(Py_None);