Skip to content

Commit

Permalink
00387: CVE-2020-10735: Prevent DoS by very large int()
Browse files Browse the repository at this point in the history
pythongh-95778: CVE-2020-10735: Prevent DoS by very large int() (pythonGH-96504)

Converting between `int` and `str` in bases other than 2
(binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base 10 (decimal) now
raises a `ValueError` if the number of digits in string form is above a
limit to avoid potential denial of service attacks due to the algorithmic
complexity. This is a mitigation for CVE-2020-10735
(https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-10735).

This new limit can be configured or disabled by environment variable, command
line flag, or :mod:`sys` APIs. See the `Integer String Conversion Length
Limitation` documentation.  The default limit is 4300
digits in string form.

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

Notes on the backport to Python 3.6:

* Use "Python 3.6.15-13" version in the documentation, whereas this
  version will never be released
* Only add _Py_global_config_int_max_str_digits global variable:
  Python 3.6 doesn't have PyConfig API (PEP 597) nor _PyRuntime.
* sys.flags.int_max_str_digits cannot be -1 on Python 3.6: it is
  set to the default limit. Adapt test_int_max_str_digits() for that.
* Declare _PY_LONG_DEFAULT_MAX_STR_DIGITS and
  _PY_LONG_MAX_STR_DIGITS_THRESHOLD macros in longobject.h but only
  if the Py_BUILD_CORE macro is defined.
* Declare _Py_global_config_int_max_str_digits in pydebug.h.

(cherry picked from commit 511ca94)

pythongh-95778: Mention sys.set_int_max_str_digits() in error message (python#96874)

When ValueError is raised if an integer is larger than the limit,
mention sys.set_int_max_str_digits() in the error message.

(cherry picked from commit e841ffc)

pythongh-96848: Fix -X int_max_str_digits option parsing (python#96988)

Fix command line parsing: reject "-X int_max_str_digits" option with
no value (invalid) when the PYTHONINTMAXSTRDIGITS environment
variable is set to a valid limit.

(cherry picked from commit 4135166)
  • Loading branch information
vstinner authored and stratakis committed Mar 11, 2024
1 parent 7c27537 commit b1d1a7c
Show file tree
Hide file tree
Showing 25 changed files with 870 additions and 15 deletions.
8 changes: 8 additions & 0 deletions Doc/library/functions.rst
Expand Up @@ -748,6 +748,14 @@ are always available. They are listed here in alphabetical order.
.. versionchanged:: 3.6
Grouping digits with underscores as in code literals is allowed.

.. versionchanged:: 3.6.15-13
:class:`int` string inputs and string representations can be limited to
help avoid denial of service attacks. A :exc:`ValueError` is raised when
the limit is exceeded while converting a string *x* to an :class:`int` or
when converting an :class:`int` into a string would exceed the limit.
See the :ref:`integer string conversion length limitation
<int_max_str_digits>` documentation.


.. function:: isinstance(object, classinfo)

Expand Down
11 changes: 11 additions & 0 deletions Doc/library/json.rst
Expand Up @@ -18,6 +18,11 @@ is a lightweight data interchange format inspired by
`JavaScript <https://en.wikipedia.org/wiki/JavaScript>`_ object literal syntax
(although it is not a strict subset of JavaScript [#rfc-errata]_ ).

.. warning::
Be cautious when parsing JSON data from untrusted sources. A malicious
JSON string may cause the decoder to consume considerable CPU and memory
resources. Limiting the size of data to be parsed is recommended.

:mod:`json` exposes an API familiar to users of the standard library
:mod:`marshal` and :mod:`pickle` modules.

Expand Down Expand Up @@ -245,6 +250,12 @@ Basic Usage
be used to use another datatype or parser for JSON integers
(e.g. :class:`float`).

.. versionchanged:: 3.6.15-13
The default *parse_int* of :func:`int` now limits the maximum length of
the integer string via the interpreter's :ref:`integer string
conversion length limitation <int_max_str_digits>` to help avoid denial
of service attacks.

*parse_constant*, if specified, will be called with one of the following
strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``.
This can be used to raise an exception if invalid JSON numbers
Expand Down
159 changes: 159 additions & 0 deletions Doc/library/stdtypes.rst
Expand Up @@ -4671,6 +4671,165 @@ types, where they are relevant. Some of these are not reported by the
[<class 'bool'>]


.. _int_max_str_digits:

Integer string conversion length limitation
===========================================

CPython has a global limit for converting between :class:`int` and :class:`str`
to mitigate denial of service attacks. This limit *only* applies to decimal or
other non-power-of-two number bases. Hexadecimal, octal, and binary conversions
are unlimited. The limit can be configured.

The :class:`int` type in CPython is an abitrary length number stored in binary
form (commonly known as a "bignum"). There exists no algorithm that can convert
a string to a binary integer or a binary integer to a string in linear time,
*unless* the base is a power of 2. Even the best known algorithms for base 10
have sub-quadratic complexity. Converting a large value such as ``int('1' *
500_000)`` can take over a second on a fast CPU.

Limiting conversion size offers a practical way to avoid `CVE-2020-10735
<https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-10735>`_.

The limit is applied to the number of digit characters in the input or output
string when a non-linear conversion algorithm would be involved. Underscores
and the sign are not counted towards the limit.

When an operation would exceed the limit, a :exc:`ValueError` is raised:

.. doctest::

>>> import sys
>>> sys.set_int_max_str_digits(4300) # Illustrative, this is the default.
>>> _ = int('2' * 5432)
Traceback (most recent call last):
...
ValueError: Exceeds the limit (4300) for integer string conversion: value has 5432 digits; use sys.set_int_max_str_digits() to increase the limit.
>>> i = int('2' * 4300)
>>> len(str(i))
4300
>>> i_squared = i*i
>>> len(str(i_squared))
Traceback (most recent call last):
...
ValueError: Exceeds the limit (4300) for integer string conversion: value has 8599 digits; use sys.set_int_max_str_digits() to increase the limit.
>>> len(hex(i_squared))
7144
>>> assert int(hex(i_squared), base=16) == i*i # Hexadecimal is unlimited.

The default limit is 4300 digits as provided in
:data:`sys.int_info.default_max_str_digits <sys.int_info>`.
The lowest limit that can be configured is 640 digits as provided in
:data:`sys.int_info.str_digits_check_threshold <sys.int_info>`.

Verification:

.. doctest::

>>> import sys
>>> assert sys.int_info.default_max_str_digits == 4300, sys.int_info
>>> assert sys.int_info.str_digits_check_threshold == 640, sys.int_info
>>> msg = int('578966293710682886880994035146873798396722250538762761564'
... '9252925514383915483333812743580549779436104706260696366600'
... '571186405732').to_bytes(53, 'big')
...

.. versionadded:: 3.6.15-13

Affected APIs
-------------

The limitation only applies to potentially slow conversions between :class:`int`
and :class:`str` or :class:`bytes`:

* ``int(string)`` with default base 10.
* ``int(string, base)`` for all bases that are not a power of 2.
* ``str(integer)``.
* ``repr(integer)``
* any other string conversion to base 10, for example ``f"{integer}"``,
``"{}".format(integer)``, or ``b"%d" % integer``.

The limitations do not apply to functions with a linear algorithm:

* ``int(string, base)`` with base 2, 4, 8, 16, or 32.
* :func:`int.from_bytes` and :func:`int.to_bytes`.
* :func:`hex`, :func:`oct`, :func:`bin`.
* :ref:`formatspec` for hex, octal, and binary numbers.
* :class:`str` to :class:`float`.
* :class:`str` to :class:`decimal.Decimal`.

Configuring the limit
---------------------

Before Python starts up you can use an environment variable or an interpreter
command line flag to configure the limit:

* :envvar:`PYTHONINTMAXSTRDIGITS`, e.g.
``PYTHONINTMAXSTRDIGITS=640 python3`` to set the limit to 640 or
``PYTHONINTMAXSTRDIGITS=0 python3`` to disable the limitation.
* :option:`-X int_max_str_digits <-X>`, e.g.
``python3 -X int_max_str_digits=640``
* :data:`sys.flags.int_max_str_digits` contains the value of
:envvar:`PYTHONINTMAXSTRDIGITS` or :option:`-X int_max_str_digits <-X>`.
If both the env var and the ``-X`` option are set, the ``-X`` option takes
precedence. A value of *-1* indicates that both were unset, thus a value of
:data:`sys.int_info.default_max_str_digits` was used during initilization.

From code, you can inspect the current limit and set a new one using these
:mod:`sys` APIs:

* :func:`sys.get_int_max_str_digits` and :func:`sys.set_int_max_str_digits` are
a getter and setter for the interpreter-wide limit. Subinterpreters have
their own limit.

Information about the default and minimum can be found in :attr:`sys.int_info`:

* :data:`sys.int_info.default_max_str_digits <sys.int_info>` is the compiled-in
default limit.
* :data:`sys.int_info.str_digits_check_threshold <sys.int_info>` is the lowest
accepted value for the limit (other than 0 which disables it).

.. versionadded:: 3.6.15-13

.. caution::

Setting a low limit *can* lead to problems. While rare, code exists that
contains integer constants in decimal in their source that exceed the
minimum threshold. A consequence of setting the limit is that Python source
code containing decimal integer literals longer than the limit will
encounter an error during parsing, usually at startup time or import time or
even at installation time - anytime an up to date ``.pyc`` does not already
exist for the code. A workaround for source that contains such large
constants is to convert them to ``0x`` hexadecimal form as it has no limit.

Test your application thoroughly if you use a low limit. Ensure your tests
run with the limit set early via the environment or flag so that it applies
during startup and even during any installation step that may invoke Python
to precompile ``.py`` sources to ``.pyc`` files.

Recommended configuration
-------------------------

The default :data:`sys.int_info.default_max_str_digits` is expected to be
reasonable for most applications. If your application requires a different
limit, set it from your main entry point using Python version agnostic code as
these APIs were added in security patch releases in versions before 3.11.

Example::

>>> import sys
>>> if hasattr(sys, "set_int_max_str_digits"):
... upper_bound = 68000
... lower_bound = 4004
... current_limit = sys.get_int_max_str_digits()
... if current_limit == 0 or current_limit > upper_bound:
... sys.set_int_max_str_digits(upper_bound)
... elif current_limit < lower_bound:
... sys.set_int_max_str_digits(lower_bound)

If you need to disable it entirely, set it to ``0``.


.. rubric:: Footnotes

.. [1] Additional information on these special methods may be found in the Python
Expand Down
53 changes: 43 additions & 10 deletions Doc/library/sys.rst
Expand Up @@ -296,6 +296,7 @@ always available.
:const:`bytes_warning` :option:`-b`
:const:`quiet` :option:`-q`
:const:`hash_randomization` :option:`-R`
:const:`int_max_str_digits` :option:`-X int_max_str_digits <-X>` (:ref:`integer string conversion length limitation <int_max_str_digits>`)
============================= =============================

.. versionchanged:: 3.2
Expand All @@ -310,6 +311,9 @@ always available.
.. versionchanged:: 3.4
Added ``isolated`` attribute for :option:`-I` ``isolated`` flag.

.. versionchanged:: 3.6.15-13
Added the ``int_max_str_digits`` attribute.

.. data:: float_info

A :term:`struct sequence` holding information about the float type. It
Expand Down Expand Up @@ -468,6 +472,15 @@ always available.

.. versionadded:: 3.6


.. function:: get_int_max_str_digits()

Returns the current value for the :ref:`integer string conversion length
limitation <int_max_str_digits>`. See also :func:`set_int_max_str_digits`.

.. versionadded:: 3.6.15-13


.. function:: getrefcount(object)

Return the reference count of the *object*. The count returned is generally one
Expand Down Expand Up @@ -730,19 +743,31 @@ always available.

.. tabularcolumns:: |l|L|

+-------------------------+----------------------------------------------+
| Attribute | Explanation |
+=========================+==============================================+
| :const:`bits_per_digit` | number of bits held in each digit. Python |
| | integers are stored internally in base |
| | ``2**int_info.bits_per_digit`` |
+-------------------------+----------------------------------------------+
| :const:`sizeof_digit` | size in bytes of the C type used to |
| | represent a digit |
+-------------------------+----------------------------------------------+
+----------------------------------------+-----------------------------------------------+
| Attribute | Explanation |
+========================================+===============================================+
| :const:`bits_per_digit` | number of bits held in each digit. Python |
| | integers are stored internally in base |
| | ``2**int_info.bits_per_digit`` |
+----------------------------------------+-----------------------------------------------+
| :const:`sizeof_digit` | size in bytes of the C type used to |
| | represent a digit |
+----------------------------------------+-----------------------------------------------+
| :const:`default_max_str_digits` | default value for |
| | :func:`sys.get_int_max_str_digits` when it |
| | is not otherwise explicitly configured. |
+----------------------------------------+-----------------------------------------------+
| :const:`str_digits_check_threshold` | minimum non-zero value for |
| | :func:`sys.set_int_max_str_digits`, |
| | :envvar:`PYTHONINTMAXSTRDIGITS`, or |
| | :option:`-X int_max_str_digits <-X>`. |
+----------------------------------------+-----------------------------------------------+

.. versionadded:: 3.1

.. versionchanged:: 3.6.15-13
Added ``default_max_str_digits`` and ``str_digits_check_threshold``.


.. data:: __interactivehook__

Expand Down Expand Up @@ -1001,6 +1026,14 @@ always available.

Availability: Unix.

.. function:: set_int_max_str_digits(n)

Set the :ref:`integer string conversion length limitation
<int_max_str_digits>` used by this interpreter. See also
:func:`get_int_max_str_digits`.

.. versionadded:: 3.6.15-13

.. function:: setprofile(profilefunc)

.. index::
Expand Down
10 changes: 10 additions & 0 deletions Doc/library/test.rst
Expand Up @@ -625,6 +625,16 @@ The :mod:`test.support` module defines the following functions:
.. versionadded:: 3.6


.. function:: adjust_int_max_str_digits(max_digits)

This function returns a context manager that will change the global
:func:`sys.set_int_max_str_digits` setting for the duration of the
context to allow execution of test code that needs a different limit
on the number of digits when converting between an integer and string.

.. versionadded:: 3.6.15-13


The :mod:`test.support` module defines the following classes:

.. class:: TransientResource(exc, **kwargs)
Expand Down
14 changes: 14 additions & 0 deletions Doc/using/cmdline.rst
Expand Up @@ -422,6 +422,9 @@ Miscellaneous options
* ``-X showalloccount`` to output the total count of allocated objects for
each type when the program finishes. This only works when Python was built with
``COUNT_ALLOCS`` defined.
* ``-X int_max_str_digits`` configures the :ref:`integer string conversion
length limitation <int_max_str_digits>`. See also
:envvar:`PYTHONINTMAXSTRDIGITS`.

It also allows passing arbitrary values and retrieving them through the
:data:`sys._xoptions` dictionary.
Expand All @@ -438,6 +441,9 @@ Miscellaneous options
.. versionadded:: 3.6
The ``-X showalloccount`` option.

.. versionadded:: 3.6.15-13
The ``-X int_max_str_digits`` option.


Options you shouldn't use
~~~~~~~~~~~~~~~~~~~~~~~~~
Expand Down Expand Up @@ -571,6 +577,14 @@ conflict.
.. versionadded:: 3.2.3


.. envvar:: PYTHONINTMAXSTRDIGITS

If this variable is set to an integer, it is used to configure the
interpreter's global :ref:`integer string conversion length limitation
<int_max_str_digits>`.

.. versionadded:: 3.6.15-13

.. envvar:: PYTHONIOENCODING

If this is set before running the interpreter, it overrides the encoding used
Expand Down
15 changes: 15 additions & 0 deletions Doc/whatsnew/3.6.rst
Expand Up @@ -2488,3 +2488,18 @@ ASCII newline ``\n``, ``\r`` and tab ``\t`` characters are stripped from the
URL by the parser :func:`urllib.parse` preventing such attacks. The removal
characters are controlled by a new module level variable
``urllib.parse._UNSAFE_URL_BYTES_TO_REMOVE``. (See :issue:`43882`)


Notable security feature in 3.6.15-13
=====================================

Converting between :class:`int` and :class:`str` in bases other than 2
(binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base 10 (decimal)
now raises a :exc:`ValueError` if the number of digits in string form is
above a limit to avoid potential denial of service attacks due to the
algorithmic complexity. This is a mitigation for `CVE-2020-10735
<https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-10735>`_.
This limit can be configured or disabled by environment variable, command
line flag, or :mod:`sys` APIs. See the :ref:`integer string conversion
length limitation <int_max_str_digits>` documentation. The default limit
is 4300 digits in string form.

0 comments on commit b1d1a7c

Please sign in to comment.