Skip to content
Memory corruption Disclosed report Advanced CVE-2020-8174

napi_get_value_string_X allow various kinds of memory corruption

The N-API string conversion functions mishandle a zero buffer size, causing an integer underflow that writes the whole string past the end of the buffer. An attacker who controls the string contents could corrupt memory, crash the process, or potentially execute code.

tniessen Follow

Originally disclosed on HackerOne

Bounty$250 High 8.5 View original
  • Triaged in 16 days
  • Fixed in 4 months
  • Paid in 6 months
  • Disclosed after 5 months

Summary:

napi_get_value_string_latin1, napi_get_value_string_utf8, napi_get_value_string_utf16 are vulnerable to buffer overflows, partially due to an integer underflow.

Description:

napi_get_value_string_latin1, napi_get_value_string_utf8, and napi_get_value_string_utf16 behave like this:

  1. If the output pointer is NULL, return.
  2. Write min(string_length, bufsize - 1) bytes to the output buffer. Note that bufsize is an unsigned type, so this leads to an integer underflow for bufsize == 0. Since this is a size_t, the underflow will cause the entire string to be written to memory, no matter how long the string is.
  3. Finally, write to buf[copied], where copied is the number of bytes previously written. Even if step 2 hadn't written out of bounds, this would (for bufsize == 0).

Steps To Reproduce:

C++
Napi::Value Test(const Napi::CallbackInfo& info) {
  char buf[1];
  // This should be a valid call, e.g., due to a malloc(0).
  napi_get_value_string_latin1(info.Env(), info[0], buf, 0, nullptr);
  return info.Env().Undefined();
}
JavaScript
const binding = require('bindings')('validation');
console.log(binding.test('this could be code that might later be executed'));

Running the above script corrupts the call stack:

Bash
tniessen@local-vm:~/validation-fails$ node .
*** stack smashing detected ***: <unknown> terminated
Aborted (core dumped)

The best outcome is a crash, but a very likely outcome is data corruption. If the attacker can control the string's contents, they can even insert code into the process heap, or modify the call stack. Depending on the architecture and application, this can lead to various issues, up to remote code execution.

It is perfectly valid to pass in a non-NULL pointer for buf while specifying bufsize == 0. For example, malloc(0) is not guaranteed to return NULL. A npm package might correctly work on one machine based on the assumption that malloc(0) == NULL, but might create severe security issues on a different host. Passing a non-NULL pointer is also not ruled out by the documentation of N-API, so it is not valid to assume that buf will always be NULL if bufsize == 0.

Impact

npm packages and other applications that use N-API may involuntarily open up severe security issues, that might even be exploitable remotely. Even if buf is a valid pointer, passing bufsize == 0 allows to write outside of the boundaries of that buffer.

Step 2 of the description allows an attacker to precisely define what is written to memory by passing in a custom string. Depending on whether the pointer points to heap or stack, possible results include data corruption, crashes (and thus DoS), and possibly even remote code execution, either by writing instructions to heap memory or by corrupting the stack.

Many attacks are likely caught by kernel and hardware protection mechanisms, but that depends on the specific hardware, kernel, and application, and memory layout. Even if they are caught, the entire process will crash (which is still good compared to other outcomes).

The original report as published on HackerOne, by tniessen. 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. 6 min read.

Context

Node.js exposes N-API (N-API, the stable C API for native addons) so that npm packages and other applications can be written in C or C++ and loaded into a Node.js process. Among the functions N-API provides are three that copy a JavaScript string into a caller-supplied C buffer:

  • napi_get_value_string_latin1
  • napi_get_value_string_utf8
  • napi_get_value_string_utf16

These are ordinary string-conversion helpers: a native addon hands over a JavaScript value, a destination buffer and a buffer size, and the runtime copies the string into that buffer, truncating it to fit. The report is about what happens when the buffer size is zero.

Setup

The researcher built a small native addon to exercise the API. The reproduction uses the bindings npm package to load a compiled module named validation, and a C++ function Test that calls napi_get_value_string_latin1 with a one-byte stack buffer and a size of zero. The report does not list Node.js versions, operating system versions or compiler details beyond the shell prompt shown in the output.

