# Integer overflow leading to buffer overflow

Integer overflow in Perl_my_setenv's nlen+vlen+2 allocation lets attacker-controlled long env strings cause a heap buffer overflow via memcpy, enabling code execution.

- Payout: $1,000
- Severity: critical
- Program: Internet Bug Bounty
- Credited: jkrshnmenon
- Disclosed: 2019-09-25
- CVE: CVE-2018-18311
- Write-up quality: 7/10
- Original: https://hackerone.com/reports/424447
- Library page: https://bugbountylibrary.com/r/h1%3A424447
- Tags: domain:oss impact:rce kind:bounty platform:hackerone sev:critical tech:linux technique:source-review vuln:memory-corruption

**Target:** Perl core util.c Perl_my_setenv (legacy Perl)
**Root cause:** nlen and vlen are declared as 32-bit int while strlen returns size_t; summing two ~2GB strings overflows the int, so safesysmalloc allocates a too-small buffer that memcpy then overflows.
**Steps:**
1. Locate Perl_my_setenv in util.c around line 2070.
2. Note nlen/vlen are int (32-bit) but strlen returns size_t on 64-bit.
3. Craft nam and val each ~2147483647 bytes long.
4. Call setenv with these values so (nlen+vlen+2) overflows int.
5. safesysmalloc allocates undersized new_env; memcpy copies nlen+vlen bytes, overflowing heap.
6. Observe segfault on 64-bit Ubuntu 16.04 perl.
**How found:** Code reading of Perl_my_setenv: noticed nlen/vlen typed as int while strlen returns size_t, then reasoned that summing two attacker-controlled ~2GB strings overflows the 32-bit addition used in the allocation size.
**Exploitation:** Attacker supplies two very long environment variable name/value strings (~2GB each) to a Perl process; the integer overflow yields a small heap allocation, and memcpy writes attacker-controlled bytes past the heap boundary, causing memory corruption that can lead to arbitrary code execution.
**Insight:** When auditing C code, grep for int/short variables assigned from strlen/size_t and used in allocation arithmetic; the 32-bit truncation on 64-bit platforms is a classic overflow even when the buffer copy itself looks correct.
