# imagecolormatch Out Of Bounds Write on Heap 

Heap OOB write in PHP imagecolormatch: attacker-controlled palette index up to 255 overflows a 40-byte buffer, enabling safe_mode bypass.

- Payout: $1,500
- Severity: high
- Program: Internet Bug Bounty
- Found by: simonscannell
- Disclosed: 2020-10-10
- CVE: CVE-2019-6977
- Write-up quality: 8/10
- Original: https://hackerone.com/reports/478368
- Library page: https://bugbountylibrary.com/r/h1%3A478368
- Tags: area:oss domain:oss impact:privesc kind:bounty platform:hackerone sev:high tech:php technique:source-review vuln:memory-corruption vuln:privilege-escalation

**Target:** PHP imagecolormatch / gdImageColorMatch (GD extension)
**Root cause:** Buffer sized as 5*im2->colorsTotal but indexed by pixel color value up to 255, so a small palette with a high pixel index writes past the allocation.
**Steps:**
1. Create truecolor image img1 and palette image img2 of size 0xfff x 0xfff
2. Allocate only one color in img2 via imagecolorallocate
3. Set a pixel to index 255 with imagesetpixel($img2,0,0,255)
4. Call imagecolormatch($img1,$img2) to trigger OOB write of up to 1200 bytes
**How found:** Code review of gdImageColorMatch: noticed buffer sized by colorsTotal but indexed by pixel color char value, mismatch yields OOB.
**Exploitation:** Attacker controls both the palette index (up to 255) and RGB values written, giving a controlled heap overflow of up to ~1200 bytes; used to build a local safe_mode bypass exploit.
**Escalation:** Chained the heap corruption into a local safe_mode/disabled-functions bypass.
**Insight:** When a buffer is sized by one attacker-controlled count but indexed by another (palette size vs pixel index), check for index/count mismatch; small palette + high pixel index is the trigger.

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

**PHP PoC script triggering heap OOB write**

```
$img1 = imagecreatetruecolor(0xfff, 0xfff);
$img2 = imagecreate(0xfff, 0xfff);
imagecolorallocate($img2, 0, 0, 0);
imagesetpixel($img2, 0, 0, 255);
imagecolormatch($img1, $img2);
```

## Write-ups of the same bug (oldest first)
- 2019-09-11: [Apache HTTP [2.4.17-2.4.38] Local Root Privilege Escalation](https://bugbountylibrary.com/r/h1%3A520903) — real
- 2020-10-10: [imagecolormatch Out Of Bounds Write on Heap ](https://bugbountylibrary.com/r/h1%3A478368) — simonscannell (this one)

