Type confusion in FutureIter_throw() which may potentially lead to an arbitrary code execution
The FutureIter_throw() method in Python's asyncio module did not validate the types of its arguments before passing them to PyErr_Restore(), which also lacked type checks. This allowed an attacker to store arbitrary objects as exception values, leading to type confusion that could cause a crash or potentially arbitrary code execution.
- Fixed in 19 days
- Paid in 19 days
- Disclosed after 19 days
Hello,
I reported this directly to [email protected]. The issue has been fixed. Python Team confirmed that it's fixed and disclosed:
It's disclosed. Feel free to file a bug if that would be helpful to you.
On Mon, Nov 14, 2016, at 09:54, Artem Smotrakov wrote:
Hello Benjamin,
I am planning to submit it to https://hackerone.com/ibb-python to see if it's eligible. Since the fix is in public repo, may it be considered as disclosed? Or, should I wait for next release?
Is there a bug id for it?
Thanks for fixing this quickly!
Artem
2016-11-14 0:17 GMT-08:00 Benjamin Peterson [email protected]:
Thank you for the report. Fixed in https://hg.python.org/cpython/rev/3ea121235ede
Here is the original report:
Hello Python Security Team,
A type confusion may occur in FutureIter_throw() method of _asynciomodule:
https://hg.python.org/cpython/file/tip/Modules/_asynciomodule.c#l1022
static PyObject *
FutureIter_throw(futureiterobject *self, PyObject *args)
{
PyObject *type=NULL, *val=NULL, *tb=NULL;
if (!PyArg_ParseTuple(args, "O|OO", &type, &val, &tb))
return NULL;
if (val == Py_None) {
val = NULL;
}
if (tb == Py_None) {
tb = NULL;
}
Py_CLEAR(self->future);
if (tb != NULL) {
PyErr_Restore(type, val, tb);
}
The method doesn't check types of "type" and "val", and passes them to PyErr_Restore().
PyErr_Restore() method doesn't perform any type check on "type" and "val" either, and stores them "as is" to "tstate->curexc_type" and "tstate->curexc_value".
https://hg.python.org/cpython/file/tip/Python/errors.c#l27
Then, "tstate->curexc_value" can be retrieved by PyErr_Fetch() funciton, and callers will assume that it returns an object of exception type. This results to a type confusion.
There are a lot of invocation of PyErr_Fetch() which may lead to different consequences. I am attaching two POCs which demonstrates the problem.
- FutureIter_type_confusion_1.py results to a crash with the following output:
in A.__init__
in A.__str__
in except, e = this is not an exception
in except, type(e) = <class 'Exception'>
Traceback (most recent call last):
File "./FutureIter_type_confusion_report/FutureIter_type_confusion_1.py", line 13, in <module>
Segmentation fault (core dumped)
- FutureIter_type_confusion_2.py shows that the issue may lead to overwritting function pointers
which may potentially result to an arbitrary code execution:
(gdb) run
Starting program: /home/artem/projects/python/build/cpython-normal/bin/python3 ./FutureIter_type_confusion_report/FutureIter_type_confusion_2.py
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Program received signal SIGSEGV, Segmentation fault.
0x00000000004b751a in PyObject_Repr (v=0xae1890) at Objects/object.c:474
474 if (Py_TYPE(v)->tp_repr == NULL)
(gdb) p v->ob_type->tp_repr
Cannot access memory at address 0x50607020304050c8
(gdb) list
469 return NULL;
470 }
471 #endif
472 if (v == NULL)
473 return PyUnicode_FromString("<NULL>");
474 if (Py_TYPE(v)->tp_repr == NULL)
475 return PyUnicode_FromFormat("<%s object at %p>",
476 v->ob_type->tp_name, v);
477
478 #ifdef Py_DEBUG
479 /* PyObject_Repr() must not be called with an exception set,
480 because it may clear it (directly or indirectly) and so the
481 caller loses its exception */
482 assert(!PyErr_Occurred());
483 #endif
484
485 res = (*v->ob_type->tp_repr)(v);
486 if (res == NULL)
487 return NULL;
488 if (!PyUnicode_Check(res)) {
(gdb)
"v->ob_type->tp_repr" contains an invalid address 0x50607020304050c8, so it results to a crash. But this address is controlled by an attacker. "v->ob_type->tp_repr" is called later in line 485, so if it had a valid pointer, then it may potentially lead to full control of instruction pointer.
FutureIter_throw() accepts any types, and confused "tstate->curexc_value" may be used in lots of places, so there may be much more many ways to use this problem.
I am also attaching an untested patch which updates FutureIter_throw() function to check types of its parameters. The patch seems to solve the problem. I am wondering if such a check might be added to PyErr_Restore() to prevent similar issues.
Context
CPython's _asynciomodule implements the iterator object that wraps a future, so that await on a future can be driven by the event loop. One of the methods on that iterator is FutureIter_throw(), which is what runs when an exception is thrown into a suspended coroutine or future iterator. It receives the exception type, value and traceback as Python objects, clears the stored future, and then hands the three objects to PyErr_Restore() so that the exception is raised at the point where the coroutine resumes.
The report concerns a type confusion in that handover: FutureIter_throw() accepts objects of any type for the exception type and value, and PyErr_Restore() stores them without checking them. The report was disclosed on 3 December 2016.
Setup
The researcher reported the issue directly to [redacted] before submitting it to the HackerOne Internet Bug Bounty programme. The proof of concept scripts are referenced by the paths shown in the output below. The second proof of concept was analysed under gdb. No special account, role or network position is involved: the precondition is simply the ability to run Python code that throws into a future iterator.
Finding it
The starting point is the implementation of FutureIter_throw() at the linked revision of Modules/_asynciomodule.c:
static PyObject *
FutureIter_throw(futureiterobject *self, PyObject *args)
{
PyObject *type=NULL, *val=NULL, *tb=NULL;
if (!PyArg_ParseTuple(args, "O|OO", &type, &val, &tb))
return NULL;
if (val == Py_None) {
val = NULL;
}
if (tb == Py_None) {
tb = NULL;
}
Py_CLEAR(self->future);
if (tb != NULL) {
PyErr_Restore(type, val, tb);
}
The format string "O|OO" accepts any object for type, val and tb; nothing checks that type is an exception class or that val is an exception instance. The only normalisation is that None for val and tb is turned into NULL.
The researcher then looked at the other end, PyErr_Restore() in Python/errors.c. That function performs no type check on type and val either, and stores them as they are into tstate->curexc_type and tstate->curexc_value. The consequence is that a later PyErr_Fetch() returns whatever object was passed in, and its callers assume they are dealing with an object of exception type. That mismatch between what is stored and what consumers expect is the type confusion.
The report notes that there are many invocations of PyErr_Fetch() in the interpreter, so the confused value can surface in many different places with different consequences. Two proof of concept scripts were attached to demonstrate this.
Exploitation
Step 1: crash through a confused exception value
The first script, FutureIter_type_confusion_1.py, produces the following output:
in A.__init__
in A.__str__
in except, e = this is not an exception
in except, type(e) = <class 'Exception'>
Traceback (most recent call last):
File "./FutureIter_type_confusion_report/FutureIter_type_confusion_1.py", line 13, in <module>
Segmentation fault (core dumped)
The output shows the object's __init__ and __str__ being invoked, and then an except block receiving a value that prints as this is not an exception while type(e) reports <class 'Exception'>. The interpreter then dies with a segmentation fault at line 13 of the script. This is the minimal demonstration that the object stored as the exception value is not an exception, and that code downstream treats it as one.
Step 2: attacker-controlled function pointer
The second script, FutureIter_type_confusion_2.py, was run under gdb:
(gdb) run
Starting program: /home/artem/projects/python/build/cpython-normal/bin/python3 ./FutureIter_type_confusion_report/FutureIter_type_confusion_2.py
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Program received signal SIGSEGV, Segmentation fault.
0x00000000004b751a in PyObject_Repr (v=0xae1890) at Objects/object.c:474
474 if (Py_TYPE(v)->tp_repr == NULL)
(gdb) p v->ob_type->tp_repr
Cannot access memory at address 0x50607020304050c8
(gdb) list
469 return NULL;
470 }
471 #endif
472 if (v == NULL)
473 return PyUnicode_FromString("<NULL>");
474 if (Py_TYPE(v)->tp_repr == NULL)
475 return PyUnicode_FromFormat("<%s object at %p>",
476 v->ob_type->tp_name, v);
477
478 #ifdef Py_DEBUG
479 /* PyObject_Repr() must not be called with an exception set,
480 because it may clear it (directly or indirectly) and so the
481 caller loses its exception */
482 assert(!PyErr_Occurred());
483 #endif
484
485 res = (*v->ob_type->tp_repr)(v);
486 if (res == NULL)
487 return NULL;
488 if (!PyUnicode_Check(res)) {
(gdb)
The crash happens in PyObject_Repr() at Objects/object.c:474, where the type of the object is dereferenced. Inspecting v->ob_type->tp_repr shows the invalid address 0x50607020304050c8, which is why the dereference faults. The researcher points out that this address is controlled by an attacker. The call through the function pointer happens later, at line 485, res = (*v->ob_type->tp_repr)(v);, so if the address were a valid pointer, the attacker would gain control of the instruction pointer, which may potentially lead to arbitrary code execution.
Step 3: scope of the problem
Because FutureIter_throw() accepts any types and the confused tstate->curexc_value can be consumed in many places, the researcher notes that there may be many more ways to use the problem than the two scripts show.
Root cause
The mistake is a missing type check at the boundary between the asyncio iterator and the exception machinery. FutureIter_throw() parses its arguments with "O|OO", which accepts arbitrary objects, and forwards them to PyErr_Restore(). PyErr_Restore() in turn stores type and val into the thread state without validating them, on the assumption that its callers have already done so. When PyErr_Fetch() later retrieves the value, callers assume it is an exception object and use it accordingly, for example by taking its type and calling through tp_repr. The existing defences did not stop this because neither function in the chain performs the check; the report suggests that a check in PyErr_Restore() itself might be worth considering to prevent similar issues elsewhere.
Impact
The first proof of concept shows a denial of service: a segmentation fault in the interpreter. The second shows that the confused object's type pointer is attacker-controlled, and that a function pointer taken from it is called, so under the right conditions this may potentially lead to arbitrary code execution. The report hedges this appropriately: the demonstrated outcome is a crash, and code execution is described as potential, conditional on the attacker being able to place a valid pointer at the controlled address.
Fix
The issue was fixed in CPython revision 3ea121235ede (https://hg.python.org/cpython/rev/3ea121235ede), as confirmed by Benjamin Peterson in the correspondence quoted in the report. The researcher also attached an untested patch that updates FutureIter_throw() to check the types of its parameters; the report says the patch seems to solve the problem, and asks whether such a check might also be added to PyErr_Restore() to prevent similar issues. The report does not include the contents of either change.
Variants to test
- Other C functions that parse arguments with a permissive format such as
"O"and forward the result into exception state, for example anything that ends up inPyErr_Restore()orPyErr_SetObject(). A positive result is an object of a non-exception type being retrieved byPyErr_Fetch()and then dereferenced as an exception. - Other consumers of
PyErr_Fetch()that assume the fetched value is an exception instance, particularly those that call methods or read fields through the object's type. A positive result is a crash whose faulting address matches bytes you control in the confused object. - Other iterator or generator protocol methods that accept exception triples from Python code, checking whether they validate the type and value before storing them. A positive result is the same mismatch between the printed value and
type(e)seen in the first proof of concept.
Hunting notes
This kind of bug hides at the boundary between a Python-level API that accepts arbitrary objects and C code that assumes a narrower type, especially where exception state is stored and later fetched. The signal during review is a permissive argument format string followed by a call into the exception machinery without validation. The researcher showed impact in two stages: a crash with a traceback, and a gdb session showing the faulting pointer is attacker-controlled and would be called if valid. That combination, a deterministic crash plus evidence of control over the pointer, is what makes the potential for code execution credible enough to report.
Disclosure timeline
The issue was reported privately to [redacted] and fixed in the public repository. The researcher then asked whether, given that the fix was already public, the issue could be considered disclosed for the purposes of submitting it to the HackerOne Internet Bug Bounty programme, and the Python team confirmed that it was disclosed and that filing a bug would be fine. The report was disclosed on HackerOne on 3 December 2016.
What happened, in plain words
Python has a feature called asyncio that lets a program do several things at once without waiting for each one to finish. Under the hood, asyncio uses a small C object called a future iterator, and one of its methods is FutureIter_throw(). That method is used when an error is thrown into a piece of code that is paused and waiting to resume. The method is supposed to receive an exception type, an exception value and a traceback, and then hand them to another C function, PyErr_Restore(), so that the error is raised when the paused code resumes.
The problem is that FutureIter_throw() does not check what kind of objects it receives. It accepts anything, and PyErr_Restore() stores those objects without checking them either. Later, other parts of Python fetch the stored value and assume it is a real exception. When it is not, the program can crash, and in some conditions an attacker might be able to control where the program jumps next, which could potentially lead to arbitrary code execution.
The researcher reported this privately to the Python security team, the issue was fixed, and the report was later disclosed on the Internet Bug Bounty programme on HackerOne on 3 December 2016.
Background: what you need to know
Before walking through the report, here are the ideas it relies on, explained from scratch.
- Python: a programming language. You write instructions in a text file and a program called the interpreter runs them. CPython is the standard interpreter, written mostly in the C language.
- C: a lower-level programming language used to build things like interpreters and operating systems. C code works with raw memory addresses, which is why mistakes in C can crash a program or let an attacker take control of it.
- asyncio: a part of Python that lets a program wait for slow things (like a network reply) without freezing everything else. It schedules many small tasks and switches between them.
- Future: an asyncio object that represents a result that is not ready yet. You can think of it as a receipt you hold while waiting for a parcel: the parcel is not here, but the receipt lets you collect it later.
- Iterator: an object that produces a sequence of values one at a time. A future iterator is the object asyncio uses to step through a future.
- Exception: Python's way of signalling that something went wrong. An exception has a type (for example
Exception), a value (the specific error object) and a traceback (the record of where the error happened). - Type confusion: a class of bug where a program stores an object of one kind but later treats it as another kind. Imagine a form that asks for a date but accepts a phone number, and then a clerk tries to read the phone number as a date. The result is nonsense, and in C it can be dangerous because the program may follow a pointer that does not point where it expects.
- Pointer: a number that is a memory address. In C, a pointer tells the program where in memory an object lives. If an attacker can control a pointer, they may be able to make the program read or jump to a place of their choosing.
- Function pointer: a pointer that points to code rather than data. When the program calls a function through a function pointer, it jumps to whatever address is stored there. If an attacker controls that address, they may control where the program jumps.
- Segmentation fault: the operating system's way of stopping a program that tried to access memory it is not allowed to touch. It is a crash.
- gdb: a debugger, a tool that lets you pause a running program, inspect its memory and step through its code. Security researchers use it to see exactly why a crash happened.
- Proof of concept (PoC): a small script or set of steps that demonstrates a bug without causing harm beyond the demonstration.
- Patch: a change to the source code that fixes a bug.
- Revision: a specific saved version of a source code repository. The report refers to revision
3ea121235edeas the fix. - HackerOne: a platform where security researchers report bugs to companies and organisations. The Internet Bug Bounty is a programme on HackerOne that covers widely used open-source software, including Python.
The setup
The report links to the development version of CPython, called tip, which is the latest code in the repository. The issue was first reported directly to the Python security team at [redacted], and later submitted to the HackerOne Internet Bug Bounty programme. The proof of concept scripts are referenced by the paths shown in the output below. The second proof of concept was analysed under gdb. No special account, role or network position is needed: the only precondition is the ability to run Python code that throws into a future iterator.
Finding the bug
The starting point is the implementation of FutureIter_throw() in the file Modules/_asynciomodule.c. The report links to a specific line in the repository, and shows this code:
static PyObject *
FutureIter_throw(futureiterobject *self, PyObject *args)
{
PyObject *type=NULL, *val=NULL, *tb=NULL;
if (!PyArg_ParseTuple(args, "O|OO", &type, &val, &tb))
return NULL;
if (val == Py_None) {
val = NULL;
}
if (tb == Py_None) {
tb = NULL;
}
Py_CLEAR(self->future);
if (tb != NULL) {
PyErr_Restore(type, val, tb);
}
Line by line, in plain words:
static PyObject *andFutureIter_throw(futureiterobject *self, PyObject *args)declare a C function namedFutureIter_throw. It receives a pointer to the future iterator object (self) and a tuple of arguments (args), and it returns a Python object.PyObject *type=NULL, *val=NULL, *tb=NULL;creates three pointers for the exception type, value and traceback, all initially empty.if (!PyArg_ParseTuple(args, "O|OO", &type, &val, &tb)) return NULL;reads the arguments. The format string"O|OO"means: one required object, then up to two optional objects. The letterOaccepts any Python object at all. Nothing here checks thattypeis an exception class or thatvalis an exception instance.- The two
ifblocks turn a PythonNonevalue forvalandtbinto a CNULL, which means "nothing". Py_CLEAR(self->future);clears the stored future from the iterator.if (tb != NULL) { PyErr_Restore(type, val, tb); }hands the three objects toPyErr_Restore()if a traceback was supplied.
The researcher then looked at the other end, PyErr_Restore() in Python/errors.c. That function performs no type check on type and val either, and stores them as they are into tstate->curexc_type and tstate->curexc_value. In plain words, tstate is the thread state, a per-thread record the interpreter keeps, and curexc_type and curexc_value are the slots where the current exception's type and value are kept. Storing arbitrary objects there means that a later PyErr_Fetch(), which reads those slots back, returns whatever object was passed in. The callers of PyErr_Fetch() assume they are dealing with an object of exception type. That mismatch between what is stored and what consumers expect is the type confusion.
The report notes that there are many invocations of PyErr_Fetch() in the interpreter, so the confused value can surface in many different places with different consequences. Two proof of concept scripts were attached to demonstrate this.
Exploitation
Step 1: crash through a confused exception value
The first script, FutureIter_type_confusion_1.py, produces the following output:
in A.__init__
in A.__str__
in except, e = this is not an exception
in except, type(e) = <class 'Exception'>
Traceback (most recent call last):
File "./FutureIter_type_confusion_report/FutureIter_type_confusion_1.py", line 13, in <module>
Segmentation fault (core dumped)
What this output shows, line by line:
in A.__init__means the constructor of a class namedAwas called. In Python,__init__is the method that runs when an object is created.in A.__str__means the text representation method of that object was called.__str__is what Python uses when you print an object or turn it into a string.in except, e = this is not an exceptionmeans anexceptblock caught something and assigned it to the variablee, and printingeproduced the textthis is not an exception. So the value is not a normal exception message.in except, type(e) = <class 'Exception'>means that when the code asked Python what typeeis, Python answered that it is the built-inExceptionclass. This is the confusion: the value behaves like a custom object, but its type is reported as an exception.- The traceback points to line 13 of the script, and then the interpreter dies with
Segmentation fault (core dumped). A segmentation fault is a crash caused by accessing memory the program is not allowed to access.
This is the minimal demonstration that the object stored as the exception value is not an exception, and that code downstream treats it as one. The step was taken to show that the mismatch is real and has a visible, repeatable effect: a crash.
Step 2: attacker-controlled function pointer
The second script, FutureIter_type_confusion_2.py, was run under gdb:
(gdb) run
Starting program: /home/artem/projects/python/build/cpython-normal/bin/python3 ./FutureIter_type_confusion_report/FutureIter_type_confusion_2.py
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Program received signal SIGSEGV, Segmentation fault.
0x00000000004b751a in PyObject_Repr (v=0xae1890) at Objects/object.c:474
474 if (Py_TYPE(v)->tp_repr == NULL)
(gdb) p v->ob_type->tp_repr
Cannot access memory at address 0x50607020304050c8
(gdb) list
469 return NULL;
470 }
471 #endif
472 if (v == NULL)
473 return PyUnicode_FromString("<NULL>");
474 if (Py_TYPE(v)->tp_repr == NULL)
475 return PyUnicode_FromFormat("<%s object at %p>",
476 v->ob_type->tp_name, v);
477
478 #ifdef Py_DEBUG
479 /* PyObject_Repr() must not be called with an exception set,
480 because it may clear it (directly or indirectly) and so the
481 caller loses its exception */
482 assert(!PyErr_Occurred());
483 #endif
484
485 res = (*v->ob_type->tp_repr)(v);
486 if (res == NULL)
487 return NULL;
488 if (!PyUnicode_Check(res)) {
(gdb)
What each part means:
(gdb) runstarts the program inside the debugger.Starting program: ...shows the exact interpreter binary and script being run. The path is the researcher's local build.[Thread debugging using libthread_db enabled]and the library line are gdb telling you it has loaded support for debugging threads. They are not part of the bug.Program received signal SIGSEGV, Segmentation fault.means the program crashed with a segmentation fault.0x00000000004b751a in PyObject_Repr (v=0xae1890) at Objects/object.c:474tells you the crash happened inside a function calledPyObject_Repr, which is the C function that produces the text representation of an object. The object being represented is at memory address0xae1890, and the crash is at line 474 of the fileObjects/object.c.474 if (Py_TYPE(v)->tp_repr == NULL)is the source line.Py_TYPE(v)reads the type of the object, and->tp_reprreads a field of that type, which is a function pointer used to turn the object into text. The program is checking whether that function pointer is empty.(gdb) p v->ob_type->tp_reprasks gdb to print the value of that function pointer. The answer isCannot access memory at address 0x50607020304050c8, meaning the pointer contains an address that cannot be read. That is why the check itself crashed.(gdb) listshows the surrounding source code, lines 469 to 488, so you can see the context.- Lines 469 to 473 handle the case where the object pointer is empty, returning the string
<NULL>. - Line 474 is the check that crashed.
- Lines 475 and 476 build a fallback text representation using the type's name and the object's address.
- Lines 478 to 483 are a debug-only assertion explaining that
PyObject_Repr()must not be called while an exception is set, because it may clear it and the caller would lose it. - Line 485,
res = (*v->ob_type->tp_repr)(v);, is where the function pointer is actually called. This is the dangerous line: if the pointer were valid, the program would jump to whatever code lives at that address. - Lines 486 to 488 check whether the call returned nothing and whether the result is a Unicode string.
The crash happens in PyObject_Repr() at Objects/object.c:474, where the type of the object is dereferenced. Inspecting v->ob_type->tp_repr shows the invalid address 0x50607020304050c8, which is why the dereference faults. The researcher points out that this address is controlled by an attacker. The call through the function pointer happens later, at line 485, res = (*v->ob_type->tp_repr)(v);, so if the address were a valid pointer, the attacker would gain control of the instruction pointer, which may potentially lead to arbitrary code execution. In plain words, the program would jump to code chosen by the attacker instead of the code it intended to run.
This step was taken to show that the crash is caused by a value the attacker can influence, and that the same value would be used as a function pointer if it were valid. That is what makes the potential for code execution credible.
Step 3: scope of the problem
Because FutureIter_throw() accepts any types and the confused tstate->curexc_value can be consumed in many places, the researcher notes that there may be many more ways to use the problem than the two scripts show. In other words, the two scripts are examples, not a complete list.
Root cause
The mistake is a missing type check at the boundary between the asyncio iterator and the exception machinery. FutureIter_throw() parses its arguments with "O|OO", which accepts arbitrary objects, and forwards them to PyErr_Restore(). PyErr_Restore() in turn stores type and val into the thread state without validating them, on the assumption that its callers have already done so. When PyErr_Fetch() later retrieves the value, callers assume it is an exception object and use it accordingly, for example by taking its type and calling through tp_repr. The existing defences did not stop this because neither function in the chain performs the check. The report suggests that a check in PyErr_Restore() itself might be worth considering to prevent similar issues elsewhere.
Impact
The first proof of concept shows a denial of service: a segmentation fault in the interpreter. Denial of service means the program stops working, which can take down whatever service depends on it. The second shows that the confused object's type pointer is attacker-controlled, and that a function pointer taken from it is called, so under the right conditions this may potentially lead to arbitrary code execution. The report hedges this appropriately: the demonstrated outcome is a crash, and code execution is described as potential, conditional on the attacker being able to place a valid pointer at the controlled address.
Fix
The issue was fixed in CPython revision 3ea121235ede (https://hg.python.org/cpython/rev/3ea121235ede), as confirmed by Benjamin Peterson in the correspondence quoted in the report. The researcher also attached an untested patch that updates FutureIter_throw() to check the types of its parameters. The report says the patch seems to solve the problem, and asks whether such a check might also be added to PyErr_Restore() to prevent similar issues. The report does not include the contents of either change.
Variants to test
If you were looking for similar bugs, these are the directions the report points to:
- Other C functions that parse arguments with a permissive format such as
"O"and forward the result into exception state, for example anything that ends up inPyErr_Restore()orPyErr_SetObject(). A positive result is an object of a non-exception type being retrieved byPyErr_Fetch()and then dereferenced as an exception. - Other consumers of
PyErr_Fetch()that assume the fetched value is an exception instance, particularly those that call methods or read fields through the object's type. A positive result is a crash whose faulting address matches bytes you control in the confused object. - Other iterator or generator protocol methods that accept exception triples from Python code, checking whether they validate the type and value before storing them. A positive result is the same mismatch between the printed value and
type(e)seen in the first proof of concept.
Hunting notes
This kind of bug hides at the boundary between a Python-level API that accepts arbitrary objects and C code that assumes a narrower type, especially where exception state is stored and later fetched. The signal during review is a permissive argument format string followed by a call into the exception machinery without validation. The researcher showed impact in two stages: a crash with a traceback, and a gdb session showing the faulting pointer is attacker-controlled and would be called if valid. That combination, a deterministic crash plus evidence of control over the pointer, is what makes the potential for code execution credible enough to report.
Disclosure timeline
The issue was reported privately to [redacted] and fixed in the public repository. The researcher then asked whether, given that the fix was already public, the issue could be considered disclosed for the purposes of submitting it to the HackerOne Internet Bug Bounty programme, and the Python team confirmed that it was disclosed and that filing a bug would be fine. The report was disclosed on HackerOne on 3 December 2016.
Glossary
- API: a defined way for one piece of software to talk to another, like a menu of allowed requests and responses.
- Arbitrary code execution: a situation where an attacker can make a program run code of their choosing, rather than only the code it was designed to run.
- asyncio: a Python library for running many tasks concurrently without blocking on slow operations.
- Bounty: a payment made by a programme to a researcher who reports a valid security issue.
- C: a low-level programming language used to build interpreters and operating systems, where the programmer manages memory directly.
- CPython: the standard Python interpreter, written mostly in C.
- Denial of service: an attack or bug that makes a program or service stop working for legitimate users.
- Exception: Python's way of signalling an error, carrying a type, a value and a traceback.
- Function pointer: a pointer that stores the address of code to be called later.
- Future: an asyncio object representing a result that will be available later.
- gdb: the GNU debugger, a tool for pausing a program and inspecting its memory and execution.
- HackerOne: a platform for reporting and managing security vulnerabilities.
- Internet Bug Bounty: a HackerOne programme that rewards reports about widely used open-source software.
- Iterator: an object that produces values one at a time.
- Patch: a change to source code that fixes a bug.
- Pointer: a value that is a memory address, telling the program where an object lives.
- Proof of concept (PoC): a small demonstration that a bug exists, without causing harm beyond the demonstration.
- PyErr_Fetch(): a C function in CPython that retrieves the current exception's type, value and traceback from the thread state.
- PyErr_Restore(): a C function in CPython that stores an exception's type, value and traceback into the thread state.
- Segmentation fault: a crash caused by accessing memory the program is not allowed to access.
- Thread state: a per-thread record the interpreter keeps, including the current exception.
- Traceback: the record of where an error happened in a program.
- Type confusion: a bug where an object of one kind is stored and later treated as another kind, leading to incorrect or unsafe behaviour.