# efree() on uninitialized Heap data in imagescale leads to use-after-free

Integer-overflow error path in PHP's imagescale() frees uninitialized Weights pointers, causing use-after-free and potential remote code execution.

- Payout: $1,500
- Severity: critical
- Program: Internet Bug Bounty
- Found by: simonscannell
- Disclosed: 2020-10-10
- CVE: CVE-2016-10166
- Write-up quality: 7/10
- Original: https://hackerone.com/reports/478367
- Library page: https://bugbountylibrary.com/r/h1%3A478367
- Tags: area:oss domain:oss impact:privesc impact:rce kind:bounty platform:hackerone sev:critical tech:php technique:incomplete-fix technique:regression technique:source-review vuln:memory-corruption

**Target:** PHP ext/gd libgd imagescale() / _gdContributionsAlloc
**Root cause:** On overflow2(windows_size) failure, the cleanup loop frees res->ContribRow[i].Weights for entries never allocated; u-- makes u=-1 so the loop is skipped, leaving uninitialized pointers, and a related free() bug from an incomplete CVE-2016-10166 backport.
**Steps:**
1. Call imagescale() with dimensions causing overflow2(windows_size, sizeof(double)) to be true
2. Observe overflow_error=1 and Weights left uninitialized
3. u-- sets u=-1 so cleanup loop `for(i=0;i<=u;i++)` never runs
4. Trigger subsequent free of uninitialized Weights pointer -> UAF
**How found:** Code review of gd_interpolation.c after noticing PHP's libgd never received the CVE-2016-10166 patch; traced the overflow error path and spotted the u-- making the cleanup loop unreachable.
**Exploitation:** Craft image/dimension input to hit the overflow path, leaving uninitialized Weights pointers that are later freed, yielding use-after-free; report claims local safe-mode bypass and potential remote exploitation.
**Insight:** When auditing vendored libraries, diff against upstream fixes: an unapplied CVE patch often means the original bug persists, and the patch itself may introduce new bugs (here a UAF) worth reviewing in the backport.

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

**Vulnerable _gdContributionsAlloc free loop**

```
if (overflow2(line_length, sizeof(ContributionType))) {
		gdFree(res);
		return NULL;
	}
	res->ContribRow = (ContributionType *) gdMalloc(line_length * sizeof(ContributionType));
	if (res->ContribRow == NULL) {
		gdFree(res);
		return NULL;
	}
	for (u = 0 ; u < line_length ; u++) {
		if (overflow2(windows_size, sizeof(double))) {
			overflow_error = 1;
		} else {
			res->ContribRow[u].Weights = (double *) gdMalloc(windows_size * sizeof(double));
		}
		if (overflow_error == 1 || res->ContribRow[u].Weights == NULL) {
			unsigned int i;
			u--;
			for (i=0;i<=u;i++) {
                gdFree(res->ContribRow[i].Weights);
			}
```