Finding it

The researcher describes the behaviour of all three functions as a three-step sequence:

  1. If the output pointer is NULL, return.
  2. Write min(string_length, bufsize - 1) bytes to the output buffer. Note that bufsize is an unsigned type, so this leads to an integer underflow for bufsize == 0. Since this is a size_t, the underflow will cause the entire string to be written to memory, no matter how long the string is.
  3. Finally, write to buf[copied], where copied is the number of bytes previously written. Even if step 2 hadn't written out of bounds, this would (for bufsize == 0).

The flaw is therefore twofold: the length calculation underflows when the size is zero, and the terminating write at buf[copied] lands out of bounds even if the copy itself had been bounded. The researcher also stresses that passing a non-NULL pointer with bufsize == 0 is perfectly valid. malloc(0) is not guaranteed to return NULL, and the N-API documentation does not rule out a non-NULL pointer, so an addon cannot assume that buf will always be NULL when the size is zero.

Exploitation

Step 1: call the API with a zero buffer size

The native side allocates a single byte on the stack and passes it as the destination with a size of zero:

C++
Napi::Value Test(const Napi::CallbackInfo& info) {
  char buf[1];
  // This should be a valid call, e.g., due to a malloc(0).
  napi_get_value_string_latin1(info.Env(), info[0], buf, 0, nullptr);
  return info.Env().Undefined();
}

The comment in the code makes the intended scenario explicit: a size of zero is something a caller can legitimately arrive at, for example through a malloc(0). The pointer is non-NULL, so the early return in step 1 does not apply, and the underflow in step 2 takes over.

Step 2: drive it from JavaScript with an attacker-controlled string

JavaScript
const binding = require('bindings')('validation');
console.log(binding.test('this could be code that might later be executed'));

The string passed from JavaScript is the data that gets written past the end of the one-byte buffer. Because the underflow makes the copy length effectively unbounded, the whole string is written to memory regardless of its length, and the final terminator write adds one more byte beyond that.

Step 3: observe the result

Bash
tniessen@local-vm:~/validation-fails$ node .
*** stack smashing detected ***: <unknown> terminated
Aborted (core dumped)

Running the script corrupts the call stack. The output shows the process aborting with a stack smashing message. The researcher notes that the best outcome is a crash, but a very likely outcome is data corruption. If the attacker can control the string's contents, they can even insert code into the process heap, or modify the call stack. Depending on the architecture and application, this can lead to various issues, up to remote code execution.

Root cause

The mistake is in the length arithmetic of the three string-copy functions. bufsize is an unsigned size_t, so bufsize - 1 wraps to a huge value when bufsize is zero. The min(string_length, bufsize - 1) expression then selects the full string length instead of zero, and the entire string is copied into a buffer that was declared to have no room. Separately, the terminator write buf[copied] is unconditional and out of bounds for bufsize == 0 even without the underflow.

The design assumption that made this easy to miss is that a zero size implies a NULL pointer. The report points out that this is not guaranteed: malloc(0) may return a non-NULL pointer, and the N-API documentation does not forbid a non-NULL buffer with a zero size. An npm package that works correctly on one machine because malloc(0) happened to return NULL can create severe security issues on a different host. The report does not describe any defence in the runtime that would have caught the overflow before it reached memory.

Impact

npm packages and other applications that use N-API may involuntarily open up severe security issues, that might even be exploitable remotely. Even if buf is a valid pointer, passing bufsize == 0 allows writing outside the boundaries of that buffer.

Step 2 of the description allows an attacker to precisely define what is written to memory by passing in a custom string. Depending on whether the pointer points to heap or stack, possible results include data corruption, crashes (and thus DoS), and possibly even remote code execution, either by writing instructions to heap memory or by corrupting the stack.

Many attacks are likely caught by kernel and hardware protection mechanisms, but that depends on the specific hardware, kernel, and application, and memory layout. Even if they are caught, the entire process will crash, which is still good compared to other outcomes.

Fix

The report does not describe a patch or the change that was made. What it establishes is the condition that any fix has to handle: a zero bufsize must not underflow, and the terminator write must not occur outside the buffer when the size is zero, whether or not the pointer is NULL.

