Skip to content

Commit

Permalink
bpo-34087: Fix buffer overflow in int(s) and similar functions (GH-8274)
Browse files Browse the repository at this point in the history
`_PyUnicode_TransformDecimalAndSpaceToASCII()` missed trailing NUL char.
It caused buffer overflow in `_Py_string_to_number_with_underscores()`.

This bug is introduced in 9b6c60c.
(cherry picked from commit 16dfca4)

Co-authored-by: INADA Naoki <methane@users.noreply.github.com>
  • Loading branch information
miss-islington and methane committed Jul 14, 2018
1 parent cf21d00 commit c721472
Show file tree
Hide file tree
Showing 6 changed files with 15 additions and 0 deletions.
3 changes: 3 additions & 0 deletions Lib/test/test_complex.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,9 @@ def split_zeros(x):
self.assertEqual(type(complex("1"*500)), complex)
# check whitespace processing
self.assertEqual(complex('\N{EM SPACE}(\N{EN SPACE}1+1j ) '), 1+1j)
# Invalid unicode string
# See bpo-34087
self.assertRaises(ValueError, complex, '\u3053\u3093\u306b\u3061\u306f')

class EvilExc(Exception):
pass
Expand Down
3 changes: 3 additions & 0 deletions Lib/test/test_float.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@ def test_float(self):
# extra long strings should not be a problem
float(b'.' + b'1'*1000)
float('.' + '1'*1000)
# Invalid unicode string
# See bpo-34087
self.assertRaises(ValueError, float, '\u3053\u3093\u306b\u3061\u306f')

def test_underscores(self):
for lit in VALID_UNDERSCORE_LITERALS:
Expand Down
4 changes: 4 additions & 0 deletions Lib/test/test_long.py
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,10 @@ def test_long(self):
for base in invalid_bases:
self.assertRaises(ValueError, int, '42', base)

# Invalid unicode string
# See bpo-34087
self.assertRaises(ValueError, int, '\u3053\u3093\u306b\u3061\u306f')


def test_conversion(self):

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix buffer overflow while converting unicode to numeric values.
2 changes: 2 additions & 0 deletions Objects/unicodeobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -9076,13 +9076,15 @@ _PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
int decimal = Py_UNICODE_TODECIMAL(ch);
if (decimal < 0) {
out[i] = '?';
out[i+1] = '\0';
_PyUnicode_LENGTH(result) = i + 1;
break;
}
out[i] = '0' + decimal;
}
}

assert(_PyUnicode_CheckConsistency(result, 1));
return result;
}

Expand Down
2 changes: 2 additions & 0 deletions Python/pystrtod.c
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,8 @@ _Py_string_to_number_with_underscores(
char *dup, *end;
PyObject *result;

assert(s[orig_len] == '\0');

if (strchr(s, '_') == NULL) {
return innerfunc(s, orig_len, arg);
}
Expand Down

0 comments on commit c721472

Please sign in to comment.