0
0
mirror of https://github.com/python/cpython.git synced 2024-11-27 23:47:29 +01:00
cpython/Include/internal
Gregory P. Smith eace09e63e
[3.10] gh-95778: Correctly pre-check for int-to-str conversion (GH-96537) (#96563)
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>
(cherry picked from commit b126196838)

Co-authored-by: Mark Dickinson <dickinsm@gmail.com>
2022-09-04 09:54:56 -07:00
..
pycore_abstract.h
pycore_accu.h
pycore_asdl.h
pycore_ast_state.h
pycore_ast.h
pycore_atomic_funcs.h
pycore_atomic.h
pycore_bitutils.h
pycore_blocks_output_buffer.h
pycore_bytes_methods.h
pycore_call.h
pycore_ceval.h
pycore_code.h
pycore_compile.h
pycore_condvar.h
pycore_context.h
pycore_dtoa.h
pycore_fileutils.h
pycore_format.h
pycore_gc.h
pycore_getopt.h
pycore_gil.h
pycore_hamt.h
pycore_hashtable.h
pycore_import.h
pycore_initconfig.h [3.10] gh-95778: CVE-2020-10735: Prevent DoS by very large int() (#96501) 2022-09-02 09:51:49 -07:00
pycore_interp.h [3.10] gh-95778: CVE-2020-10735: Prevent DoS by very large int() (#96501) 2022-09-02 09:51:49 -07:00
pycore_list.h
pycore_long.h [3.10] gh-95778: Correctly pre-check for int-to-str conversion (GH-96537) (#96563) 2022-09-04 09:54:56 -07:00
pycore_moduleobject.h
pycore_object.h
pycore_parser.h
pycore_pathconfig.h
pycore_pyarena.h
pycore_pyerrors.h
pycore_pyhash.h
pycore_pylifecycle.h
pycore_pymem.h
pycore_pystate.h
pycore_runtime.h
pycore_structseq.h
pycore_symtable.h
pycore_sysmodule.h
pycore_traceback.h
pycore_tuple.h
pycore_ucnhash.h
pycore_unionobject.h
pycore_warnings.h