Variants to test

  • Call each of napi_get_value_string_latin1, napi_get_value_string_utf8 and napi_get_value_string_utf16 with bufsize == 0 and a non-NULL buffer. A positive result is a crash, a stack-smashing abort, or visible corruption of adjacent memory.
  • Pass a zero size with a buffer obtained from malloc(0) on a platform where it returns non-NULL. A positive result is the same out-of-bounds write, showing the bug is reachable through ordinary allocation patterns rather than only through a deliberately tiny stack array.
  • Vary the length and contents of the JavaScript string. A positive result is that the full string, not a truncated prefix, appears beyond the buffer, confirming the underflow rather than a simple off-by-one.
  • Try the same zero-size pattern against other native string-conversion helpers in the same API family. A positive result is any helper that writes past a zero-length buffer or writes a terminator when the declared size is zero.

Hunting notes

This kind of bug hides at the boundary between a managed runtime and native code, in the C API surface that addons call. The signal is an unsigned size parameter combined with a subtraction, especially size - 1, and a separate unconditional terminator write. Documentation that treats a zero size as equivalent to a NULL pointer is worth checking against the actual implementation, because malloc(0) behaviour varies by platform and allocator.

To show impact, the researcher reduced the issue to a minimal native function and a two-line JavaScript driver, then demonstrated a concrete failure: the stack smashing abort in the output above. The report also spells out the attacker-controlled data path, the string contents, and the range of outcomes from corruption and denial of service up to possible remote code execution, while being explicit that kernel and hardware protections may turn exploitation into a crash depending on the environment.

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. 14 min read.

What happened, in plain words

Node.js is a program that lets people run JavaScript outside a web browser, for example on a server. One of its features is that it can load extra pieces of software written in other languages, mainly C and C++. These extra pieces are called native addons, and they are often shipped as npm packages (npm is the package manager that JavaScript developers use to download reusable code).

To let those C and C++ addons talk to JavaScript, Node.js offers a set of ready-made functions called N-API. Think of an API as a service counter: instead of building something yourself, you walk up to the counter, hand over your request in a fixed format, and get an answer back. N-API is the counter where native code asks Node.js to do things with JavaScript values.

Three of those functions copy a JavaScript string into a piece of memory that the addon provides. The addon says: here is my string, here is my memory area, and here is how many bytes of room I have. The function then copies the text in, cutting it short if it does not fit.

The researcher found that if the addon says it has zero bytes of room, the functions do not behave safely. Instead of copying nothing, they copy the entire string into memory that was never meant to hold it, and then write one extra byte past the end. That is a memory corruption bug: the program writes data where it should not, which can crash it, corrupt other data, or in the worst case let an attacker run their own code.

Context

Node.js exposes N-API, the stable C API for native addons, so that npm packages and other applications can be written in C or C++ and loaded into a Node.js process. Among the functions N-API provides are three that copy a JavaScript string into a caller-supplied C buffer:

  • napi_get_value_string_latin1
  • napi_get_value_string_utf8
  • napi_get_value_string_utf16

A few words on those names. A buffer is a fixed-size block of memory, like a row of numbered boxes, each holding one byte. A byte is the basic unit of computer memory; a short piece of text takes one byte per character in the simplest encodings. Latin1, UTF-8 and UTF-16 are three different ways of turning characters into bytes, which is why there are three separate functions.

These are ordinary string-conversion helpers: a native addon hands over a JavaScript value, a destination buffer and a buffer size, and the runtime copies the string into that buffer, truncating it to fit. The report is about what happens when the buffer size is zero.

Setup

The researcher built a small native addon to exercise the API. The reproduction uses the bindings npm package to load a compiled module named validation, and a C++ function Test that calls napi_get_value_string_latin1 with a one-byte stack buffer and a size of zero. The report does not list Node.js versions, operating system versions or compiler details beyond the shell prompt shown in the output.

Two ideas from that paragraph are worth unpacking. A compiled module is a file of machine instructions produced from C or C++ source code; the bindings package is a small helper that finds and loads such a file from JavaScript. The stack is the region of memory a program uses for short-lived local data, such as the variables inside a function while it runs. A one-byte stack buffer is therefore a single box on that stack, and anything written past it lands on whatever the program keeps next door.

