Skip to content
Memory corruption Disclosed report Advanced

Integer overflow in strop.expandtabs

An integer overflow in the strop.expandtabs function allows a crafted string with many tabs and newlines to cause an undersized buffer allocation, leading to heap corruption. An attacker could potentially achieve native code execution by manipulating the heap and overwriting function pointers.

ianbeer Follow

Originally disclosed on HackerOne

  • Fixed in 9 days
  • Paid in 8 days
  • Disclosed after under an hour

This issue was originally disclosed directly to the Python Security Response Team

Here's a bug in a string handling function which might be reachable in some "sandboxed python" environments, and maybe (at a stretch) remotely if someone were to offer "expanding-tabs-in-strings"-as-a-service...

Bug:

Modules/stropmodule.c

static PyObject *
strop_expandtabs(PyObject *self, PyObject *args)
...
  i = j = old_j = 0;
  e = string + stringlen;
  for (p = string; p < e; p++) {
      if (*p == '\t') {
          j += tabsize - (j%tabsize);
          if (old_j > j) {
              PyErr_SetString(PyExc_OverflowError,
                              "new string is too long");
              return NULL;
          }
          old_j = j;
      } else {
          j++;
          if (*p == '\n') {
              i += j;               <-- missing check here
              j = 0;
          }
      }
  }
...
  out = PyString_FromStringAndSize(NULL, i+j);
...
  i = 0;
  q = PyString_AS_STRING(out);

  for (p = string; p < e; p++) {
      if (*p == '\t') {
          j = tabsize - (i%tabsize);
          i += j;
          while (j-- > 0)
              *q++ = ' ';
      } else {
          *q++ = *p;
          i++;
          if (*p == '\n')
              i = 0;
      }
  }
...

There's no check preventing i from overflowing, meaning that a string consisting of multiple tabs spread over multiple lines combined with a large tabsize can cause the allocation of an undersized string buffer.

With some simple heap manipulation the length of the copy into this buffer can be controlled, and it's pretty easy to corrupt memory in such a way as to gain native code execution:

[h1|----------][h2|\t\n\t\n....][h3|----------]

h1: PyStringObject header of undersized buffer h2: PyStringObject header of tabstring

By grooming the heap such that this allocation pattern is achieved when the expandtabs function starts expanding the h2 string into the h1 inline buffer it will overflow into the string being expanded, overwriting the tabs in the original string with spaces so that the second loop won't expand them anymore.

By carefully crafting the string to expand and choosing the tabsize you can limit the extent of the memory corruption to chosen objects.

Getting code execution is simply a matter of pointing the ob_type field of the h2 string header to a controlled address with a fake struct _typeobject. The struct contains the following function pointers which will be called when their corresponing python function is called:

destructor tp_dealloc; printfunc tp_print; getattrfunc tp_getattr; setattrfunc tp_setattr; cmpfunc tp_compare; reprfunc tp_repr;

Patch:

You've actually already patched this bug in a copy-and-paste version of this function... In fact there seem to be at least three versions of expandtabs; transmogrify.h and stropmodule.c are both vulnerable; stringobject.c isn't. I'm not familiar enough with the code to know when each version will be used.

The patch is to use the stringobject.c implementation which does the overflow check correctly, but here's a quick patch (for the 2.7 branch) which will do the job:

--- a/Modules/stropmodule.c Sun Mar 30 16:43:11 2014 -0400
+++ b/Modules/stropmodule.c Mon Mar 31 00:36:57 2014 +0200
@@ -624,6 +624,11 @@
         } else {
             j++;
             if (*p == '\n') {
+                if (i > PY_SSIZE_T_MAX - j){
+                    PyErr_SetString(PyExc_OverflowError,
+                                    "new string is too long");
+                    return NULL;
+                }
                 i += j;
                 j = 0;
             }

Proof of Concept

Run this script for a very simple crashing PoC for 32-bit python 2.7 which should crash at at address near 0x20202020 (since the ob_type field will be overwritten with spaces.) No idea if the heap manipulation used here will work on other platforms but it should be easy to do.

import strop

strs = []
for i in range(20):
  strs.append('\t\n' * 0x10000 + 'A' * 0x1000000)
for i in range(20):
  print hex(id(strs[i]))
strs[14] = None
strop.expandtabs(strs[15], 0x10001)
print strs[15]

The original report as published on HackerOne, by ianbeer. Images and videos are our own copies; raw HTML is shown as text. View it on HackerOne.

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

How it worked

Root cause

The code that accumulates the total length (variable i) lacks an overflow check when adding the length of a line (j) after a newline, so i can wrap around and cause an undersized allocation.

Impact

With heap grooming, an attacker could corrupt memory and potentially achieve native code execution; the report says this might be reachable in some sandboxed environments and maybe remotely at a stretch.

What the attacker needed

Ability to call strop.expandtabs with attacker-controlled…; 32-bit Python 2.7 (for the provided PoC)

The fix

The fix is to add an overflow check before adding j to i, similar to the existing check for tab expansion, or to use the stringobject.c implementation which already has the check.

How it was found

  1. Create a list of many large strings, each containing repeated tab-newline sequences followed by a long run of 'A' characters.
  2. Print the memory addresses of the strings to observe heap layout.
  3. Set one of the strings to None to free its memory, creating a hole.
  4. Call strop.expandtabs on a neighbouring string with a large tabsize value.
  5. Observe that the program crashes, indicating memory corruption.

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 report has not been written yet. The Original tab links to the source.

This is a bug in a Python function that expands tab characters into spaces. When given a very long string with many tabs and newlines, the function miscalculates how much memory it needs, so it writes more data than the buffer can hold. That can crash Python or, with careful setup, let an attacker run their own 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.

More from Internet Bug Bounty

View all

The newest disclosed reports for this program.

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.