# Integer underflow / arbitrary null write in fread/gzread

Integer underflow in PHP's fread/gzread length parameter on 64-bit lets an attacker write an arbitrary null byte via a negative string length.

- Payout: $500
- Severity: high
- Program: Internet Bug Bounty
- Credited: fms
- Disclosed: 2019-10-13
- Write-up quality: 7/10
- Original: https://hackerone.com/reports/141212
- Library page: https://bugbountylibrary.com/r/h1%3A141212
- Tags: domain:oss impact:dos kind:bounty platform:hackerone sev:high tech:php technique:fuzzing technique:source-review vuln:memory-corruption

**Target:** PHP ext/standard/file.c zif_fread and gzread
**Root cause:** The length parameter to fread/gzread underflows to a negative value (e.g. -2147483648) on 64-bit, and the null-terminator write `Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0` uses that negative length as an offset, producing an out-of-bounds null write.
**Steps:**
1. Craft a PHP script calling `fread`/`gzread` with a length argument that underflows to a negative 32-bit value on 64-bit PHP.
2. Run under gdb/ASAN; observe SIGSEGV in `zif_fread` at file.c:1769.
3. Inspect `*return_value`: `value.str.len = -2147483648`.
4. The null-terminator write uses the negative len as index, writing a null byte at an attacker-influenced offset.
**How found:** Custom fuzzer plus ASAN on PHP 5.5/5.6/7.0 surfaced the crash; gdb inspection of the return_value struct revealed the negative string length feeding the null-terminator write.
**Exploitation:** Triggered by supplying a crafted length to fread/gzread so the internal string length becomes negative; the subsequent null-terminator store writes a zero byte out of bounds. Demonstrated as a crash under ASAN/gdb; arbitrary null-byte write primitive on 64-bit.
**Insight:** When auditing PHP internals, watch for length parameters that can go negative on 64-bit (int truncation) and are then used directly as array indices in null-terminator or bounds writes; fuzz with ASAN and inspect struct fields like `value.str.len` for sign anomalies.