Finding it

The researcher describes the behaviour of all three functions as a three-step sequence:

  1. If the output pointer is NULL, return.
  2. Write min(string_length, bufsize - 1) bytes to the output buffer. Note that bufsize is an unsigned type, so this leads to an integer underflow for bufsize == 0. Since this is a size_t, the underflow will cause the entire string to be written to memory, no matter how long the string is.
  3. Finally, write to buf[copied], where copied is the number of bytes previously written. Even if step 2 hadn't written out of bounds, this would (for bufsize == 0).

Step by step in plain words:

  1. A pointer is a memory address, essentially the number of a box in the row. NULL means "no address at all". So if the caller did not supply a destination, the function simply stops. That is a sensible guard.
  2. min(a, b) means "take the smaller of the two values". string_length is how many bytes the text needs. bufsize is how many bytes of room the caller declared. The intent is to copy at most one byte less than the room available, leaving space for a terminator (a zero byte that marks the end of a C string). The problem is the subtraction. bufsize is an unsigned type, meaning it can only hold zero and positive numbers, never negatives. size_t is the standard unsigned type used for sizes. When you subtract 1 from an unsigned zero, the result does not become minus one; it wraps around to the largest value the type can hold, a huge number. So min(string_length, huge_number) is just string_length, and the whole string gets copied.
  3. After copying, the function writes a terminator at buf[copied], the position just after the last byte it copied. With a zero size, that position is already outside the buffer, so this write is out of bounds even if step 2 had copied nothing.

The flaw is therefore twofold: the length calculation underflows when the size is zero, and the terminating write at buf[copied] lands out of bounds even if the copy itself had been bounded. The researcher also stresses that passing a non-NULL pointer with bufsize == 0 is perfectly valid. malloc(0) is not guaranteed to return NULL, and the N-API documentation does not rule out a non-NULL pointer, so an addon cannot assume that buf will always be NULL when the size is zero.

malloc is the standard C function for asking the system for memory; you tell it how many bytes you want and it gives you back an address. Asking for zero bytes is legal, but the answer is not fixed: some systems hand back NULL, others hand back a real address that simply has no usable room. That variability is what makes the bug easy to miss in testing and dangerous in the field.

Exploitation

Step 1: call the API with a zero buffer size

The native side allocates a single byte on the stack and passes it as the destination with a size of zero:

C++
Napi::Value Test(const Napi::CallbackInfo& info) {
  char buf[1];
  // This should be a valid call, e.g., due to a malloc(0).
  napi_get_value_string_latin1(info.Env(), info[0], buf, 0, nullptr);
  return info.Env().Undefined();
}

Line by line:

  • Napi::Value Test(const Napi::CallbackInfo& info) { declares a function called Test that JavaScript can call. Napi::Value is the type of value it returns to JavaScript, and info carries the arguments the JavaScript side passed in.
  • char buf[1]; creates the one-byte buffer on the stack. char is a single byte, and [1] means an array of exactly one of them.
  • The comment // This should be a valid call, e.g., due to a malloc(0). records the researcher's point: a caller can legitimately end up with a zero size, for instance because malloc(0) gave it an address with no room.
  • napi_get_value_string_latin1(info.Env(), info[0], buf, 0, nullptr); is the vulnerable call. It asks N-API to convert the first JavaScript argument (info[0]) into Latin1 text, store it in buf, use a declared size of 0, and pass nullptr (no address) for the optional out-parameter that would report how many bytes were copied.
  • return info.Env().Undefined(); hands JavaScript back the value undefined, which is JavaScript's "nothing here" value.
  • The closing } ends the function.

The comment in the code makes the intended scenario explicit: a size of zero is something a caller can legitimately arrive at, for example through a malloc(0). The pointer is non-NULL, so the early return in step 1 does not apply, and the underflow in step 2 takes over.

Step 2: drive it from JavaScript with an attacker-controlled string

JavaScript
const binding = require('bindings')('validation');
console.log(binding.test('this could be code that might later be executed'));

