# Integer Overflow in _gd2GetHeader() resulting in heap overflow

Integer overflow in PHP's _gd2GetHeader() when multiplying chunk dimensions causes undersized heap allocation, then heap overflow writing chunk entries.

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

**Target:** PHP ext/gd libgd GD2 image parser (_gd2GetHeader)
**Root cause:** nc = ncx * ncy and sidx = sizeof(t_chunk_info) * nc are computed without overflow checks; a crafted GD2 header with large chunk counts overflows the size, so gdCalloc allocates a too-small buffer while the loop still iterates nc times.
**Steps:**
1. Craft poc.gd with GD2 header where Chunks wide (ncx) and Chunks high (ncy) are both `0x5b00`
2. Run `php poc.php` where poc.php calls `imagecreatefromgd2("poc.gd")`
3. Observe at gd_gd2.c:139 nc=0x20590000, at line 141 sidx=sizeof(t_chunk_info)*nc overflows to 0x2C80000
4. gdCalloc(sidx,1) allocates undersized buffer; loop `for(i=0;i<nc;i++)` writes cidx[i].offset/size past the allocation
5. Process crashes with SIGSEGV in gdGetInt writing to out-of-bounds pointer
**How found:** Code review of _gd2GetHeader arithmetic; set breakpoint at gd_gd2.c:139 and traced nc and sidx values to spot the multiplication overflow before gdCalloc.
**Exploitation:** Attacker supplies a malicious GD2 image to any PHP app calling imagecreatefromgd2; the undersized allocation followed by out-of-bounds chunk-entry writes yields heap corruption, demonstrated as a crash (potential RCE with heap grooming).
**Insight:** In image-format parsers, audit every `count * sizeof(struct)` allocation where count comes from two attacker-controlled header fields multiplied together; the overflow check `sidx <= 0` misses positive wrapped values.

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

**PHP script calling imagecreatefromgd2 on crafted file**

```
<?php imagecreatefromgd2("poc.gd"); ?>
```

