Skip to content
Memory corruption Write-up Advanced

Python Objects

A use-after-free in CPython's BufferedReader allows a memoryview to reference freed memory, which can be exploited to achieve arbitrary code execution. The author demonstrates a reliable exploit that works on every Python 3 version on x86-64 Ubuntu, even with PIE, full RELRO, and CET enabled.

pwn.win

Published on pwn.win

A while ago I was browsing the Python bug tracker, and I stumbled upon this bug - “memoryview to freed memory can cause segfault”. It was created in 2012, originally present in Python 2.7, but remains open to this day, 10 years later.

The author, on pwn.win

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Not written yet. The AI write-up for this write-up has not been written yet. The Original tab links to the source.

How it worked

Impact

An attacker who can execute arbitrary Python code could bypass sandbox restrictions and achieve native code execution, but the exploit requires the ability to run Python code in the first place.

What the attacker needed

Ability to execute arbitrary Python code; x86-64 Ubuntu system

How it was found

  1. Create a custom RawIOBase subclass whose readinto method saves the provided buffer as a memoryview.
  2. Wrap an instance of this class in a BufferedReader and call read to obtain the memoryview.
  3. Delete the BufferedReader to free its internal buffer, leaving the memoryview dangling.
  4. Create a list of the same size as the freed buffer to reuse the freed memory.
  5. Use the memoryview to write fake PyObject pointers into the list's item buffer.
  6. Trigger code execution by accessing a fake object with a crafted type object.

Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.

Not written yet. The AI write-up for this write-up has not been written yet. The Original tab links to the source.

A use-after-free happens when a program keeps a pointer to memory after it has been freed, and that memory can be reused for something else. Here, a memoryview object still points to a buffer that was freed when the BufferedReader was deleted, so an attacker can write to that memory and trick Python into running arbitrary code.

What is Memory corruption?

Native code reads or writes memory it should not: overflows, use-after-free, type confusion. The core of browser, kernel and parser bugs.

Similar reports

View all

Same bug class and techniques, clearest first.

Memory corruption

The lesson behind this report.

Native code reads or writes memory it should not: overflows, use-after-free, type confusion. The core of browser, kernel and parser bugs.