antonin

Finding memory corruption bugs in Python C extensions

Writing a vulnerable module, then finding its bug with Atheris

When I published Frelatage a year ago, I was often told: “Why fuzz Python? There is nothing interesting to find in this language.” When people think of fuzzing, they think of memory corruption vulnerabilities, and often assume that only C/C++ codebases can have them. However, many Python libraries are partly written in C, mostly for performance reasons.

Here are some Python modules written at least partially in C, and therefore potentially vulnerable to memory corruption:

Table of contents:

  1. Creating a vulnerable demo module
  2. Finding the bug with a fuzzer
  3. Conclusion

Creating a vulnerable demo module

Let’s start by writing a vulnerable Python module in C. This minimal example contains a buffer_overflow_vulnerable method which, as its name suggests, is vulnerable to a buffer overflow. It does only one thing: copy an arbitrary input into a 667-byte buffer, which overflows if the input and its null terminator exceed 667 bytes.

#include <stdio.h>
#include <Python.h>

// A Method vulnerable to a buffer overflow.
static PyObject* buffer_overflow_vulnerable(PyObject *self, PyObject *args) {
    const char* input;
    if (!PyArg_ParseTuple(args, "s", &input)) {
        return NULL;
    }

    /*  /!\ Buffer overflow /!\ */
    char buffer[667] = {0};
    strcpy(buffer, input);

    Py_RETURN_NONE;
}

// Method definition object for this extension
static PyMethodDef mymodule_methods[] = { 
    {   
        "buffer_overflow_vulnerable", buffer_overflow_vulnerable, METH_VARARGS,
        "Method vulnerable to a buffer overflow."
    },  
    {NULL, NULL, 0, NULL}
};

// Module definition
static struct PyModuleDef mymodule_definition = { 
    PyModuleDef_HEAD_INIT,
    "mymodule",
    "A Python module vulnerable to a buffer overflow, for demonstration purposes.",
    -1, 
    mymodule_methods
};

// Module initialization
PyMODINIT_FUNC PyInit_mymodule(void) {
    Py_Initialize();
    return PyModule_Create(&mymodule_definition);
}

Then we create a setup.py file, which lets us use this C method from a Python module:

#!/usr/bin/env python3
# encoding: utf-8

from setuptools import setup, Extension

mymodule = Extension('mymodule', sources = ['mymodule.c'])

setup(name='mymodule',
      version='0.1.0',
      description='A Python module vulnerable to a buffer overflow, for demonstration purposes.',
      ext_modules=[mymodule])

Now it’s time to build our module:

pip3 install .

We test it in a Python interpreter, and it works very well:

>>> import mymodule
>>> mymodule.buffer_overflow_vulnerable("a")

Now comes the time to find this bug with a fuzzer.

Finding the bug with a fuzzer

Fuzzing is one of the easiest ways to find this kind of vulnerability. There are several fuzzers for Python; here I chose to write the harness with Atheris:

#!/usr/bin/env python3

import atheris

with atheris.instrument_imports():
    import mymodule 
    import sys

def fuzz_mymodule(input_bytes):
    fdp = atheris.FuzzedDataProvider(input_bytes)
    data = fdp.ConsumeString(sys.maxsize)

    try:
        mymodule.buffer_overflow_vulnerable(data)
    except:
        return

atheris.Setup(sys.argv, fuzz_mymodule)
atheris.Fuzz()

Note that Atheris only instruments Python code here: the C extension is built without coverage instrumentation, so the fuzzer finds this bug by luck rather than guidance. For real targets, build the extension with Clang and -fsanitize=fuzzer-no-link,address, as described in the Atheris documentation.

I launch the fuzzer and, after a few very long seconds (3), a crash occurs:

*** buffer overflow detected ***: terminated
==6746== ERROR: libFuzzer: deadly signal
NOTE: libFuzzer has rudimentary signal handlers.
      Combine libFuzzer with AddressSanitizer or similar for better crash reports.
SUMMARY: libFuzzer: deadly signal
MS: 4 InsertRepeatedBytes-InsertRepeatedBytes-CopyPart-CopyPart-; base unit: adc83b19e793491b1c6ea0fd8b46cd9f32e592fc
artifact_prefix='./'; Test unit written to ./crash-854298749b437ea327679792bf9cc9addf5876e6

The input that crashed the method is 830 bytes long, more than the 667 bytes of our buffer:

$ ~ wc ./crash-854298749b437ea327679792bf9cc9addf5876e6
1   0 830 ./crash-854298749b437ea327679792bf9cc9addf5876e6

Conclusion

So we have proof that memory corruption vulnerabilities are not exclusive to C and C++ programs: they also affect Python, through its native extensions.

Here are a few memory corruption vulnerabilities found in Python and its libraries:

Now you know what to fuzz to find vulnerabilities on still little-explored ground. Happy vulnerability hunting!