Skip to content

Commit a1247fd

Browse files
mdickinsongpshead
andcommitted
gh-95778: Correctly pre-check for int-to-str conversion (#96537)
Converting a large enough `int` to a decimal string raises `ValueError` as expected. However, the raise comes _after_ the quadratic-time base-conversion algorithm has run to completion. For effective DOS prevention, we need some kind of check before entering the quadratic-time loop. Oops! =) The quick fix: essentially we catch _most_ values that exceed the threshold up front. Those that slip through will still be on the small side (read: sufficiently fast), and will get caught by the existing check so that the limit remains exact. The justification for the current check. The C code check is: ```c max_str_digits / (3 * PyLong_SHIFT) <= (size_a - 11) / 10 ``` In GitHub markdown math-speak, writing $M$ for `max_str_digits`, $L$ for `PyLong_SHIFT` and $s$ for `size_a`, that check is: $$\left\lfloor\frac{M}{3L}\right\rfloor \le \left\lfloor\frac{s - 11}{10}\right\rfloor$$ From this it follows that $$\frac{M}{3L} < \frac{s-1}{10}$$ hence that $$\frac{L(s-1)}{M} > \frac{10}{3} > \log_2(10).$$ So $$2^{L(s-1)} > 10^M.$$ But our input integer $a$ satisfies $|a| \ge 2^{L(s-1)}$, so $|a|$ is larger than $10^M$. This shows that we don't accidentally capture anything _below_ the intended limit in the check. <!-- gh-issue-number: gh-95778 --> * Issue: gh-95778 <!-- /gh-issue-number --> Co-authored-by: Gregory P. Smith [Google LLC] <greg@krypto.org>
1 parent 0515141 commit a1247fd

File tree

3 files changed

+105
-5
lines changed

3 files changed

+105
-5
lines changed

Lib/test/test_int.py

+82
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import sys
2+
import time
23

34
import unittest
45
from test import support
@@ -626,6 +627,87 @@ def test_max_str_digits(self):
626627
with self.assertRaises(ValueError):
627628
str(i)
628629

630+
def test_denial_of_service_prevented_int_to_str(self):
631+
"""Regression test: ensure we fail before performing O(N**2) work."""
632+
maxdigits = sys.get_int_max_str_digits()
633+
assert maxdigits < 50_000, maxdigits # A test prerequisite.
634+
get_time = time.process_time
635+
if get_time() <= 0: # some platforms like WASM lack process_time()
636+
get_time = time.monotonic
637+
638+
huge_int = int(f'0x{"c"*65_000}', base=16) # 78268 decimal digits.
639+
digits = 78_268
640+
with support.adjust_int_max_str_digits(digits):
641+
start = get_time()
642+
huge_decimal = str(huge_int)
643+
seconds_to_convert = get_time() - start
644+
self.assertEqual(len(huge_decimal), digits)
645+
# Ensuring that we chose a slow enough conversion to measure.
646+
# It takes 0.1 seconds on a Zen based cloud VM in an opt build.
647+
if seconds_to_convert < 0.005:
648+
raise unittest.SkipTest('"slow" conversion took only '
649+
f'{seconds_to_convert} seconds.')
650+
651+
# We test with the limit almost at the size needed to check performance.
652+
# The performant limit check is slightly fuzzy, give it a some room.
653+
with support.adjust_int_max_str_digits(int(.995 * digits)):
654+
with self.assertRaises(ValueError) as err:
655+
start = get_time()
656+
str(huge_int)
657+
seconds_to_fail_huge = get_time() - start
658+
self.assertIn('conversion', str(err.exception))
659+
self.assertLess(seconds_to_fail_huge, seconds_to_convert/8)
660+
661+
# Now we test that a conversion that would take 30x as long also fails
662+
# in a similarly fast fashion.
663+
extra_huge_int = int(f'0x{"c"*500_000}', base=16) # 602060 digits.
664+
with self.assertRaises(ValueError) as err:
665+
start = get_time()
666+
# If not limited, 8 seconds said Zen based cloud VM.
667+
str(extra_huge_int)
668+
seconds_to_fail_extra_huge = get_time() - start
669+
self.assertIn('conversion', str(err.exception))
670+
self.assertLess(seconds_to_fail_extra_huge, seconds_to_convert/8)
671+
672+
def test_denial_of_service_prevented_str_to_int(self):
673+
"""Regression test: ensure we fail before performing O(N**2) work."""
674+
maxdigits = sys.get_int_max_str_digits()
675+
assert maxdigits < 100_000, maxdigits # A test prerequisite.
676+
get_time = time.process_time
677+
if get_time() <= 0: # some platforms like WASM lack process_time()
678+
get_time = time.monotonic
679+
680+
digits = 133700
681+
huge = '8'*digits
682+
with support.adjust_int_max_str_digits(digits):
683+
start = get_time()
684+
int(huge)
685+
seconds_to_convert = get_time() - start
686+
# Ensuring that we chose a slow enough conversion to measure.
687+
# It takes 0.1 seconds on a Zen based cloud VM in an opt build.
688+
if seconds_to_convert < 0.005:
689+
raise unittest.SkipTest('"slow" conversion took only '
690+
f'{seconds_to_convert} seconds.')
691+
692+
with support.adjust_int_max_str_digits(digits - 1):
693+
with self.assertRaises(ValueError) as err:
694+
start = get_time()
695+
int(huge)
696+
seconds_to_fail_huge = get_time() - start
697+
self.assertIn('conversion', str(err.exception))
698+
self.assertLess(seconds_to_fail_huge, seconds_to_convert/8)
699+
700+
# Now we test that a conversion that would take 30x as long also fails
701+
# in a similarly fast fashion.
702+
extra_huge = '7'*1_200_000
703+
with self.assertRaises(ValueError) as err:
704+
start = get_time()
705+
# If not limited, 8 seconds in the Zen based cloud VM.
706+
int(extra_huge)
707+
seconds_to_fail_extra_huge = get_time() - start
708+
self.assertIn('conversion', str(err.exception))
709+
self.assertLess(seconds_to_fail_extra_huge, seconds_to_convert/8)
710+
629711
def test_power_of_two_bases_unlimited(self):
630712
"""The limit does not apply to power of 2 bases."""
631713
maxdigits = sys.get_int_max_str_digits()

