# Heap overflow due to integer overflow in pg_escape_string() function

Integer overflow in PHP pg_escape_string() on 32-bit lets a 0x7fffffff-length string allocate a 0x10-byte buffer, causing heap overflow and RCE.

- Payout: hidden
- Severity: low
- Program: Internet Bug Bounty
- Found by: fosec
- Disclosed: 2019-11-12
- Write-up quality: 7/10
- Original: https://hackerone.com/reports/180584
- Library page: https://bugbountylibrary.com/r/h1%3A180584
- Tags: area:oss domain:oss impact:dos impact:rce kind:bounty platform:hackerone sev:low tech:php technique:source-review vuln:memory-corruption

**Target:** ext/pgsql pg_escape_string() in PHP 7.1 (32-bit)
**Root cause:** pg_escape_string() calls zend_string_alloc(ZSTR_LEN(from) * 2) without overflow check; on 32-bit, len 0x7fffffff doubles to wrap, allocating a tiny 0x10-byte buffer for a huge string.
**Steps:**
1. Run on a 32-bit PHP 7.1 build with pgsql extension.
2. Execute `ini_set('memory_limit', -1); $s = str_repeat("a",0x7FFFFFFF); $escaped = pg_escape_string($s);`
3. Observe _emalloc called with 0x10 due to `(0x7fffffff*2+0x14)&0xfffffffc` overflow.
4. PQescapeStringInternal writes the full string into the undersized buffer, overwriting adjacent heap until SIGSEGV.
**How found:** Code review of ext/pgsql/pgsql.c:4384 spotted zend_string_alloc(ZSTR_LEN(from) * 2) with no size check; hypothesized integer wrap at PHP_INT_MAX length on 32-bit, confirmed in gdb at the _emalloc call showing size 0x10.
**Exploitation:** Attacker supplies a ~2GB string to pg_escape_string(); the undersized allocation is overflowed by libpq's escape loop, corrupting adjacent PHP heap objects. Researcher reports leaking memory to bypass ASLR+DEP, controlling EIP, and achieving arbitrary code execution yielding /bin/sh.
**Escalation:** Heap overflow -> memory leak to defeat ASLR/DEP -> EIP control -> arbitrary code execution.
**Insight:** Audit length-doubling allocations (len*2, len+n) for integer wrap on 32-bit; a single unchecked multiply before an allocator turns a string-escape helper into a heap overflow.

