# Unsafe arithmetic in PyString_DecodeEscape

Integer overflow in Python 2.7 PyString_DecodeEscape's 4*len allocation lets a ~1GB source file with non-UTF8 coding declaration overflow newlen and heap-corrupt the interpreter.

- Payout: $500
- Severity: low
- Program: Internet Bug Bounty
- Credited: jaybosamiya
- Disclosed: 2017-08-15
- Write-up quality: 7/10
- Original: https://hackerone.com/reports/241202
- Library page: https://bugbountylibrary.com/r/h1%3A241202
- Tags: domain:oss impact:rce kind:bounty platform:hackerone sev:low tech:python technique:source-review vuln:memory-corruption

**Target:** CPython 2.7 stringobject.c PyString_DecodeEscape via ast.c parsestr
**Root cause:** newlen = 4*len overflows Py_ssize_t when recode_encoding is set, allocating a tiny buffer that is then filled with the full decoded string.
**Steps:**
1. Craft a .py file starting with `# -*- coding: us-ascii -*-` to force recode_encoding non-null in parsestr (ast.c).
2. Include a string literal of ~1GB (on 32-bit) so 4*len overflows Py_ssize_t to a small value.
3. PyString_FromStringAndSize allocates the small buffer; the decode loop writes the full string into it.
4. Run poc-gen.py to generate poc.py; load under 32-bit ASAN Python build to observe heap corruption/crash.
**How found:** Code review of PyString_DecodeEscape spotted the unchecked 4*len multiplication feeding an allocation, then traced reachability through ast.c parsestr via the file coding declaration.
**Exploitation:** Attacker supplies a malicious .py source file; when parsed, the overflowed allocation is overrun by the decoded string, corrupting the heap and potentially enabling arbitrary code execution.
**Insight:** Encoding-declaration-driven recode paths multiply length by a factor; audit any `N*len` allocation where N>1 and the input length is attacker-controlled for Py_ssize_t overflow, especially on 32-bit builds.
