Blame SOURCES/00387-cve-2020-10735-prevent-dos-by-very-large-int.patch

8c28fd
From ef282220bd6e759c125c82351355d27627a0c08f Mon Sep 17 00:00:00 2001
8c28fd
From: Victor Stinner <vstinner@python.org>
8c28fd
Date: Thu, 15 Sep 2022 17:35:24 +0200
8c28fd
Subject: [PATCH] 00387: CVE-2020-10735: Prevent DoS by very large int()
8c28fd
8c28fd
gh-95778: CVE-2020-10735: Prevent DoS by very large int() (GH-96504)
8c28fd
8c28fd
Converting between `int` and `str` in bases other than 2
8c28fd
(binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base 10 (decimal) now
8c28fd
raises a `ValueError` if the number of digits in string form is above a
8c28fd
limit to avoid potential denial of service attacks due to the algorithmic
8c28fd
complexity. This is a mitigation for CVE-2020-10735
8c28fd
(https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-10735).
8c28fd
8c28fd
This new limit can be configured or disabled by environment variable, command
8c28fd
line flag, or :mod:`sys` APIs. See the `Integer String Conversion Length
8c28fd
Limitation` documentation.  The default limit is 4300
8c28fd
digits in string form.
8c28fd
8c28fd
Patch by Gregory P. Smith [Google] and Christian Heimes [Red Hat] with feedback
8c28fd
from Victor Stinner, Thomas Wouters, Steve Dower, Ned Deily, and Mark Dickinson.
8c28fd
8c28fd
Notes on the backport to Python 3.6 in RHEL:
8c28fd
8c28fd
* Use "Python 3.6.8-48" version in the documentation, whereas this
8c28fd
  version will never be released
8c28fd
* Only add _Py_global_config_int_max_str_digits global variable:
8c28fd
  Python 3.6 doesn't have PyConfig API (PEP 597) nor _PyRuntime.
8c28fd
* sys.flags.int_max_str_digits cannot be -1 on Python 3.6: it is
8c28fd
  set to the default limit. Adapt test_int_max_str_digits() for that.
8c28fd
* Declare _PY_LONG_DEFAULT_MAX_STR_DIGITS and
8c28fd
  _PY_LONG_MAX_STR_DIGITS_THRESHOLD macros in longobject.h but only
8c28fd
  if the Py_BUILD_CORE macro is defined.
8c28fd
* Declare _Py_global_config_int_max_str_digits in pydebug.h.
8c28fd
8c28fd
(cherry picked from commit 511ca9452033ef95bc7d7fc404b8161068226002)
8c28fd
8c28fd
gh-95778: Mention sys.set_int_max_str_digits() in error message (#96874)
8c28fd
8c28fd
When ValueError is raised if an integer is larger than the limit,
8c28fd
mention sys.set_int_max_str_digits() in the error message.
8c28fd
8c28fd
(cherry picked from commit e841ffc915e82e5ea6e3b473205417d63494808d)
8c28fd
8c28fd
gh-96848: Fix -X int_max_str_digits option parsing (#96988)
8c28fd
8c28fd
Fix command line parsing: reject "-X int_max_str_digits" option with
8c28fd
no value (invalid) when the PYTHONINTMAXSTRDIGITS environment
8c28fd
variable is set to a valid limit.
8c28fd
8c28fd
(cherry picked from commit 41351662bcd21672d8ccfa62fe44d72027e6bcf8)
8c28fd
---
8c28fd
 Doc/library/functions.rst         |   8 ++
8c28fd
 Doc/library/json.rst              |  11 ++
8c28fd
 Doc/library/stdtypes.rst          | 159 ++++++++++++++++++++++++
8c28fd
 Doc/library/sys.rst               |  53 ++++++--
8c28fd
 Doc/library/test.rst              |  10 ++
8c28fd
 Doc/using/cmdline.rst             |  14 +++
8c28fd
 Doc/whatsnew/3.6.rst              |  15 +++
8c28fd
 Include/longobject.h              |  38 ++++++
8c28fd
 Include/pydebug.h                 |   2 +
8c28fd
 Lib/test/support/__init__.py      |  10 ++
8c28fd
 Lib/test/test_ast.py              |   8 ++
8c28fd
 Lib/test/test_cmd_line.py         |  35 ++++++
8c28fd
 Lib/test/test_compile.py          |  13 ++
8c28fd
 Lib/test/test_decimal.py          |  18 +++
8c28fd
 Lib/test/test_int.py              | 196 ++++++++++++++++++++++++++++++
8c28fd
 Lib/test/test_json/test_decode.py |   8 ++
8c28fd
 Lib/test/test_sys.py              |  11 +-
8c28fd
 Lib/test/test_xmlrpc.py           |  10 ++
8c28fd
 Modules/main.c                    |   7 ++
8c28fd
 Objects/longobject.c              | 168 ++++++++++++++++++++++++-
8c28fd
 Python/ast.c                      |  26 +++-
8c28fd
 Python/pylifecycle.c              |   2 +
8c28fd
 Python/sysmodule.c                |  46 ++++++-
8c28fd
 23 files changed, 853 insertions(+), 15 deletions(-)
8c28fd
8c28fd
diff --git a/Doc/library/functions.rst b/Doc/library/functions.rst
8c28fd
index bc528dd..b0806b2 100644
8c28fd
--- a/Doc/library/functions.rst
8c28fd
+++ b/Doc/library/functions.rst
8c28fd
@@ -748,6 +748,14 @@ are always available.  They are listed here in alphabetical order.
8c28fd
    .. versionchanged:: 3.6
8c28fd
       Grouping digits with underscores as in code literals is allowed.
8c28fd
 
8c28fd
+   .. versionchanged:: 3.6.8-48
8c28fd
+      :class:`int` string inputs and string representations can be limited to
8c28fd
+      help avoid denial of service attacks. A :exc:`ValueError` is raised when
8c28fd
+      the limit is exceeded while converting a string *x* to an :class:`int` or
8c28fd
+      when converting an :class:`int` into a string would exceed the limit.
8c28fd
+      See the :ref:`integer string conversion length limitation
8c28fd
+      <int_max_str_digits>` documentation.
8c28fd
+
8c28fd
 
8c28fd
 .. function:: isinstance(object, classinfo)
8c28fd
 
8c28fd
diff --git a/Doc/library/json.rst b/Doc/library/json.rst
8c28fd
index 98ca86e..330e53f 100644
8c28fd
--- a/Doc/library/json.rst
8c28fd
+++ b/Doc/library/json.rst
8c28fd
@@ -18,6 +18,11 @@ is a lightweight data interchange format inspired by
8c28fd
 `JavaScript <https://en.wikipedia.org/wiki/JavaScript>`_ object literal syntax
8c28fd
 (although it is not a strict subset of JavaScript [#rfc-errata]_ ).
8c28fd
 
8c28fd
+.. warning::
8c28fd
+   Be cautious when parsing JSON data from untrusted sources. A malicious
8c28fd
+   JSON string may cause the decoder to consume considerable CPU and memory
8c28fd
+   resources. Limiting the size of data to be parsed is recommended.
8c28fd
+
8c28fd
 :mod:`json` exposes an API familiar to users of the standard library
8c28fd
 :mod:`marshal` and :mod:`pickle` modules.
8c28fd
 
8c28fd
@@ -245,6 +250,12 @@ Basic Usage
8c28fd
    be used to use another datatype or parser for JSON integers
8c28fd
    (e.g. :class:`float`).
8c28fd
 
8c28fd
+   .. versionchanged:: 3.6.8-48
8c28fd
+      The default *parse_int* of :func:`int` now limits the maximum length of
8c28fd
+      the integer string via the interpreter's :ref:`integer string
8c28fd
+      conversion length limitation <int_max_str_digits>` to help avoid denial
8c28fd
+      of service attacks.
8c28fd
+
8c28fd
    *parse_constant*, if specified, will be called with one of the following
8c28fd
    strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``.
8c28fd
    This can be used to raise an exception if invalid JSON numbers
8c28fd
diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst
8c28fd
index 00e1f4c..1dc3253 100644
8c28fd
--- a/Doc/library/stdtypes.rst
8c28fd
+++ b/Doc/library/stdtypes.rst
8c28fd
@@ -4671,6 +4671,165 @@ types, where they are relevant.  Some of these are not reported by the
8c28fd
       [<class 'bool'>]
8c28fd
 
8c28fd
 
8c28fd
+.. _int_max_str_digits:
8c28fd
+
8c28fd
+Integer string conversion length limitation
8c28fd
+===========================================
8c28fd
+
8c28fd
+CPython has a global limit for converting between :class:`int` and :class:`str`
8c28fd
+to mitigate denial of service attacks. This limit *only* applies to decimal or
8c28fd
+other non-power-of-two number bases. Hexadecimal, octal, and binary conversions
8c28fd
+are unlimited. The limit can be configured.
8c28fd
+
8c28fd
+The :class:`int` type in CPython is an abitrary length number stored in binary
8c28fd
+form (commonly known as a "bignum"). There exists no algorithm that can convert
8c28fd
+a string to a binary integer or a binary integer to a string in linear time,
8c28fd
+*unless* the base is a power of 2. Even the best known algorithms for base 10
8c28fd
+have sub-quadratic complexity. Converting a large value such as ``int('1' *
8c28fd
+500_000)`` can take over a second on a fast CPU.
8c28fd
+
8c28fd
+Limiting conversion size offers a practical way to avoid `CVE-2020-10735
8c28fd
+<https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-10735>`_.
8c28fd
+
8c28fd
+The limit is applied to the number of digit characters in the input or output
8c28fd
+string when a non-linear conversion algorithm would be involved.  Underscores
8c28fd
+and the sign are not counted towards the limit.
8c28fd
+
8c28fd
+When an operation would exceed the limit, a :exc:`ValueError` is raised:
8c28fd
+
8c28fd
+.. doctest::
8c28fd
+
8c28fd
+   >>> import sys
8c28fd
+   >>> sys.set_int_max_str_digits(4300)  # Illustrative, this is the default.
8c28fd
+   >>> _ = int('2' * 5432)
8c28fd
+   Traceback (most recent call last):
8c28fd
+   ...
8c28fd
+   ValueError: Exceeds the limit (4300) for integer string conversion: value has 5432 digits; use sys.set_int_max_str_digits() to increase the limit.
8c28fd
+   >>> i = int('2' * 4300)
8c28fd
+   >>> len(str(i))
8c28fd
+   4300
8c28fd
+   >>> i_squared = i*i
8c28fd
+   >>> len(str(i_squared))
8c28fd
+   Traceback (most recent call last):
8c28fd
+   ...
8c28fd
+   ValueError: Exceeds the limit (4300) for integer string conversion: value has 8599 digits; use sys.set_int_max_str_digits() to increase the limit.
8c28fd
+   >>> len(hex(i_squared))
8c28fd
+   7144
8c28fd
+   >>> assert int(hex(i_squared), base=16) == i*i  # Hexadecimal is unlimited.
8c28fd
+
8c28fd
+The default limit is 4300 digits as provided in
8c28fd
+:data:`sys.int_info.default_max_str_digits <sys.int_info>`.
8c28fd
+The lowest limit that can be configured is 640 digits as provided in
8c28fd
+:data:`sys.int_info.str_digits_check_threshold <sys.int_info>`.
8c28fd
+
8c28fd
+Verification:
8c28fd
+
8c28fd
+.. doctest::
8c28fd
+
8c28fd
+   >>> import sys
8c28fd
+   >>> assert sys.int_info.default_max_str_digits == 4300, sys.int_info
8c28fd
+   >>> assert sys.int_info.str_digits_check_threshold == 640, sys.int_info
8c28fd
+   >>> msg = int('578966293710682886880994035146873798396722250538762761564'
8c28fd
+   ...           '9252925514383915483333812743580549779436104706260696366600'
8c28fd
+   ...           '571186405732').to_bytes(53, 'big')
8c28fd
+   ...
8c28fd
+
8c28fd
+.. versionadded:: 3.6.8-48
8c28fd
+
8c28fd
+Affected APIs
8c28fd
+-------------
8c28fd
+
8c28fd
+The limitation only applies to potentially slow conversions between :class:`int`
8c28fd
+and :class:`str` or :class:`bytes`:
8c28fd
+
8c28fd
+* ``int(string)`` with default base 10.
8c28fd
+* ``int(string, base)`` for all bases that are not a power of 2.
8c28fd
+* ``str(integer)``.
8c28fd
+* ``repr(integer)``
8c28fd
+* any other string conversion to base 10, for example ``f"{integer}"``,
8c28fd
+  ``"{}".format(integer)``, or ``b"%d" % integer``.
8c28fd
+
8c28fd
+The limitations do not apply to functions with a linear algorithm:
8c28fd
+
8c28fd
+* ``int(string, base)`` with base 2, 4, 8, 16, or 32.
8c28fd
+* :func:`int.from_bytes` and :func:`int.to_bytes`.
8c28fd
+* :func:`hex`, :func:`oct`, :func:`bin`.
8c28fd
+* :ref:`formatspec` for hex, octal, and binary numbers.
8c28fd
+* :class:`str` to :class:`float`.
8c28fd
+* :class:`str` to :class:`decimal.Decimal`.
8c28fd
+
8c28fd
+Configuring the limit
8c28fd
+---------------------
8c28fd
+
8c28fd
+Before Python starts up you can use an environment variable or an interpreter
8c28fd
+command line flag to configure the limit:
8c28fd
+
8c28fd
+* :envvar:`PYTHONINTMAXSTRDIGITS`, e.g.
8c28fd
+  ``PYTHONINTMAXSTRDIGITS=640 python3`` to set the limit to 640 or
8c28fd
+  ``PYTHONINTMAXSTRDIGITS=0 python3`` to disable the limitation.
8c28fd
+* :option:`-X int_max_str_digits <-X>`, e.g.
8c28fd
+  ``python3 -X int_max_str_digits=640``
8c28fd
+* :data:`sys.flags.int_max_str_digits` contains the value of
8c28fd
+  :envvar:`PYTHONINTMAXSTRDIGITS` or :option:`-X int_max_str_digits <-X>`.
8c28fd
+  If both the env var and the ``-X`` option are set, the ``-X`` option takes
8c28fd
+  precedence. A value of *-1* indicates that both were unset, thus a value of
8c28fd
+  :data:`sys.int_info.default_max_str_digits` was used during initilization.
8c28fd
+
8c28fd
+From code, you can inspect the current limit and set a new one using these
8c28fd
+:mod:`sys` APIs:
8c28fd
+
8c28fd
+* :func:`sys.get_int_max_str_digits` and :func:`sys.set_int_max_str_digits` are
8c28fd
+  a getter and setter for the interpreter-wide limit. Subinterpreters have
8c28fd
+  their own limit.
8c28fd
+
8c28fd
+Information about the default and minimum can be found in :attr:`sys.int_info`:
8c28fd
+
8c28fd
+* :data:`sys.int_info.default_max_str_digits <sys.int_info>` is the compiled-in
8c28fd
+  default limit.
8c28fd
+* :data:`sys.int_info.str_digits_check_threshold <sys.int_info>` is the lowest
8c28fd
+  accepted value for the limit (other than 0 which disables it).
8c28fd
+
8c28fd
+.. versionadded:: 3.6.8-48
8c28fd
+
8c28fd
+.. caution::
8c28fd
+
8c28fd
+   Setting a low limit *can* lead to problems. While rare, code exists that
8c28fd
+   contains integer constants in decimal in their source that exceed the
8c28fd
+   minimum threshold. A consequence of setting the limit is that Python source
8c28fd
+   code containing decimal integer literals longer than the limit will
8c28fd
+   encounter an error during parsing, usually at startup time or import time or
8c28fd
+   even at installation time - anytime an up to date ``.pyc`` does not already
8c28fd
+   exist for the code. A workaround for source that contains such large
8c28fd
+   constants is to convert them to ``0x`` hexadecimal form as it has no limit.
8c28fd
+
8c28fd
+   Test your application thoroughly if you use a low limit. Ensure your tests
8c28fd
+   run with the limit set early via the environment or flag so that it applies
8c28fd
+   during startup and even during any installation step that may invoke Python
8c28fd
+   to precompile ``.py`` sources to ``.pyc`` files.
8c28fd
+
8c28fd
+Recommended configuration
8c28fd
+-------------------------
8c28fd
+
8c28fd
+The default :data:`sys.int_info.default_max_str_digits` is expected to be
8c28fd
+reasonable for most applications. If your application requires a different
8c28fd
+limit, set it from your main entry point using Python version agnostic code as
8c28fd
+these APIs were added in security patch releases in versions before 3.11.
8c28fd
+
8c28fd
+Example::
8c28fd
+
8c28fd
+   >>> import sys
8c28fd
+   >>> if hasattr(sys, "set_int_max_str_digits"):
8c28fd
+   ...     upper_bound = 68000
8c28fd
+   ...     lower_bound = 4004
8c28fd
+   ...     current_limit = sys.get_int_max_str_digits()
8c28fd
+   ...     if current_limit == 0 or current_limit > upper_bound:
8c28fd
+   ...         sys.set_int_max_str_digits(upper_bound)
8c28fd
+   ...     elif current_limit < lower_bound:
8c28fd
+   ...         sys.set_int_max_str_digits(lower_bound)
8c28fd
+
8c28fd
+If you need to disable it entirely, set it to ``0``.
8c28fd
+
8c28fd
+
8c28fd
 .. rubric:: Footnotes
8c28fd
 
8c28fd
 .. [1] Additional information on these special methods may be found in the Python
8c28fd
diff --git a/Doc/library/sys.rst b/Doc/library/sys.rst
8c28fd
index 9198466..6144f8f 100644
8c28fd
--- a/Doc/library/sys.rst
8c28fd
+++ b/Doc/library/sys.rst
8c28fd
@@ -296,6 +296,7 @@ always available.
8c28fd
    :const:`bytes_warning`        :option:`-b`
8c28fd
    :const:`quiet`                :option:`-q`
8c28fd
    :const:`hash_randomization`   :option:`-R`
8c28fd
+   :const:`int_max_str_digits`   :option:`-X int_max_str_digits <-X>` (:ref:`integer string conversion length limitation <int_max_str_digits>`)
8c28fd
    ============================= =============================
8c28fd
 
8c28fd
    .. versionchanged:: 3.2
8c28fd
@@ -310,6 +311,9 @@ always available.
8c28fd
    .. versionchanged:: 3.4
8c28fd
       Added ``isolated`` attribute for :option:`-I` ``isolated`` flag.
8c28fd
 
8c28fd
+   .. versionchanged:: 3.6.8-48
8c28fd
+      Added the ``int_max_str_digits`` attribute.
8c28fd
+
8c28fd
 .. data:: float_info
8c28fd
 
8c28fd
    A :term:`struct sequence` holding information about the float type. It
8c28fd
@@ -468,6 +472,15 @@ always available.
8c28fd
 
8c28fd
    .. versionadded:: 3.6
8c28fd
 
8c28fd
+
8c28fd
+.. function:: get_int_max_str_digits()
8c28fd
+
8c28fd
+   Returns the current value for the :ref:`integer string conversion length
8c28fd
+   limitation <int_max_str_digits>`. See also :func:`set_int_max_str_digits`.
8c28fd
+
8c28fd
+   .. versionadded:: 3.6.8-48
8c28fd
+
8c28fd
+
8c28fd
 .. function:: getrefcount(object)
8c28fd
 
8c28fd
    Return the reference count of the *object*.  The count returned is generally one
8c28fd
@@ -730,19 +743,31 @@ always available.
8c28fd
 
8c28fd
    .. tabularcolumns:: |l|L|
8c28fd
 
8c28fd
-   +-------------------------+----------------------------------------------+
8c28fd
-   | Attribute               | Explanation                                  |
8c28fd
-   +=========================+==============================================+
8c28fd
-   | :const:`bits_per_digit` | number of bits held in each digit.  Python   |
8c28fd
-   |                         | integers are stored internally in base       |
8c28fd
-   |                         | ``2**int_info.bits_per_digit``               |
8c28fd
-   +-------------------------+----------------------------------------------+
8c28fd
-   | :const:`sizeof_digit`   | size in bytes of the C type used to          |
8c28fd
-   |                         | represent a digit                            |
8c28fd
-   +-------------------------+----------------------------------------------+
8c28fd
+   +----------------------------------------+-----------------------------------------------+
8c28fd
+   | Attribute                              | Explanation                                   |
8c28fd
+   +========================================+===============================================+
8c28fd
+   | :const:`bits_per_digit`                | number of bits held in each digit.  Python    |
8c28fd
+   |                                        | integers are stored internally in base        |
8c28fd
+   |                                        | ``2**int_info.bits_per_digit``                |
8c28fd
+   +----------------------------------------+-----------------------------------------------+
8c28fd
+   | :const:`sizeof_digit`                  | size in bytes of the C type used to           |
8c28fd
+   |                                        | represent a digit                             |
8c28fd
+   +----------------------------------------+-----------------------------------------------+
8c28fd
+   | :const:`default_max_str_digits`        | default value for                             |
8c28fd
+   |                                        | :func:`sys.get_int_max_str_digits` when it    |
8c28fd
+   |                                        | is not otherwise explicitly configured.       |
8c28fd
+   +----------------------------------------+-----------------------------------------------+
8c28fd
+   | :const:`str_digits_check_threshold`    | minimum non-zero value for                    |
8c28fd
+   |                                        | :func:`sys.set_int_max_str_digits`,           |
8c28fd
+   |                                        | :envvar:`PYTHONINTMAXSTRDIGITS`, or           |
8c28fd
+   |                                        | :option:`-X int_max_str_digits <-X>`.         |
8c28fd
+   +----------------------------------------+-----------------------------------------------+
8c28fd
 
8c28fd
    .. versionadded:: 3.1
8c28fd
 
8c28fd
+   .. versionchanged:: 3.6.8-48
8c28fd
+      Added ``default_max_str_digits`` and ``str_digits_check_threshold``.
8c28fd
+
8c28fd
 
8c28fd
 .. data:: __interactivehook__
8c28fd
 
8c28fd
@@ -1001,6 +1026,14 @@ always available.
8c28fd
 
8c28fd
    Availability: Unix.
8c28fd
 
8c28fd
+.. function:: set_int_max_str_digits(n)
8c28fd
+
8c28fd
+   Set the :ref:`integer string conversion length limitation
8c28fd
+   <int_max_str_digits>` used by this interpreter. See also
8c28fd
+   :func:`get_int_max_str_digits`.
8c28fd
+
8c28fd
+   .. versionadded:: 3.6.8-48
8c28fd
+
8c28fd
 .. function:: setprofile(profilefunc)
8c28fd
 
8c28fd
    .. index::
8c28fd
diff --git a/Doc/library/test.rst b/Doc/library/test.rst
8c28fd
index 04d6cd8..5153162 100644
8c28fd
--- a/Doc/library/test.rst
8c28fd
+++ b/Doc/library/test.rst
8c28fd
@@ -625,6 +625,16 @@ The :mod:`test.support` module defines the following functions:
8c28fd
    .. versionadded:: 3.6
8c28fd
 
8c28fd
 
8c28fd
+.. function:: adjust_int_max_str_digits(max_digits)
8c28fd
+
8c28fd
+   This function returns a context manager that will change the global
8c28fd
+   :func:`sys.set_int_max_str_digits` setting for the duration of the
8c28fd
+   context to allow execution of test code that needs a different limit
8c28fd
+   on the number of digits when converting between an integer and string.
8c28fd
+
8c28fd
+   .. versionadded:: 3.6.8-48
8c28fd
+
8c28fd
+
8c28fd
 The :mod:`test.support` module defines the following classes:
8c28fd
 
8c28fd
 .. class:: TransientResource(exc, **kwargs)
8c28fd
diff --git a/Doc/using/cmdline.rst b/Doc/using/cmdline.rst
8c28fd
index 65aa3ad..f5f76c4 100644
8c28fd
--- a/Doc/using/cmdline.rst
8c28fd
+++ b/Doc/using/cmdline.rst
8c28fd
@@ -422,6 +422,9 @@ Miscellaneous options
8c28fd
    * ``-X showalloccount`` to output the total count of allocated objects for
8c28fd
      each type when the program finishes. This only works when Python was built with
8c28fd
      ``COUNT_ALLOCS`` defined.
8c28fd
+   * ``-X int_max_str_digits`` configures the :ref:`integer string conversion
8c28fd
+     length limitation <int_max_str_digits>`.  See also
8c28fd
+     :envvar:`PYTHONINTMAXSTRDIGITS`.
8c28fd
 
8c28fd
    It also allows passing arbitrary values and retrieving them through the
8c28fd
    :data:`sys._xoptions` dictionary.
8c28fd
@@ -438,6 +441,9 @@ Miscellaneous options
8c28fd
    .. versionadded:: 3.6
8c28fd
       The ``-X showalloccount`` option.
8c28fd
 
8c28fd
+   .. versionadded:: 3.6.8-48
8c28fd
+      The ``-X int_max_str_digits`` option.
8c28fd
+
8c28fd
 
8c28fd
 Options you shouldn't use
8c28fd
 ~~~~~~~~~~~~~~~~~~~~~~~~~
8c28fd
@@ -571,6 +577,14 @@ conflict.
8c28fd
    .. versionadded:: 3.2.3
8c28fd
 
8c28fd
 
8c28fd
+.. envvar:: PYTHONINTMAXSTRDIGITS
8c28fd
+
8c28fd
+   If this variable is set to an integer, it is used to configure the
8c28fd
+   interpreter's global :ref:`integer string conversion length limitation
8c28fd
+   <int_max_str_digits>`.
8c28fd
+
8c28fd
+   .. versionadded:: 3.6.8-48
8c28fd
+
8c28fd
 .. envvar:: PYTHONIOENCODING
8c28fd
 
8c28fd
    If this is set before running the interpreter, it overrides the encoding used
8c28fd
diff --git a/Doc/whatsnew/3.6.rst b/Doc/whatsnew/3.6.rst
8c28fd
index 0095844..d669c5c 100644
8c28fd
--- a/Doc/whatsnew/3.6.rst
8c28fd
+++ b/Doc/whatsnew/3.6.rst
8c28fd
@@ -2438,3 +2438,18 @@ In 3.6.7 the :mod:`tokenize` module now implicitly emits a ``NEWLINE`` token
8c28fd
 when provided with input that does not have a trailing new line.  This behavior
8c28fd
 now matches what the C tokenizer does internally.
8c28fd
 (Contributed by Ammar Askar in :issue:`33899`.)
8c28fd
+
8c28fd
+
8c28fd
+Notable security feature in 3.6.8-48
8c28fd
+=====================================
8c28fd
+
8c28fd
+Converting between :class:`int` and :class:`str` in bases other than 2
8c28fd
+(binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base 10 (decimal)
8c28fd
+now raises a :exc:`ValueError` if the number of digits in string form is
8c28fd
+above a limit to avoid potential denial of service attacks due to the
8c28fd
+algorithmic complexity. This is a mitigation for `CVE-2020-10735
8c28fd
+<https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-10735>`_.
8c28fd
+This limit can be configured or disabled by environment variable, command
8c28fd
+line flag, or :mod:`sys` APIs. See the :ref:`integer string conversion
8c28fd
+length limitation <int_max_str_digits>` documentation.  The default limit
8c28fd
+is 4300 digits in string form.
8c28fd
diff --git a/Include/longobject.h b/Include/longobject.h
8c28fd
index efd409c..d8a080a 100644
8c28fd
--- a/Include/longobject.h
8c28fd
+++ b/Include/longobject.h
8c28fd
@@ -209,6 +209,44 @@ PyAPI_FUNC(long) PyOS_strtol(const char *, char **, int);
8c28fd
 PyAPI_FUNC(PyObject *) _PyLong_GCD(PyObject *, PyObject *);
8c28fd
 #endif /* !Py_LIMITED_API */
8c28fd
 
8c28fd
+#ifdef Py_BUILD_CORE
8c28fd
+/*
8c28fd
+ * Default int base conversion size limitation: Denial of Service prevention.
8c28fd
+ *
8c28fd
+ * Chosen such that this isn't wildly slow on modern hardware and so that
8c28fd
+ * everyone's existing deployed numpy test suite passes before
8c28fd
+ * https://github.com/numpy/numpy/issues/22098 is widely available.
8c28fd
+ *
8c28fd
+ * $ python -m timeit -s 's = "1"*4300' 'int(s)'
8c28fd
+ * 2000 loops, best of 5: 125 usec per loop
8c28fd
+ * $ python -m timeit -s 's = "1"*4300; v = int(s)' 'str(v)'
8c28fd
+ * 1000 loops, best of 5: 311 usec per loop
8c28fd
+ * (zen2 cloud VM)
8c28fd
+ *
8c28fd
+ * 4300 decimal digits fits a ~14284 bit number.
8c28fd
+ */
8c28fd
+#define _PY_LONG_DEFAULT_MAX_STR_DIGITS 4300
8c28fd
+/*
8c28fd
+ * Threshold for max digits check.  For performance reasons int() and
8c28fd
+ * int.__str__() don't checks values that are smaller than this
8c28fd
+ * threshold.  Acts as a guaranteed minimum size limit for bignums that
8c28fd
+ * applications can expect from CPython.
8c28fd
+ *
8c28fd
+ * % python -m timeit -s 's = "1"*640; v = int(s)' 'str(int(s))'
8c28fd
+ * 20000 loops, best of 5: 12 usec per loop
8c28fd
+ *
8c28fd
+ * "640 digits should be enough for anyone." - gps
8c28fd
+ * fits a ~2126 bit decimal number.
8c28fd
+ */
8c28fd
+#define _PY_LONG_MAX_STR_DIGITS_THRESHOLD 640
8c28fd
+
8c28fd
+#if ((_PY_LONG_DEFAULT_MAX_STR_DIGITS != 0) && \
8c28fd
+   (_PY_LONG_DEFAULT_MAX_STR_DIGITS < _PY_LONG_MAX_STR_DIGITS_THRESHOLD))
8c28fd
+# error "_PY_LONG_DEFAULT_MAX_STR_DIGITS smaller than threshold."
8c28fd
+#endif
8c28fd
+
8c28fd
+#endif /* Py_BUILD_CORE */
8c28fd
+
8c28fd
 #ifdef __cplusplus
8c28fd
 }
8c28fd
 #endif
8c28fd
diff --git a/Include/pydebug.h b/Include/pydebug.h
8c28fd
index 6e23a89..657c552 100644
8c28fd
--- a/Include/pydebug.h
8c28fd
+++ b/Include/pydebug.h
8c28fd
@@ -28,6 +28,8 @@ PyAPI_DATA(int) Py_IsolatedFlag;
8c28fd
 PyAPI_DATA(int) Py_LegacyWindowsStdioFlag;
8c28fd
 #endif
8c28fd
 
8c28fd
+PyAPI_DATA(int) _Py_global_config_int_max_str_digits;
8c28fd
+
8c28fd
 /* this is a wrapper around getenv() that pays attention to
8c28fd
    Py_IgnoreEnvironmentFlag.  It should be used for getting variables like
8c28fd
    PYTHONPATH and PYTHONHOME from the environment */
8c28fd
diff --git a/Lib/test/support/__init__.py b/Lib/test/support/__init__.py
8c28fd
index e33096e..99920ac 100644
8c28fd
--- a/Lib/test/support/__init__.py
8c28fd
+++ b/Lib/test/support/__init__.py
8c28fd
@@ -2912,3 +2912,13 @@ class FakePath:
8c28fd
             raise self.path
8c28fd
         else:
8c28fd
             return self.path
8c28fd
+
8c28fd
+@contextlib.contextmanager
8c28fd
+def adjust_int_max_str_digits(max_digits):
8c28fd
+    """Temporarily change the integer string conversion length limit."""
8c28fd
+    current = sys.get_int_max_str_digits()
8c28fd
+    try:
8c28fd
+        sys.set_int_max_str_digits(max_digits)
8c28fd
+        yield
8c28fd
+    finally:
8c28fd
+        sys.set_int_max_str_digits(current)
8c28fd
diff --git a/Lib/test/test_ast.py b/Lib/test/test_ast.py
8c28fd
index e68d0de..7f2d793 100644
8c28fd
--- a/Lib/test/test_ast.py
8c28fd
+++ b/Lib/test/test_ast.py
8c28fd
@@ -571,6 +571,14 @@ class ASTHelpers_Test(unittest.TestCase):
8c28fd
         exec(code, ns)
8c28fd
         self.assertIn('sleep', ns)
8c28fd
 
8c28fd
+    def test_literal_eval_str_int_limit(self):
8c28fd
+        with support.adjust_int_max_str_digits(4000):
8c28fd
+            ast.literal_eval('3'*4000)  # no error
8c28fd
+            with self.assertRaises(SyntaxError) as err_ctx:
8c28fd
+                ast.literal_eval('3'*4001)
8c28fd
+            self.assertIn('Exceeds the limit ', str(err_ctx.exception))
8c28fd
+            self.assertIn(' Consider hexadecimal ', str(err_ctx.exception))
8c28fd
+
8c28fd
 
8c28fd
 class ASTValidatorTests(unittest.TestCase):
8c28fd
 
8c28fd
diff --git a/Lib/test/test_cmd_line.py b/Lib/test/test_cmd_line.py
8c28fd
index 5922ed9..fe456ee 100644
8c28fd
--- a/Lib/test/test_cmd_line.py
8c28fd
+++ b/Lib/test/test_cmd_line.py
8c28fd
@@ -502,6 +502,41 @@ class CmdLineTest(unittest.TestCase):
8c28fd
         self.assertEqual(proc.returncode, 0, proc)
8c28fd
         self.assertEqual(proc.stdout.strip(), b'0')
8c28fd
 
8c28fd
+    def test_int_max_str_digits(self):
8c28fd
+        code = "import sys; print(sys.flags.int_max_str_digits, sys.get_int_max_str_digits())"
8c28fd
+
8c28fd
+        assert_python_failure('-X', 'int_max_str_digits', '-c', code)
8c28fd
+        assert_python_failure('-X', 'int_max_str_digits=foo', '-c', code)
8c28fd
+        assert_python_failure('-X', 'int_max_str_digits=100', '-c', code)
8c28fd
+        assert_python_failure('-X', 'int_max_str_digits', '-c', code,
8c28fd
+                              PYTHONINTMAXSTRDIGITS='4000')
8c28fd
+
8c28fd
+        assert_python_failure('-c', code, PYTHONINTMAXSTRDIGITS='foo')
8c28fd
+        assert_python_failure('-c', code, PYTHONINTMAXSTRDIGITS='100')
8c28fd
+
8c28fd
+        def res2int(res):
8c28fd
+            out = res.out.strip().decode("utf-8")
8c28fd
+            return tuple(int(i) for i in out.split())
8c28fd
+
8c28fd
+        res = assert_python_ok('-c', code)
8c28fd
+        self.assertEqual(res2int(res), (sys.get_int_max_str_digits(), sys.get_int_max_str_digits()))
8c28fd
+        res = assert_python_ok('-X', 'int_max_str_digits=0', '-c', code)
8c28fd
+        self.assertEqual(res2int(res), (0, 0))
8c28fd
+        res = assert_python_ok('-X', 'int_max_str_digits=4000', '-c', code)
8c28fd
+        self.assertEqual(res2int(res), (4000, 4000))
8c28fd
+        res = assert_python_ok('-X', 'int_max_str_digits=100000', '-c', code)
8c28fd
+        self.assertEqual(res2int(res), (100000, 100000))
8c28fd
+
8c28fd
+        res = assert_python_ok('-c', code, PYTHONINTMAXSTRDIGITS='0')
8c28fd
+        self.assertEqual(res2int(res), (0, 0))
8c28fd
+        res = assert_python_ok('-c', code, PYTHONINTMAXSTRDIGITS='4000')
8c28fd
+        self.assertEqual(res2int(res), (4000, 4000))
8c28fd
+        res = assert_python_ok(
8c28fd
+            '-X', 'int_max_str_digits=6000', '-c', code,
8c28fd
+            PYTHONINTMAXSTRDIGITS='4000'
8c28fd
+        )
8c28fd
+        self.assertEqual(res2int(res), (6000, 6000))
8c28fd
+
8c28fd
 
8c28fd
 def test_main():
8c28fd
     test.support.run_unittest(CmdLineTest)
8c28fd
diff --git a/Lib/test/test_compile.py b/Lib/test/test_compile.py
8c28fd
index 13cc882..00e6468 100644
8c28fd
--- a/Lib/test/test_compile.py
8c28fd
+++ b/Lib/test/test_compile.py
8c28fd
@@ -189,6 +189,19 @@ if 1:
8c28fd
         self.assertEqual(eval("0o777"), 511)
8c28fd
         self.assertEqual(eval("-0o0000010"), -8)
8c28fd
 
8c28fd
+    def test_int_literals_too_long(self):
8c28fd
+        n = 3000
8c28fd
+        source = f"a = 1\nb = 2\nc = {'3'*n}\nd = 4"
8c28fd
+        with support.adjust_int_max_str_digits(n):
8c28fd
+            compile(source, "<long_int_pass>", "exec")  # no errors.
8c28fd
+        with support.adjust_int_max_str_digits(n-1):
8c28fd
+            with self.assertRaises(SyntaxError) as err_ctx:
8c28fd
+                compile(source, "<long_int_fail>", "exec")
8c28fd
+            exc = err_ctx.exception
8c28fd
+            self.assertEqual(exc.lineno, 3)
8c28fd
+            self.assertIn('Exceeds the limit ', str(exc))
8c28fd
+            self.assertIn(' Consider hexadecimal ', str(exc))
8c28fd
+
8c28fd
     def test_unary_minus(self):
8c28fd
         # Verify treatment of unary minus on negative numbers SF bug #660455
8c28fd
         if sys.maxsize == 2147483647:
8c28fd
diff --git a/Lib/test/test_decimal.py b/Lib/test/test_decimal.py
8c28fd
index 8808a67..4459b82 100644
8c28fd
--- a/Lib/test/test_decimal.py
8c28fd
+++ b/Lib/test/test_decimal.py
8c28fd
@@ -2442,6 +2442,15 @@ class CUsabilityTest(UsabilityTest):
8c28fd
 class PyUsabilityTest(UsabilityTest):
8c28fd
     decimal = P
8c28fd
 
8c28fd
+    def setUp(self):
8c28fd
+        super().setUp()
8c28fd
+        self._previous_int_limit = sys.get_int_max_str_digits()
8c28fd
+        sys.set_int_max_str_digits(7000)
8c28fd
+
8c28fd
+    def tearDown(self):
8c28fd
+        sys.set_int_max_str_digits(self._previous_int_limit)
8c28fd
+        super().tearDown()
8c28fd
+
8c28fd
 class PythonAPItests(unittest.TestCase):
8c28fd
 
8c28fd
     def test_abc(self):
8c28fd
@@ -4499,6 +4508,15 @@ class CCoverage(Coverage):
8c28fd
 class PyCoverage(Coverage):
8c28fd
     decimal = P
8c28fd
 
8c28fd
+    def setUp(self):
8c28fd
+        super().setUp()
8c28fd
+        self._previous_int_limit = sys.get_int_max_str_digits()
8c28fd
+        sys.set_int_max_str_digits(7000)
8c28fd
+
8c28fd
+    def tearDown(self):
8c28fd
+        sys.set_int_max_str_digits(self._previous_int_limit)
8c28fd
+        super().tearDown()
8c28fd
+
8c28fd
 class PyFunctionality(unittest.TestCase):
8c28fd
     """Extra functionality in decimal.py"""
8c28fd
 
8c28fd
diff --git a/Lib/test/test_int.py b/Lib/test/test_int.py
8c28fd
index a36076e..6cd9a5e 100644
8c28fd
--- a/Lib/test/test_int.py
8c28fd
+++ b/Lib/test/test_int.py
8c28fd
@@ -1,4 +1,5 @@
8c28fd
 import sys
8c28fd
+import time
8c28fd
 
8c28fd
 import unittest
8c28fd
 from test import support
8c28fd
@@ -514,5 +515,200 @@ class IntTestCases(unittest.TestCase):
8c28fd
         self.assertEqual(int('1_2_3_4_5_6_7', 32), 1144132807)
8c28fd
 
8c28fd
 
8c28fd
+class IntStrDigitLimitsTests(unittest.TestCase):
8c28fd
+
8c28fd
+    int_class = int  # Override this in subclasses to reuse the suite.
8c28fd
+
8c28fd
+    def setUp(self):
8c28fd
+        super().setUp()
8c28fd
+        self._previous_limit = sys.get_int_max_str_digits()
8c28fd
+        sys.set_int_max_str_digits(2048)
8c28fd
+
8c28fd
+    def tearDown(self):
8c28fd
+        sys.set_int_max_str_digits(self._previous_limit)
8c28fd
+        super().tearDown()
8c28fd
+
8c28fd
+    def test_disabled_limit(self):
8c28fd
+        self.assertGreater(sys.get_int_max_str_digits(), 0)
8c28fd
+        self.assertLess(sys.get_int_max_str_digits(), 20_000)
8c28fd
+        with support.adjust_int_max_str_digits(0):
8c28fd
+            self.assertEqual(sys.get_int_max_str_digits(), 0)
8c28fd
+            i = self.int_class('1' * 20_000)
8c28fd
+            str(i)
8c28fd
+        self.assertGreater(sys.get_int_max_str_digits(), 0)
8c28fd
+
8c28fd
+    def test_max_str_digits_edge_cases(self):
8c28fd
+        """Ignore the +/- sign and space padding."""
8c28fd
+        int_class = self.int_class
8c28fd
+        maxdigits = sys.get_int_max_str_digits()
8c28fd
+
8c28fd
+        int_class('1' * maxdigits)
8c28fd
+        int_class(' ' + '1' * maxdigits)
8c28fd
+        int_class('1' * maxdigits + ' ')
8c28fd
+        int_class('+' + '1' * maxdigits)
8c28fd
+        int_class('-' + '1' * maxdigits)
8c28fd
+        self.assertEqual(len(str(10 ** (maxdigits - 1))), maxdigits)
8c28fd
+
8c28fd
+    def check(self, i, base=None):
8c28fd
+        with self.assertRaises(ValueError):
8c28fd
+            if base is None:
8c28fd
+                self.int_class(i)
8c28fd
+            else:
8c28fd
+                self.int_class(i, base)
8c28fd
+
8c28fd
+    def test_max_str_digits(self):
8c28fd
+        maxdigits = sys.get_int_max_str_digits()
8c28fd
+
8c28fd
+        self.check('1' * (maxdigits + 1))
8c28fd
+        self.check(' ' + '1' * (maxdigits + 1))
8c28fd
+        self.check('1' * (maxdigits + 1) + ' ')
8c28fd
+        self.check('+' + '1' * (maxdigits + 1))
8c28fd
+        self.check('-' + '1' * (maxdigits + 1))
8c28fd
+        self.check('1' * (maxdigits + 1))
8c28fd
+
8c28fd
+        i = 10 ** maxdigits
8c28fd
+        with self.assertRaises(ValueError):
8c28fd
+            str(i)
8c28fd
+
8c28fd
+    def test_denial_of_service_prevented_int_to_str(self):
8c28fd
+        """Regression test: ensure we fail before performing O(N**2) work."""
8c28fd
+        maxdigits = sys.get_int_max_str_digits()
8c28fd
+        assert maxdigits < 50_000, maxdigits  # A test prerequisite.
8c28fd
+        get_time = time.process_time
8c28fd
+        if get_time() <= 0:  # some platforms like WASM lack process_time()
8c28fd
+            get_time = time.monotonic
8c28fd
+
8c28fd
+        huge_int = int(f'0x{"c"*65_000}', base=16)  # 78268 decimal digits.
8c28fd
+        digits = 78_268
8c28fd
+        with support.adjust_int_max_str_digits(digits):
8c28fd
+            start = get_time()
8c28fd
+            huge_decimal = str(huge_int)
8c28fd
+        seconds_to_convert = get_time() - start
8c28fd
+        self.assertEqual(len(huge_decimal), digits)
8c28fd
+        # Ensuring that we chose a slow enough conversion to measure.
8c28fd
+        # It takes 0.1 seconds on a Zen based cloud VM in an opt build.
8c28fd
+        if seconds_to_convert < 0.005:
8c28fd
+            raise unittest.SkipTest('"slow" conversion took only '
8c28fd
+                                    f'{seconds_to_convert} seconds.')
8c28fd
+
8c28fd
+        # We test with the limit almost at the size needed to check performance.
8c28fd
+        # The performant limit check is slightly fuzzy, give it a some room.
8c28fd
+        with support.adjust_int_max_str_digits(int(.995 * digits)):
8c28fd
+            with self.assertRaises(ValueError) as err:
8c28fd
+                start = get_time()
8c28fd
+                str(huge_int)
8c28fd
+            seconds_to_fail_huge = get_time() - start
8c28fd
+        self.assertIn('conversion', str(err.exception))
8c28fd
+        self.assertLess(seconds_to_fail_huge, seconds_to_convert/8)
8c28fd
+
8c28fd
+        # Now we test that a conversion that would take 30x as long also fails
8c28fd
+        # in a similarly fast fashion.
8c28fd
+        extra_huge_int = int(f'0x{"c"*500_000}', base=16)  # 602060 digits.
8c28fd
+        with self.assertRaises(ValueError) as err:
8c28fd
+            start = get_time()
8c28fd
+            # If not limited, 8 seconds said Zen based cloud VM.
8c28fd
+            str(extra_huge_int)
8c28fd
+        seconds_to_fail_extra_huge = get_time() - start
8c28fd
+        self.assertIn('conversion', str(err.exception))
8c28fd
+        self.assertLess(seconds_to_fail_extra_huge, seconds_to_convert/8)
8c28fd
+
8c28fd
+    def test_denial_of_service_prevented_str_to_int(self):
8c28fd
+        """Regression test: ensure we fail before performing O(N**2) work."""
8c28fd
+        maxdigits = sys.get_int_max_str_digits()
8c28fd
+        assert maxdigits < 100_000, maxdigits  # A test prerequisite.
8c28fd
+        get_time = time.process_time
8c28fd
+        if get_time() <= 0:  # some platforms like WASM lack process_time()
8c28fd
+            get_time = time.monotonic
8c28fd
+
8c28fd
+        digits = 133700
8c28fd
+        huge = '8'*digits
8c28fd
+        with support.adjust_int_max_str_digits(digits):
8c28fd
+            start = get_time()
8c28fd
+            int(huge)
8c28fd
+        seconds_to_convert = get_time() - start
8c28fd
+        # Ensuring that we chose a slow enough conversion to measure.
8c28fd
+        # It takes 0.1 seconds on a Zen based cloud VM in an opt build.
8c28fd
+        if seconds_to_convert < 0.005:
8c28fd
+            raise unittest.SkipTest('"slow" conversion took only '
8c28fd
+                                    f'{seconds_to_convert} seconds.')
8c28fd
+
8c28fd
+        with support.adjust_int_max_str_digits(digits - 1):
8c28fd
+            with self.assertRaises(ValueError) as err:
8c28fd
+                start = get_time()
8c28fd
+                int(huge)
8c28fd
+            seconds_to_fail_huge = get_time() - start
8c28fd
+        self.assertIn('conversion', str(err.exception))
8c28fd
+        self.assertLess(seconds_to_fail_huge, seconds_to_convert/8)
8c28fd
+
8c28fd
+        # Now we test that a conversion that would take 30x as long also fails
8c28fd
+        # in a similarly fast fashion.
8c28fd
+        extra_huge = '7'*1_200_000
8c28fd
+        with self.assertRaises(ValueError) as err:
8c28fd
+            start = get_time()
8c28fd
+            # If not limited, 8 seconds in the Zen based cloud VM.
8c28fd
+            int(extra_huge)
8c28fd
+        seconds_to_fail_extra_huge = get_time() - start
8c28fd
+        self.assertIn('conversion', str(err.exception))
8c28fd
+        self.assertLess(seconds_to_fail_extra_huge, seconds_to_convert/8)
8c28fd
+
8c28fd
+    def test_power_of_two_bases_unlimited(self):
8c28fd
+        """The limit does not apply to power of 2 bases."""
8c28fd
+        maxdigits = sys.get_int_max_str_digits()
8c28fd
+
8c28fd
+        for base in (2, 4, 8, 16, 32):
8c28fd
+            with self.subTest(base=base):
8c28fd
+                self.int_class('1' * (maxdigits + 1), base)
8c28fd
+                assert maxdigits < 100_000
8c28fd
+                self.int_class('1' * 100_000, base)
8c28fd
+
8c28fd
+    def test_underscores_ignored(self):
8c28fd
+        maxdigits = sys.get_int_max_str_digits()
8c28fd
+
8c28fd
+        triples = maxdigits // 3
8c28fd
+        s = '111' * triples
8c28fd
+        s_ = '1_11' * triples
8c28fd
+        self.int_class(s)  # succeeds
8c28fd
+        self.int_class(s_)  # succeeds
8c28fd
+        self.check(f'{s}111')
8c28fd
+        self.check(f'{s_}_111')
8c28fd
+
8c28fd
+    def test_sign_not_counted(self):
8c28fd
+        int_class = self.int_class
8c28fd
+        max_digits = sys.get_int_max_str_digits()
8c28fd
+        s = '5' * max_digits
8c28fd
+        i = int_class(s)
8c28fd
+        pos_i = int_class(f'+{s}')
8c28fd
+        assert i == pos_i
8c28fd
+        neg_i = int_class(f'-{s}')
8c28fd
+        assert -pos_i == neg_i
8c28fd
+        str(pos_i)
8c28fd
+        str(neg_i)
8c28fd
+
8c28fd
+    def _other_base_helper(self, base):
8c28fd
+        int_class = self.int_class
8c28fd
+        max_digits = sys.get_int_max_str_digits()
8c28fd
+        s = '2' * max_digits
8c28fd
+        i = int_class(s, base)
8c28fd
+        if base > 10:
8c28fd
+            with self.assertRaises(ValueError):
8c28fd
+                str(i)
8c28fd
+        elif base < 10:
8c28fd
+            str(i)
8c28fd
+        with self.assertRaises(ValueError) as err:
8c28fd
+            int_class(f'{s}1', base)
8c28fd
+
8c28fd
+    def test_int_from_other_bases(self):
8c28fd
+        base = 3
8c28fd
+        with self.subTest(base=base):
8c28fd
+            self._other_base_helper(base)
8c28fd
+        base = 36
8c28fd
+        with self.subTest(base=base):
8c28fd
+            self._other_base_helper(base)
8c28fd
+
8c28fd
+
8c28fd
+class IntSubclassStrDigitLimitsTests(IntStrDigitLimitsTests):
8c28fd
+    int_class = IntSubclass
8c28fd
+
8c28fd
+
8c28fd
 if __name__ == "__main__":
8c28fd
     unittest.main()
8c28fd
diff --git a/Lib/test/test_json/test_decode.py b/Lib/test/test_json/test_decode.py
8c28fd
index 738f109..b5fd4f2 100644
8c28fd
--- a/Lib/test/test_json/test_decode.py
8c28fd
+++ b/Lib/test/test_json/test_decode.py
8c28fd
@@ -2,6 +2,7 @@ import decimal
8c28fd
 from io import StringIO, BytesIO
8c28fd
 from collections import OrderedDict
8c28fd
 from test.test_json import PyTest, CTest
8c28fd
+from test import support
8c28fd
 
8c28fd
 
8c28fd
 class TestDecode:
8c28fd
@@ -95,5 +96,12 @@ class TestDecode:
8c28fd
         d = self.json.JSONDecoder()
8c28fd
         self.assertRaises(ValueError, d.raw_decode, 'a'*42, -50000)
8c28fd
 
8c28fd
+    def test_limit_int(self):
8c28fd
+        maxdigits = 5000
8c28fd
+        with support.adjust_int_max_str_digits(maxdigits):
8c28fd
+            self.loads('1' * maxdigits)
8c28fd
+            with self.assertRaises(ValueError):
8c28fd
+                self.loads('1' * (maxdigits + 1))
8c28fd
+
8c28fd
 class TestPyDecode(TestDecode, PyTest): pass
8c28fd
 class TestCDecode(TestDecode, CTest): pass
8c28fd
diff --git a/Lib/test/test_sys.py b/Lib/test/test_sys.py
8c28fd
index b41239a..f2b9e08 100644
8c28fd
--- a/Lib/test/test_sys.py
8c28fd
+++ b/Lib/test/test_sys.py
8c28fd
@@ -444,11 +444,17 @@ class SysModuleTest(unittest.TestCase):
8c28fd
         self.assertIsInstance(sys.executable, str)
8c28fd
         self.assertEqual(len(sys.float_info), 11)
8c28fd
         self.assertEqual(sys.float_info.radix, 2)
8c28fd
-        self.assertEqual(len(sys.int_info), 2)
8c28fd
+        self.assertEqual(len(sys.int_info), 4)
8c28fd
         self.assertTrue(sys.int_info.bits_per_digit % 5 == 0)
8c28fd
         self.assertTrue(sys.int_info.sizeof_digit >= 1)
8c28fd
+        self.assertGreaterEqual(sys.int_info.default_max_str_digits, 500)
8c28fd
+        self.assertGreaterEqual(sys.int_info.str_digits_check_threshold, 100)
8c28fd
+        self.assertGreater(sys.int_info.default_max_str_digits,
8c28fd
+                           sys.int_info.str_digits_check_threshold)
8c28fd
         self.assertEqual(type(sys.int_info.bits_per_digit), int)
8c28fd
         self.assertEqual(type(sys.int_info.sizeof_digit), int)
8c28fd
+        self.assertIsInstance(sys.int_info.default_max_str_digits, int)
8c28fd
+        self.assertIsInstance(sys.int_info.str_digits_check_threshold, int)
8c28fd
         self.assertIsInstance(sys.hexversion, int)
8c28fd
 
8c28fd
         self.assertEqual(len(sys.hash_info), 9)
8c28fd
@@ -552,7 +558,8 @@ class SysModuleTest(unittest.TestCase):
8c28fd
         attrs = ("debug",
8c28fd
                  "inspect", "interactive", "optimize", "dont_write_bytecode",
8c28fd
                  "no_user_site", "no_site", "ignore_environment", "verbose",
8c28fd
-                 "bytes_warning", "quiet", "hash_randomization", "isolated")
8c28fd
+                 "bytes_warning", "quiet", "hash_randomization", "isolated",
8c28fd
+                 "int_max_str_digits")
8c28fd
         for attr in attrs:
8c28fd
             self.assertTrue(hasattr(sys.flags, attr), attr)
8c28fd
             self.assertEqual(type(getattr(sys.flags, attr)), int, attr)
8c28fd
diff --git a/Lib/test/test_xmlrpc.py b/Lib/test/test_xmlrpc.py
8c28fd
index fc601d4..58553dd 100644
8c28fd
--- a/Lib/test/test_xmlrpc.py
8c28fd
+++ b/Lib/test/test_xmlrpc.py
8c28fd
@@ -286,6 +286,16 @@ class XMLRPCTestCase(unittest.TestCase):
8c28fd
         check('<bigdecimal>9876543210.0123456789</bigdecimal>',
8c28fd
               decimal.Decimal('9876543210.0123456789'))
8c28fd
 
8c28fd
+    def test_limit_int(self):
8c28fd
+        check = self.check_loads
8c28fd
+        maxdigits = 5000
8c28fd
+        with support.adjust_int_max_str_digits(maxdigits):
8c28fd
+            s = '1' * (maxdigits + 1)
8c28fd
+            with self.assertRaises(ValueError):
8c28fd
+                check(f'<int>{s}</int>', None)
8c28fd
+            with self.assertRaises(ValueError):
8c28fd
+                check(f'<biginteger>{s}</biginteger>', None)
8c28fd
+
8c28fd
     def test_get_host_info(self):
8c28fd
         # see bug #3613, this raised a TypeError
8c28fd
         transp = xmlrpc.client.Transport()
8c28fd
diff --git a/Modules/main.c b/Modules/main.c
8c28fd
index 96d8be4..405e883 100644
8c28fd
--- a/Modules/main.c
8c28fd
+++ b/Modules/main.c
8c28fd
@@ -84,6 +84,9 @@ static const char usage_3[] = "\
8c28fd
          also PYTHONWARNINGS=arg\n\
8c28fd
 -x     : skip first line of source, allowing use of non-Unix forms of #!cmd\n\
8c28fd
 -X opt : set implementation-specific option\n\
8c28fd
+-X int_max_str_digits=number: limit the size of int<->str conversions.\n\
8c28fd
+    This helps avoid denial of service attacks when parsing untrusted data.\n\
8c28fd
+    The default is sys.int_info.default_max_str_digits.  0 disables.\n\
8c28fd
 ";
8c28fd
 static const char usage_4[] = "\
8c28fd
 file   : program read from script file\n\
8c28fd
@@ -105,6 +108,10 @@ static const char usage_6[] =
8c28fd
 "   to seed the hashes of str, bytes and datetime objects.  It can also be\n"
8c28fd
 "   set to an integer in the range [0,4294967295] to get hash values with a\n"
8c28fd
 "   predictable seed.\n"
8c28fd
+"PYTHONINTMAXSTRDIGITS: limits the maximum digit characters in an int value\n"
8c28fd
+"   when converting from a string and when converting an int back to a str.\n"
8c28fd
+"   A value of 0 disables the limit.  Conversions to or from bases 2, 4, 8,\n"
8c28fd
+"   16, and 32 are never limited.\n"
8c28fd
 "PYTHONMALLOC: set the Python memory allocators and/or install debug hooks\n"
8c28fd
 "   on Python memory allocators. Use PYTHONMALLOC=debug to install debug\n"
8c28fd
 "   hooks.\n"
8c28fd
diff --git a/Objects/longobject.c b/Objects/longobject.c
8c28fd
index 3864cec..ea01169 100644
8c28fd
--- a/Objects/longobject.c
8c28fd
+++ b/Objects/longobject.c
8c28fd
@@ -33,6 +33,9 @@ static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
8c28fd
 Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
8c28fd
 #endif
8c28fd
 
8c28fd
+#define _MAX_STR_DIGITS_ERROR_FMT_TO_INT "Exceeds the limit (%d) for integer string conversion: value has %zd digits; use sys.set_int_max_str_digits() to increase the limit"
8c28fd
+#define _MAX_STR_DIGITS_ERROR_FMT_TO_STR "Exceeds the limit (%d) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit"
8c28fd
+
8c28fd
 static PyObject *
8c28fd
 get_small_int(sdigit ival)
8c28fd
 {
8c28fd
@@ -1593,6 +1596,22 @@ long_to_decimal_string_internal(PyObject *aa,
8c28fd
     size_a = Py_ABS(Py_SIZE(a));
8c28fd
     negative = Py_SIZE(a) < 0;
8c28fd
 
8c28fd
+    /* quick and dirty pre-check for overflowing the decimal digit limit,
8c28fd
+       based on the inequality 10/3 >= log2(10)
8c28fd
+
8c28fd
+       explanation in https://github.com/python/cpython/pull/96537
8c28fd
+    */
8c28fd
+    if (size_a >= 10 * _PY_LONG_MAX_STR_DIGITS_THRESHOLD
8c28fd
+                  / (3 * PyLong_SHIFT) + 2) {
8c28fd
+        int max_str_digits = _Py_global_config_int_max_str_digits ;
8c28fd
+        if ((max_str_digits > 0) &&
8c28fd
+            (max_str_digits / (3 * PyLong_SHIFT) <= (size_a - 11) / 10)) {
8c28fd
+            PyErr_Format(PyExc_ValueError, _MAX_STR_DIGITS_ERROR_FMT_TO_STR,
8c28fd
+                         max_str_digits);
8c28fd
+            return -1;
8c28fd
+        }
8c28fd
+    }
8c28fd
+
8c28fd
     /* quick and dirty upper bound for the number of digits
8c28fd
        required to express a in base _PyLong_DECIMAL_BASE:
8c28fd
 
8c28fd
@@ -1652,6 +1671,16 @@ long_to_decimal_string_internal(PyObject *aa,
8c28fd
         tenpow *= 10;
8c28fd
         strlen++;
8c28fd
     }
8c28fd
+    if (strlen > _PY_LONG_MAX_STR_DIGITS_THRESHOLD) {
8c28fd
+        int max_str_digits = _Py_global_config_int_max_str_digits ;
8c28fd
+        Py_ssize_t strlen_nosign = strlen - negative;
8c28fd
+        if ((max_str_digits > 0) && (strlen_nosign > max_str_digits)) {
8c28fd
+            Py_DECREF(scratch);
8c28fd
+            PyErr_Format(PyExc_ValueError, _MAX_STR_DIGITS_ERROR_FMT_TO_STR,
8c28fd
+                         max_str_digits);
8c28fd
+            return -1;
8c28fd
+        }
8c28fd
+    }
8c28fd
     if (writer) {
8c28fd
         if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
8c28fd
             Py_DECREF(scratch);
8c28fd
@@ -2166,6 +2195,7 @@ PyLong_FromString(const char *str, char **pend, int base)
8c28fd
 
8c28fd
     start = str;
8c28fd
     if ((base & (base - 1)) == 0) {
8c28fd
+        /* binary bases are not limited by int_max_str_digits */
8c28fd
         int res = long_from_binary_base(&str, base, &z);
8c28fd
         if (res < 0) {
8c28fd
             /* Syntax error. */
8c28fd
@@ -2318,6 +2348,16 @@ digit beyond the first.
8c28fd
             goto onError;
8c28fd
         }
8c28fd
 
8c28fd
+        /* Limit the size to avoid excessive computation attacks. */
8c28fd
+        if (digits > _PY_LONG_MAX_STR_DIGITS_THRESHOLD) {
8c28fd
+            int max_str_digits = _Py_global_config_int_max_str_digits ;
8c28fd
+            if ((max_str_digits > 0) && (digits > max_str_digits)) {
8c28fd
+                PyErr_Format(PyExc_ValueError, _MAX_STR_DIGITS_ERROR_FMT_TO_INT,
8c28fd
+                             max_str_digits, digits);
8c28fd
+                return NULL;
8c28fd
+            }
8c28fd
+        }
8c28fd
+
8c28fd
         /* Create an int object that can contain the largest possible
8c28fd
          * integer with this base and length.  Note that there's no
8c28fd
          * need to initialize z->ob_digit -- no slot is read up before
8c28fd
@@ -4820,6 +4860,7 @@ long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
8c28fd
         }
8c28fd
         return PyLong_FromLong(0L);
8c28fd
     }
8c28fd
+    /* default base and limit, forward to standard implementation */
8c28fd
     if (obase == NULL)
8c28fd
         return PyNumber_Long(x);
8c28fd
 
8c28fd
@@ -5482,6 +5523,8 @@ internal representation of integers.  The attributes are read only.");
8c28fd
 static PyStructSequence_Field int_info_fields[] = {
8c28fd
     {"bits_per_digit", "size of a digit in bits"},
8c28fd
     {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
8c28fd
+    {"default_max_str_digits", "maximum string conversion digits limitation"},
8c28fd
+    {"str_digits_check_threshold", "minimum positive value for int_max_str_digits"},
8c28fd
     {NULL, NULL}
8c28fd
 };
8c28fd
 
8c28fd
@@ -5489,7 +5532,7 @@ static PyStructSequence_Desc int_info_desc = {
8c28fd
     "sys.int_info",   /* name */
8c28fd
     int_info__doc__,  /* doc */
8c28fd
     int_info_fields,  /* fields */
8c28fd
-    2                 /* number of fields */
8c28fd
+    4                 /* number of fields */
8c28fd
 };
8c28fd
 
8c28fd
 PyObject *
8c28fd
@@ -5504,6 +5547,17 @@ PyLong_GetInfo(void)
8c28fd
                               PyLong_FromLong(PyLong_SHIFT));
8c28fd
     PyStructSequence_SET_ITEM(int_info, field++,
8c28fd
                               PyLong_FromLong(sizeof(digit)));
8c28fd
+    /*
8c28fd
+     * The following two fields were added after investigating uses of
8c28fd
+     * sys.int_info in the wild: Exceedingly rarely used. The ONLY use found was
8c28fd
+     * numba using sys.int_info.bits_per_digit as attribute access rather than
8c28fd
+     * sequence unpacking. Cython and sympy also refer to sys.int_info but only
8c28fd
+     * as info for debugging. No concern about adding these in a backport.
8c28fd
+     */
8c28fd
+    PyStructSequence_SET_ITEM(int_info, field++,
8c28fd
+                              PyLong_FromLong(_PY_LONG_DEFAULT_MAX_STR_DIGITS));
8c28fd
+    PyStructSequence_SET_ITEM(int_info, field++,
8c28fd
+                              PyLong_FromLong(_PY_LONG_MAX_STR_DIGITS_THRESHOLD));
8c28fd
     if (PyErr_Occurred()) {
8c28fd
         Py_CLEAR(int_info);
8c28fd
         return NULL;
8c28fd
@@ -5511,6 +5565,116 @@ PyLong_GetInfo(void)
8c28fd
     return int_info;
8c28fd
 }
8c28fd
 
8c28fd
+
8c28fd
+static int
8c28fd
+pymain_str_to_int(const char *str, int *result)
8c28fd
+{
8c28fd
+    errno = 0;
8c28fd
+    const char *endptr = str;
8c28fd
+    long value = strtol(str, (char **)&endptr, 10);
8c28fd
+    if (*endptr != '\0' || errno == ERANGE) {
8c28fd
+        return -1;
8c28fd
+    }
8c28fd
+    if (value < INT_MIN || value > INT_MAX) {
8c28fd
+        return -1;
8c28fd
+    }
8c28fd
+
8c28fd
+    *result = (int)value;
8c28fd
+    return 0;
8c28fd
+}
8c28fd
+
8c28fd
+
8c28fd
+static int
8c28fd
+long_get_max_str_digits_xoption(int *pmaxdigits)
8c28fd
+{
8c28fd
+    PyObject *xoptions = PySys_GetXOptions();
8c28fd
+    if (xoptions == NULL) {
8c28fd
+        return -1;
8c28fd
+    }
8c28fd
+
8c28fd
+    PyObject *key = PyUnicode_FromString("int_max_str_digits");
8c28fd
+    if (key == NULL) {
8c28fd
+        return -1;
8c28fd
+    }
8c28fd
+
8c28fd
+    PyObject *value = PyDict_GetItemWithError(xoptions, key); /* borrowed */
8c28fd
+    Py_DECREF(key);
8c28fd
+    if (value == NULL) {
8c28fd
+        if (PyErr_Occurred()) {
8c28fd
+            return -1;
8c28fd
+        }
8c28fd
+        return 0;
8c28fd
+    }
8c28fd
+
8c28fd
+    if (!PyUnicode_Check(value)) {
8c28fd
+        return -1;
8c28fd
+    }
8c28fd
+
8c28fd
+    PyObject *valuelong = PyLong_FromUnicodeObject(value, 10);
8c28fd
+    if (valuelong == NULL) {
8c28fd
+        return -1;
8c28fd
+    }
8c28fd
+
8c28fd
+    int maxdigits = _PyLong_AsInt(valuelong);
8c28fd
+    Py_DECREF(valuelong);
8c28fd
+    if (maxdigits == -1 && PyErr_Occurred()) {
8c28fd
+        return -1;
8c28fd
+    }
8c28fd
+
8c28fd
+    *pmaxdigits = maxdigits;
8c28fd
+    return 1;
8c28fd
+}
8c28fd
+
8c28fd
+
8c28fd
+static void
8c28fd
+long_init_max_str_digits(void)
8c28fd
+{
8c28fd
+    // PYTHONINTMAXSTRDIGITS env var
8c28fd
+    char *opt = Py_GETENV("PYTHONINTMAXSTRDIGITS");
8c28fd
+    int maxdigits;
8c28fd
+    if (opt) {
8c28fd
+        int valid = 0;
8c28fd
+        if (!pymain_str_to_int(opt, &maxdigits)) {
8c28fd
+            valid = ((maxdigits == 0) || (maxdigits >= _PY_LONG_MAX_STR_DIGITS_THRESHOLD));
8c28fd
+        }
8c28fd
+        if (!valid) {
8c28fd
+#define STRINGIFY(VAL) _STRINGIFY(VAL)
8c28fd
+#define _STRINGIFY(VAL) #VAL
8c28fd
+            fprintf(stderr, "Error in PYTHONINTMAXSTRDIGITS: "
8c28fd
+                    "invalid limit; must be >= "
8c28fd
+                    STRINGIFY(_PY_LONG_MAX_STR_DIGITS_THRESHOLD)
8c28fd
+                    " or 0 for unlimited.\n");
8c28fd
+            exit(1);
8c28fd
+        }
8c28fd
+        _Py_global_config_int_max_str_digits = maxdigits;
8c28fd
+    }
8c28fd
+
8c28fd
+    // -X int_max_str_digits command line option
8c28fd
+    int res = long_get_max_str_digits_xoption(&maxdigits);
8c28fd
+    if (res == 1) {
8c28fd
+        int valid = ((maxdigits == 0) || (maxdigits >= _PY_LONG_MAX_STR_DIGITS_THRESHOLD));
8c28fd
+        if (!valid) {
8c28fd
+            res = -1;
8c28fd
+        }
8c28fd
+    }
8c28fd
+    if (res < 0) {
8c28fd
+        fprintf(stderr, "Error in -X int_max_str_digits: "
8c28fd
+                "invalid limit; must be >= "
8c28fd
+                STRINGIFY(_PY_LONG_MAX_STR_DIGITS_THRESHOLD)
8c28fd
+                " or 0 for unlimited.\n");
8c28fd
+        exit(1);
8c28fd
+    }
8c28fd
+    if (res == 1) {
8c28fd
+        _Py_global_config_int_max_str_digits = maxdigits;
8c28fd
+    }
8c28fd
+
8c28fd
+    // Default value
8c28fd
+    if (_Py_global_config_int_max_str_digits == -1) {
8c28fd
+        _Py_global_config_int_max_str_digits = _PY_LONG_DEFAULT_MAX_STR_DIGITS;
8c28fd
+    }
8c28fd
+}
8c28fd
+
8c28fd
+
8c28fd
 int
8c28fd
 _PyLong_Init(void)
8c28fd
 {
8c28fd
@@ -5549,6 +5713,8 @@ _PyLong_Init(void)
8c28fd
             return 0;
8c28fd
     }
8c28fd
 
8c28fd
+    long_init_max_str_digits();
8c28fd
+
8c28fd
     return 1;
8c28fd
 }
8c28fd
 
8c28fd
diff --git a/Python/ast.c b/Python/ast.c
8c28fd
index 675063e..4b69d86 100644
8c28fd
--- a/Python/ast.c
8c28fd
+++ b/Python/ast.c
8c28fd
@@ -2149,8 +2149,32 @@ ast_for_atom(struct compiling *c, const node *n)
8c28fd
     }
8c28fd
     case NUMBER: {
8c28fd
         PyObject *pynum = parsenumber(c, STR(ch));
8c28fd
-        if (!pynum)
8c28fd
+        if (!pynum) {
8c28fd
+            PyThreadState *tstate = PyThreadState_GET();
8c28fd
+            // The only way a ValueError should happen in _this_ code is via
8c28fd
+            // PyLong_FromString hitting a length limit.
8c28fd
+            if (tstate->curexc_type == PyExc_ValueError &&
8c28fd
+                tstate->curexc_value != NULL) {
8c28fd
+                PyObject *type, *value, *tb;
8c28fd
+                // This acts as PyErr_Clear() as we're replacing curexc.
8c28fd
+                PyErr_Fetch(&type, &value, &tb);
8c28fd
+                Py_XDECREF(tb);
8c28fd
+                Py_DECREF(type);
8c28fd
+                PyObject *helpful_msg = PyUnicode_FromFormat(
8c28fd
+                    "%S - Consider hexadecimal for huge integer literals "
8c28fd
+                    "to avoid decimal conversion limits.",
8c28fd
+                    value);
8c28fd
+                if (helpful_msg) {
8c28fd
+                    const char* error_msg = PyUnicode_AsUTF8(helpful_msg);
8c28fd
+                    if (error_msg) {
8c28fd
+                        ast_error(c, ch, error_msg);
8c28fd
+                    }
8c28fd
+                    Py_DECREF(helpful_msg);
8c28fd
+                }
8c28fd
+                Py_DECREF(value);
8c28fd
+            }
8c28fd
             return NULL;
8c28fd
+        }
8c28fd
 
8c28fd
         if (PyArena_AddPyObject(c->c_arena, pynum) < 0) {
8c28fd
             Py_DECREF(pynum);
8c28fd
diff --git a/Python/pylifecycle.c b/Python/pylifecycle.c
8c28fd
index 0b985bf..095d1ef 100644
8c28fd
--- a/Python/pylifecycle.c
8c28fd
+++ b/Python/pylifecycle.c
8c28fd
@@ -97,6 +97,8 @@ int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
8c28fd
 int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
8c28fd
 int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
8c28fd
 #endif
8c28fd
+/* Unusual name compared to the above for backporting from 3.12 reasons. */
8c28fd
+int _Py_global_config_int_max_str_digits = -1; /* -X int_max_str_digits or PYTHONINTMAXSTRDIGITS */
8c28fd
 
8c28fd
 PyThreadState *_Py_Finalizing = NULL;
8c28fd
 
8c28fd
diff --git a/Python/sysmodule.c b/Python/sysmodule.c
8c28fd
index 7d1493c..ecdb62c 100644
8c28fd
--- a/Python/sysmodule.c
8c28fd
+++ b/Python/sysmodule.c
8c28fd
@@ -1079,6 +1079,46 @@ sys_mdebug(PyObject *self, PyObject *args)
8c28fd
 }
8c28fd
 #endif /* USE_MALLOPT */
8c28fd
 
8c28fd
+static PyObject *
8c28fd
+sys_get_int_max_str_digits(PyObject *module, PyObject *Py_UNUSED(ignored))
8c28fd
+{
8c28fd
+    return PyLong_FromSsize_t(_Py_global_config_int_max_str_digits);
8c28fd
+}
8c28fd
+
8c28fd
+PyDoc_STRVAR(sys_get_int_max_str_digits__doc__,
8c28fd
+"get_int_max_str_digits($module, /)\n"
8c28fd
+"--\n"
8c28fd
+"\n"
8c28fd
+"Set the maximum string digits limit for non-binary int<->str conversions.");
8c28fd
+
8c28fd
+static PyObject *
8c28fd
+sys_set_int_max_str_digits(PyObject *module, PyObject *args, PyObject *kwds)
8c28fd
+{
8c28fd
+    static char *kwlist[] = {"maxdigits", NULL};
8c28fd
+    int maxdigits;
8c28fd
+
8c28fd
+    if (!PyArg_ParseTupleAndKeywords(args, kwds, "i:set_int_max_str_digits",
8c28fd
+                                     kwlist, &maxdigits))
8c28fd
+        return NULL;
8c28fd
+
8c28fd
+    if ((!maxdigits) || (maxdigits >= _PY_LONG_MAX_STR_DIGITS_THRESHOLD)) {
8c28fd
+        _Py_global_config_int_max_str_digits = maxdigits;
8c28fd
+        Py_RETURN_NONE;
8c28fd
+    } else {
8c28fd
+        PyErr_Format(
8c28fd
+            PyExc_ValueError, "maxdigits must be 0 or larger than %d",
8c28fd
+            _PY_LONG_MAX_STR_DIGITS_THRESHOLD);
8c28fd
+        return NULL;
8c28fd
+    }
8c28fd
+}
8c28fd
+
8c28fd
+PyDoc_STRVAR(sys_set_int_max_str_digits__doc__,
8c28fd
+"set_int_max_str_digits($module, /, maxdigits)\n"
8c28fd
+"--\n"
8c28fd
+"\n"
8c28fd
+"Set the maximum string digits limit for non-binary int<->str conversions.");
8c28fd
+
8c28fd
+
8c28fd
 size_t
8c28fd
 _PySys_GetSizeOf(PyObject *o)
8c28fd
 {
8c28fd
@@ -1434,6 +1474,8 @@ static PyMethodDef sys_methods[] = {
8c28fd
      METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
8c28fd
     {"get_asyncgen_hooks", sys_get_asyncgen_hooks, METH_NOARGS,
8c28fd
      get_asyncgen_hooks_doc},
8c28fd
+    {"get_int_max_str_digits", sys_get_int_max_str_digits, METH_NOARGS, sys_get_int_max_str_digits__doc__},
8c28fd
+    {"set_int_max_str_digits", (PyCFunction)sys_set_int_max_str_digits, METH_VARARGS|METH_KEYWORDS, sys_set_int_max_str_digits__doc__},
8c28fd
     {NULL,              NULL}           /* sentinel */
8c28fd
 };
8c28fd
 
8c28fd
@@ -1681,6 +1723,7 @@ static PyStructSequence_Field flags_fields[] = {
8c28fd
     {"quiet",                   "-q"},
8c28fd
     {"hash_randomization",      "-R"},
8c28fd
     {"isolated",                "-I"},
8c28fd
+    {"int_max_str_digits",      "-X int_max_str_digits"},
8c28fd
     {0}
8c28fd
 };
8c28fd
 
8c28fd
@@ -1688,7 +1731,7 @@ static PyStructSequence_Desc flags_desc = {
8c28fd
     "sys.flags",        /* name */
8c28fd
     flags__doc__,       /* doc */
8c28fd
     flags_fields,       /* fields */
8c28fd
-    13
8c28fd
+    14
8c28fd
 };
8c28fd
 
8c28fd
 static PyObject*
8c28fd
@@ -1719,6 +1762,7 @@ make_flags(void)
8c28fd
     SetFlag(Py_QuietFlag);
8c28fd
     SetFlag(Py_HashRandomizationFlag);
8c28fd
     SetFlag(Py_IsolatedFlag);
8c28fd
+    SetFlag(_Py_global_config_int_max_str_digits);
8c28fd
 #undef SetFlag
8c28fd
 
8c28fd
     if (PyErr_Occurred()) {
8c28fd
-- 
8c28fd
2.37.3
8c28fd