Skip to content

Commit 8b040e5

Browse files
[3.7] bpo-34922: Fix integer overflow in the digest() and hexdigest() methods (GH-9751) (GH-9798)
for the SHAKE algorithm in the hashlib module. (cherry picked from commit 9b8c2e7)
1 parent 57038bc commit 8b040e5

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

Lib/test/test_hashlib.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,20 @@ def test_hexdigest(self):
230230
self.assertIsInstance(h.digest(), bytes)
231231
self.assertEqual(hexstr(h.digest()), h.hexdigest())
232232

233+
def test_digest_length_overflow(self):
234+
# See issue #34922
235+
large_sizes = (2**29, 2**32-10, 2**32+10, 2**61, 2**64-10, 2**64+10)
236+
for cons in self.hash_constructors:
237+
h = cons()
238+
if h.name not in self.shakes:
239+
continue
240+
for digest in h.digest, h.hexdigest:
241+
with self.assertRaises((ValueError, OverflowError)):
242+
digest(-10)
243+
for length in large_sizes:
244+
with self.assertRaises((ValueError, OverflowError)):
245+
digest(length)
246+
233247
def test_name_attribute(self):
234248
for cons in self.hash_constructors:
235249
h = cons()
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fixed integer overflow in the :meth:`~hashlib.shake.digest()` and
2+
:meth:`~hashlib.shake.hexdigest()` methods for the SHAKE algorithm
3+
in the :mod:`hashlib` module.

Modules/_sha3/sha3module.c

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -594,7 +594,10 @@ _SHAKE_digest(SHA3object *self, PyObject *digestlen_obj, int hex)
594594
if (digestlen == (unsigned long) -1 && PyErr_Occurred()) {
595595
return NULL;
596596
}
597-
597+
if (digestlen >= (1 << 29)) {
598+
PyErr_SetString(PyExc_ValueError, "length is too large");
599+
return NULL;
600+
}
598601
/* ExtractLane needs at least SHA3_MAX_DIGESTSIZE + SHA3_LANESIZE and
599602
* SHA3_LANESIZE extra space.
600603
*/

0 commit comments

Comments
 (0)