python / python/cpython

vars's mapping proxy can expose internal dictionary even for built-in types

Open
#152,405 18 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

interpreter-core type-crash
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Bug report

Bug description:

By creating a type or class with a definition of __eq__ that simply returns the other object, it is possible to access the underlying dictionary behind the mapping proxy returned by vars.

This can be (ab)used to bypass mutability restrictions on built-in types, as the example below shows:

class Evil:
    def __eq__(self, other):
        return other

# less readable version of Evil:
# type("Evil", (), {"__eq__": lambda self, other: other})

# this statement adds a method `prepend` to the built-in type `list`
# 1. vars(list) == Evil() returns the underlying dictionary of `list`
# 2. we can then use the dict[name] = value statement to set the attribute `name`
(vars(list) == Evil())["prepend"] = lambda self, value: self.insert(0, value)

x = [3, 5, 2]
x.prepend(7)

print(x)  # [7, 3, 5, 2]

This can be used to cause a segmentation fault:

# reusing Evil from earlier
(vars(type) == Evil())["__instancecheck__"] = lambda *_: False
# fish: Job 1, 'python' terminated by signal SIGSEGV

No FFI, not a single line of C code required.

This also works on CPython 2.7 and 3.9. It might even be possible to do on even earlier versions.

Disclaimer
I have independently discovered this by myself (no LLM).

CPython versions tested on:

3.14, 3.12, 3.11

Operating systems tested on:

Linux

Linked PRs
  • gh-152449
  • gh-152483
  • gh-152489
  • gh-153670

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 reproducing the vars(list) == Evil() and vars(type) == Evil() examples on the listed CPython versions. Review linked PRs gh-152449, gh-152483, gh-152489, and gh-153670 to understand the proposed fix and its validation; done means the mapping proxy no longer exposes a mutable internal dictionary or permits the demonstrated crash.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
security
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
20/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.