Line by line:

  • const binding = require('bindings')('validation'); loads the bindings helper and uses it to find and load the compiled module called validation. The result, stored in binding, is the JavaScript-side handle to the native code.
  • console.log(binding.test('this could be code that might later be executed')); calls the native Test function with a string, and prints whatever it returns. The string is deliberately chosen to look like something meaningful, to make the point that the bytes written into memory are under the attacker's control.

The string passed from JavaScript is the data that gets written past the end of the one-byte buffer. Because the underflow makes the copy length effectively unbounded, the whole string is written to memory regardless of its length, and the final terminator write adds one more byte beyond that.

Step 3: observe the result

Bash
tniessen@local-vm:~/validation-fails$ node .
*** stack smashing detected ***: <unknown> terminated
Aborted (core dumped)

Line by line:

  • tniessen@local-vm:~/validation-fails$ node . is the shell prompt followed by the command. node . tells Node.js to run the program in the current directory. The part before the $ is the user name, machine name and working directory.
  • *** stack smashing detected ***: <unknown> terminated is the message printed when the program detects that its stack has been overwritten, and it stops.
  • Aborted (core dumped) confirms the process was killed. A core dump is a snapshot of the program's memory saved at the moment of the crash, useful for later analysis.

Running the script corrupts the call stack. The process aborts after the overwrite. The researcher notes that the best outcome is a crash, but a very likely outcome is data corruption. If the attacker can control the string's contents, they can even insert code into the process heap, or modify the call stack. Depending on the architecture and application, this can lead to various issues, up to remote code execution.

The heap is the other main region of memory, used for data that lives longer than a single function call. Remote code execution means an attacker somewhere else on the network gets their own instructions run by the victim's program, which is about as bad as a memory bug gets.

Root cause

The mistake is in the length arithmetic of the three string-copy functions. bufsize is an unsigned size_t, so bufsize - 1 wraps to a huge value when bufsize is zero. The min(string_length, bufsize - 1) expression then selects the full string length instead of zero, and the entire string is copied into a buffer that was declared to have no room. Separately, the terminator write buf[copied] is unconditional and out of bounds for bufsize == 0 even without the underflow.

An everyday comparison: imagine a form that asks how many guests you are bringing, and the kitchen plans to cook one fewer portion than that number to leave room for dessert. If you write zero, the kitchen's arithmetic goes wrong and it cooks for a huge crowd instead of nobody. The number was never checked for the zero case before the subtraction.

The design assumption that made this easy to miss is that a zero size implies a NULL pointer. The report points out that this is not guaranteed: malloc(0) may return a non-NULL pointer, and the N-API documentation does not forbid a non-NULL buffer with a zero size. An npm package that works correctly on one machine because malloc(0) happened to return NULL can create severe security issues on a different host. The report does not describe any defence in the runtime that would have caught the overflow before it reached memory.

Impact

npm packages and other applications that use N-API may involuntarily open up severe security issues, that might even be exploitable remotely. Even if buf is a valid pointer, passing bufsize == 0 allows writing outside the boundaries of that buffer.

Step 2 of the description allows an attacker to precisely define what is written to memory by passing in a custom string. Depending on whether the pointer points to heap or stack, possible results include data corruption, crashes (and thus DoS), and possibly even remote code execution, either by writing instructions to heap memory or by corrupting the stack.

DoS stands for denial of service: the attacker's goal is simply to make the service stop working, for example by crashing it repeatedly. Data corruption means some other value in memory gets overwritten with the attacker's bytes, which can change the program's behaviour in unpredictable ways.

Many attacks are likely caught by kernel and hardware protection mechanisms, but that depends on the specific hardware, kernel, and application, and memory layout. Even if they are caught, the entire process will crash, which is still good compared to other outcomes.

The kernel is the core of the operating system, and modern processors and kernels include features that mark certain memory as non-executable or detect tampering. They raise the cost of exploitation, but they do not make the underlying bug harmless.

Fix

The report does not describe a patch or the change that was made. What it establishes is the condition that any fix has to handle: a zero bufsize must not underflow, and the terminator write must not occur outside the buffer when the size is zero, whether or not the pointer is NULL.

