python / python/cpython

itertools.count use-after-free via re-entrant step.__radd__

Open
#154,670 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

extension-modules type-crash
Dominant language
Python
Stars
77.2k
Forks
36k
PR merge metrics
PR metrics pending

Description

Bug description

itertools.count has a use-after-free when the step object's __radd__ re-enters the iterator.

count_nextlong() borrows lz->long_cnt (the running total) without Py_INCREF, then calls PyNumber_Add(result, step). If step.__radd__ calls next() on the same count, the inner call moves lz->long_cnt to the new value and hands the old total's only reference back, which is then dropped and freed. The outer call still returns that freed total as a dangling pointer.

The step needs __index__ so count() accepts it as a number, and the returned value has to be used to hit the freed memory:

from itertools import count

class Step:
    armed = True
    def __index__(self):        # so count() accepts it as a number
        return 1
    def __radd__(self, other):
        if Step.armed:
            Step.armed = False
            inner = next(c)     # re-enter; steals the running total's ref
            f"{inner!r}"        # churn the heap so the freed slot is reused
        return other + 1

c = count(1 << 100, Step())
val = next(c)
val + 1                         # use the returned (dangling) total

Run with PYTHONMALLOC=debug python repro.py -> SIGSEGV. With the fix it prints the correct value.

CPython versions tested on

main

Operating systems tested on

macOS

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by tracing the count_nextlong() path described in the report and run the supplied reproducer with PYTHONMALLOC=debug. Investigate the re-entrant next() call and reference lifetime around the running total; the work is done when the reproducer prints the correct value without a crash.

Written by the indexing model from the issue text.

Assessment

Tech stack
c, python
Domain
backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
52/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.