Misc/NEWS.d/next/Security/2022-08-07-16-53-38.gh-issue-95778.ch010gps.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,4 @@ limitation <int_max_str_digits>` documentation. The default limit is 4300
1111
digits in string form.
1212

1313
Patch by Gregory P. Smith [Google] and Christian Heimes [Red Hat] with feedback
14-
from Victor Stinner, Thomas Wouters, Steve Dower, and Ned Deily.
14+
from Victor Stinner, Thomas Wouters, Steve Dower, Ned Deily, and Mark Dickinson.

Objects/longobject.c

+22-4
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,8 @@ PyObject *_PyLong_One = NULL;
3838
#define IS_SMALL_INT(ival) (-NSMALLNEGINTS <= (ival) && (ival) < NSMALLPOSINTS)
3939
#define IS_SMALL_UINT(ival) ((ival) < NSMALLPOSINTS)
4040

41-
#define _MAX_STR_DIGITS_ERROR_FMT "Exceeds the limit (%d) for integer string conversion: value has %zd digits"
41+
#define _MAX_STR_DIGITS_ERROR_FMT_TO_INT "Exceeds the limit (%d) for integer string conversion: value has %zd digits"
42+
#define _MAX_STR_DIGITS_ERROR_FMT_TO_STR "Exceeds the limit (%d) for integer string conversion"
4243

4344
static PyObject *
4445
get_small_int(sdigit ival)
@@ -1722,6 +1723,23 @@ long_to_decimal_string_internal(PyObject *aa,
17221723
size_a = Py_ABS(Py_SIZE(a));
17231724
negative = Py_SIZE(a) < 0;
17241725

1726+
/* quick and dirty pre-check for overflowing the decimal digit limit,
1727+
based on the inequality 10/3 >= log2(10)
1728+
1729+
explanation in https://github.com/python/cpython/pull/96537
1730+
*/
1731+
if (size_a >= 10 * _PY_LONG_MAX_STR_DIGITS_THRESHOLD
1732+
/ (3 * PyLong_SHIFT) + 2) {
1733+
PyInterpreterState *interp = _PyInterpreterState_GET();
1734+
int max_str_digits = interp->int_max_str_digits;
1735+
if ((max_str_digits > 0) &&
1736+
(max_str_digits / (3 * PyLong_SHIFT) <= (size_a - 11) / 10)) {
1737+
PyErr_Format(PyExc_ValueError, _MAX_STR_DIGITS_ERROR_FMT_TO_STR,
1738+
max_str_digits);
1739+
return -1;
1740+
}
1741+
}
1742+
17251743
/* quick and dirty upper bound for the number of digits
17261744
required to express a in base _PyLong_DECIMAL_BASE:
17271745
@@ -1787,8 +1805,8 @@ long_to_decimal_string_internal(PyObject *aa,
17871805
Py_ssize_t strlen_nosign = strlen - negative;
17881806
if ((max_str_digits > 0) && (strlen_nosign > max_str_digits)) {
17891807
Py_DECREF(scratch);
1790-
PyErr_Format(PyExc_ValueError, _MAX_STR_DIGITS_ERROR_FMT,
1791-
max_str_digits, strlen_nosign);
1808+
PyErr_Format(PyExc_ValueError, _MAX_STR_DIGITS_ERROR_FMT_TO_STR,
1809+
max_str_digits);
17921810
return -1;
17931811
}
17941812
}
@@ -2462,7 +2480,7 @@ digit beyond the first.
24622480
PyInterpreterState *interp = _PyInterpreterState_GET();
24632481
int max_str_digits = interp->int_max_str_digits;
24642482
if ((max_str_digits > 0) && (digits > max_str_digits)) {
2465-
PyErr_Format(PyExc_ValueError, _MAX_STR_DIGITS_ERROR_FMT,
2483+
PyErr_Format(PyExc_ValueError, _MAX_STR_DIGITS_ERROR_FMT_TO_INT,
24662484
max_str_digits, digits);
24672485
return NULL;
24682486
}

0 commit comments

Comments
 (0)