Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions Lib/test/test_bytes.py
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,15 @@ def test_fromhex(self):
self.type2test.fromhex(data)
self.assertIn('at position %s' % pos, str(cm.exception))

# gh-158583: Check for out of bounds reads (uninitialized bytes).
# Create an array from a list to not overallocate.
a = array.array('B', list(b'1234 ')) # Py_ISSPACE() loop
self.assertEqual(self.type2test.fromhex(a), b'\x12\x34')

a = array.array('B', list(b'12345')) # Missing second digit
with self.assertRaises(ValueError):
self.type2test.fromhex(a)

def test_hex(self):
self.assertRaises(TypeError, self.type2test.hex)
self.assertRaises(TypeError, self.type2test.hex, 1)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
:meth:`bytes.fromhex` and :meth:`bytearray.fromhex`: Fix uninitialized
memory read. Patch by Victor Stinner.
18 changes: 10 additions & 8 deletions Objects/bytesobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -2691,33 +2691,35 @@ _PyBytes_FromHex(PyObject *string, int use_bytearray)
if (Py_ISSPACE(*str)) {
do {
str++;
if (str >= end) {
goto done;
}
} while (Py_ISSPACE(*str));
if (str >= end)
break;
}

top = _PyLong_DigitValue[*str];
if (top >= 16) {
invalid_char = str - start;
goto error;
}

str++;
if (str >= end) {
invalid_char = -1;
goto error;
}

bot = _PyLong_DigitValue[*str];
if (bot >= 16) {
/* Check if we had a second digit */
if (str >= end){
invalid_char = -1;
} else {
invalid_char = str - start;
}
invalid_char = str - start;
goto error;
}
str++;

*buf++ = (unsigned char)((top << 4) + bot);
}

done:
if (view.obj != NULL) {
PyBuffer_Release(&view);
}
Expand Down
Loading