Variants to test

  • Call each of napi_get_value_string_latin1, napi_get_value_string_utf8 and napi_get_value_string_utf16 with bufsize == 0 and a non-NULL buffer. A positive result is a crash, a stack-smashing abort, or visible corruption of adjacent memory.
  • Pass a zero size with a buffer obtained from malloc(0) on a platform where it returns non-NULL. A positive result is the same out-of-bounds write, showing the bug is reachable through ordinary allocation patterns rather than only through a deliberately tiny stack array.
  • Vary the length and contents of the JavaScript string. A positive result is that the full string, not a truncated prefix, appears beyond the buffer, confirming the underflow rather than a simple off-by-one.
  • Try the same zero-size pattern against other native string-conversion helpers in the same API family. A positive result is any helper that writes past a zero-length buffer or writes a terminator when the declared size is zero.

An off-by-one is a much smaller mistake where a program writes exactly one byte too many. Here the mistake is bigger: the whole string goes out of bounds, which is why the researcher wants to distinguish the two when testing.

Hunting notes

This kind of bug hides at the boundary between a managed runtime and native code, in the C API surface that addons call. A managed runtime is one that handles memory for you, like JavaScript; native code manages its own memory, and the handover point between the two is where assumptions on each side can disagree. The signal is an unsigned size parameter combined with a subtraction, especially size - 1, and a separate unconditional terminator write. Documentation that treats a zero size as equivalent to a NULL pointer is worth checking against the actual implementation, because malloc(0) behaviour varies by platform and allocator.

To show impact, the researcher reduced the issue to a minimal native function and a two-line JavaScript driver, then demonstrated a concrete failure: the stack smashing abort in the output above. The report also spells out the attacker-controlled data path, the string contents, and the range of outcomes from corruption and denial of service up to possible remote code execution, while being explicit that kernel and hardware protections may turn exploitation into a crash depending on the environment.

Glossary

  • API: a fixed set of functions one piece of software offers to another, like a service counter with defined requests and answers.
  • Buffer: a fixed-size block of memory used to hold data such as text.
  • Byte: the basic unit of computer memory, large enough for one simple character in many encodings.
  • C / C++: programming languages that give direct control over memory, often used for performance-critical code.
  • Compiled module: a file of machine instructions produced from source code, which a program can load at runtime.
  • Core dump: a snapshot of a program's memory saved when it crashes.
  • CVSS: a standard scoring system for the severity of a security flaw; 8.5 is in the high range.
  • Data corruption: unwanted changes to values stored in memory.
  • Denial of service (DoS): making a service unavailable, for example by crashing it.
  • Heap: the region of memory used for data that outlives a single function call.
  • Integer underflow: what happens when you subtract from an unsigned number at zero and it wraps around to a very large value instead of going negative.
  • Kernel: the core of the operating system, which manages memory, processes and hardware.
  • Latin1 / UTF-8 / UTF-16: three ways of representing characters as bytes.
  • malloc: the standard C function for requesting memory from the system.
  • Memory corruption: writing data to memory locations the program was not supposed to touch.
  • min(a, b): an expression that returns the smaller of two values.
  • N-API: Node.js's stable C interface that native addons use to interact with JavaScript values.
  • Native addon: a piece of software written in C or C++ that is loaded into a Node.js process.
  • Node.js: a runtime that runs JavaScript outside the browser, commonly on servers.
  • npm: the package manager JavaScript developers use to download and share reusable code.
  • NULL / nullptr: a special pointer value meaning "no address at all".
  • Off-by-one: a mistake where a program writes exactly one element too many.
  • Out of bounds: outside the memory area a program was given permission to use.
  • Pointer: a value that holds a memory address, like the number of a box in a row.
  • Remote code execution (RCE): an attacker getting their own instructions executed by the victim's program over a network.
  • size_t: the standard unsigned integer type used for sizes in C and C++.
  • Stack: the region of memory used for short-lived local data inside functions.
  • Stack protector: a compiler-added check that detects writes past local buffers and aborts the program.
  • Terminator: a zero byte written after a string in C to mark where the text ends.
  • Truncating: cutting text short so it fits in the available space.
  • Unsigned type: a number type that can hold zero and positive values but never negatives.

More by tniessen

View all

15 more disclosed reports, best first.

More from Node.js

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.