Tags: python pwn gc 

Rating:

Although the vulnerability was very easy, it was difficult to find. There were a few reasons for this.

First, it required some knowledge about the Python-C-API.
Second, there was another working vulnerability that discouraged me to look for the easy one. (zero refcount double free) Later by other teams' writeups I realized that the intended one was by using zero refcount but during the CTF I thought it was the result of lazy coding and didn't consider it an intended vulnerability.

Simply the vulnerability is due to the misuse of type_handlers. Type_handler is a structure used to store the types within a collection. If an object is an int, the collection object stores it as a C Int instead of an object. If an int entry is misunderstood as a list or dictionary entry, we can access arbitrary, user controlled pointers which is an extremely powerful primitive. We use a bytearray object, because a bytearray object contains a pointer that stores its data. We forged a fake bytearray object to obtain arbitrary R/W.

I looked at the other teams' writeups and found out that they used Python GC's behavior. Initially I tried to use this but Python's heap made me crazy so I gave up and looked for other vulnerabilities to use.

Original writeup (https://github.com/ch0rse/CTF-writeups/tree/master/35c3).