Hunting Bugs in Nginx JavaScript Engine (njs)
The njs JavaScript engine's Array.prototype.toSpliced (and similar methods) assigned the result array to the return value before fully initialising it, so an exception thrown by a getter left uninitialised heap memory visible as array elements. An attacker could exploit this to obtain a type confusion primitive and ultimately achieve remote code execution.
0xbigshaq.github.io
Published on 0xbigshaq.github.io
I spent the last few weekends on a new target: njs, a JavaScript interpreter that is being used as part of the nginx webserver’s backend. Essentially, my goal is to find a way to break out of the interpreter’s sandbox without using require("childprocess"); and friends.
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
njs is a JavaScript interpreter used as part of the nginx web server's backend. The goal of this research was to break out of the interpreter's sandbox without using require("child_process"); and similar escape hatches. After some fuzzing, two bugs turned up; CodeQL was then used to find more variants of the first one.
The research was conducted on commit [redacted], which was the latest at the time of the research (May 2024).
Two bugs are described below:
- Bug #1, a type confusion in
Array.prototype.toSplicedthat can be weaponised into arbitrary read/write and code execution. - Bug #2, an out-of-bounds read reachable through
String.prototype.replaceAll()that could not be exploited.
Setup
The work was done against the njs source tree at the commit above. The tools involved were a fuzzer, CodeQL (used to model the vulnerable pattern and find variants), and GDB for inspecting memory during exploit development. The debugging output shows a glibc main_arena symbol and the /lib/x86_64-linux-gnu/libc.so.6 path.
Finding it
After some fuzzing, two bugs were found. The first is a type confusion in Array.prototype.toSpliced: the implementation can hand back an array whose elements are uninitialised heap memory. The second is an off-by-one reachable through String.prototype.replaceAll() that leads to an out-of-bounds read.
Bug #1: Type Confusion
Description
The implementation of Array.prototype.toSpliced has a bug that allows you to get an array with uninitialised heap memory. This can be leveraged into a type confusion primitive by:
- Allocating a
Uint8Arraybuffer; the buffer will contain bytes that form annjs_value_tobject. - Freeing it.
- Allocating an array using
Array.prototype.toSpliced; the memory in this array will not be initialised because the bug is triggered. The address of this array will be the same address freed in step 2. - Profit: the array now holds fake
njs_value_telements.
The PoC triggers a segfault.
Analysis
In Array.prototype.toSpliced / njs_array_prototype_to_spliced, the code performs the following:
- Allocate an array.
- Assign the pointer to
retvalby callingnjs_set_array(). - Access the array members (which also trigger getters/setters) to populate the new array's content.
- If something goes wrong, abort and return
NJS_ERROR.
The relevant code is at src/njs_array.c#L1451-L1468.
The problem is in step 2: the new pointer is assigned to retval too early. retval receives a heap chunk with uninitialised data, and then the throw new Error() exception, triggered by the getter, makes the function bail out in the middle of the toSpliced operation, before the memory pointed to by retval is fully initialised.
Visually, this is how the retval variable is represented in memory:

This is a JavaScript Array with elements; each element has a size of 16 bytes and is represented with an njs_value_t struct.
Initial Exploit
The first attempt was similar to the initial PoC but with a few more strings and changes to the allocation sizes. Heap shaping was still being worked out, but a scenario was reached where buggy[0] lands on a glibc main_arena pointer:
gef➤ print value->data->u.array->start
$5 = (njs_value_t *) 0x555555649000
gef➤ hexdump byte 0x555555649000
0x0000555555649000 10 83 c4 f7 ff 7f 00 00 10 83 c4 f7 ff 7f 00 00 ................ <---- buggy[0]
0x0000555555649010 f0 8f 64 55 55 55 00 00 f0 8f 64 55 55 55 00 00 ..dUUU....dUUU.. buggy[1]
0x0000555555649020 07 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ ...
0x0000555555649030 07 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
0x0000555555649040 07 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
0x0000555555649050 07 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
0x0000555555649060 07 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
0x0000555555649070 07 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
gef➤ x/gx 0x0000555555649000
0x555555649000: 0x00007ffff7c48310
gef➤ info symbol 0x00007ffff7c48310
main_arena + 1680 in section .data of /lib/x86_64-linux-gnu/libc.so.6
This might be useful, but it is not the type of primitive wanted here. The aim was to make it re-usable and njs-oriented: achieving a fake njs_value_t in order to build up to arbitrary read/write and then code execution.
Full Exploit
After brainstorming with @iamgweej about how to leverage the bug to RCE, the exploit was ready. The breakthrough came from looking at the allocator's logic: @iamgweej found the way to achieve the heap leak described in Step 0, which allowed the bug to be weaponised into stronger primitives.
Links to the exploits:
- @iamgweej's exploit:
https://gist.github.com/iamgweej/[redacted] - The author's exploit:
https://github.com/0xbigshaq/njs-vr/blob/[redacted]/exp.js
Below is a breakdown of exp.js, how it works and the logic behind it.
Step 0: Heap leak
To get a heap leak, allocate a chunk with a size that is not njs_is_power_of_two(). This breaks the alignment of the chunk. As a result, the NJS engine decides to round up the size and push an njs_mp_block_t struct into the remaining space, at the end of the chunk. The relevant code is at src/njs_mp.c#L617-L627.
This helps if you:
- Create a
Uint8Arraybuffer with a size that is not a power of two. - In the last 8 bytes of the byte array, craft a fake array element /
njs_value_tand set its type to be anNJS_STRINGwith a size below 0xf to make it a short string. Strings below 15 characters are embedded within the remaining space ofnjs_value_t. - Free the
Uint8Arrayby callingUint8Array.prototype.sort()(ref:njs_typed_array.c#L2048). - Trigger the bug and get the chunk that was freed.
- At this point the contents of the freed
Uint8Arraybuffer are confused with a JavaScriptArraywhose memory is not initialised, so it still contains the contents of theUint8Array. - Access the last element of the
Array; it should be a shortNJS_STRINGcontaining the data ofnjs_mp_block_t, which previously was part of theUint8Array, accommodating its last 8 bytes.
The heap leak PoC produces:
[*] heap leak = 0x55851b7e3fb8
This leaks (njs_mp_block_t*)->node.left. The first 8 bytes of the njs_value_t are set with the type-info of a string, and the allocator wrote the other half, which is the string's content. Visually, this is how it looks at runtime:

Step 1: Getting an addrOf primitive
To figure out where things are on the heap, the method from the previous step is used with a small twist. Now that there is a valid address in the VA space, another string can be forged, but with a greater length. This was not possible previously because strings with a length above 15 require a pointer to their contents. With a valid pointer, a bigger OOB read primitive can be created that allows finding the address of other objects on the heap.
To get an addrOf primitive:
- Allocate
raw_buf = new Uint8Array(0x2000);. This buffer is used in the next steps to forge more complex objects to achieve arbitrary read/write. - Call
oob_read()and provide the heap pointer leaked from the previous step. This helper uses the same technique as the previous step but with a string of type long string, so the pointer can be dereferenced to get a large string. It confuses the elements of(njs_string_t*)->startwith(njs_mp_block_t*)->node.rightand(njs_string_t*)->lengthwith(njs_mp_block_t*)->node.left.oob_read()returns a string that points somewhere on the heap, with a very large size.
- Take the large string and search for the contents of
raw_bufin it. - Once the offset of
raw_bufwithin the large string is found, calculate its address by adding the offset to the pointer leaked in step 0.
The implementation of this part is at exp.js#L208-L223. Output:
[*] long string length: 0x60dbde40
[*] offset: 451168
[?] addrof raw_buf = 0x55bf60e28420
Step 2: Build a fakeObj primitive
To get arbitrary read/write:
- Trigger the bug again, this time making one of the elements of
fake_arr[5]a JavaScript TypedArray. - This TypedArray information points to the contents of
raw_buf, which is controlled and whose address is known from the previous step. - In
raw_buf[0x100], spoof annjs_typed_array_tstruct that has a pointer to annjs_array_buffer_t0x100 bytes after it.
The implementation of this part is at exp.js#L112-L139. All that remains is to manipulate the contents of raw_buf to change where fakeObj points, done with the arb_read() and arb_write() helper functions at exp.js#L141-L190.
Step 3: Break ASLR
The allocator stores a function pointer to njs_mp_rbtree_compare() in its chunks' metadata (njs_mp.c#L217). To find the base address of the njs binary, the arb_read() primitive is used to traverse the allocator's red-black tree until a pointer to njs_mp_rbtree_compare is found. This is implemented in exp.js#L229-L245; from there it should not be a problem to calculate any other address in the binary.
Step 4: Get PC control
At njs_process_script(), there is a call to njs_console->engine->output() (njs_shell.c#L3531). The njs_engine_t::output struct member is a function pointer that can be overwritten to take over the execution flow. It is set to system() as follows (exp.js#L254-L266).
When the script ends, it triggers a call to system() with a pointer to an njs_engine_t struct; its first bytes were changed to /bin/sh\x00 to pop a shell. Output:

Step 1 is still not 100% reliable; ways to make it more stable were still being looked at.
Spot more variants with CodeQL
A CodeQL query was written to detect whether this pattern repeats itself in more places. The pattern is: allocate an array, assign it to retval via njs_set_array(), then trigger accessors while populating it, so that an exception can bail out with retval already set.
The query yielded two more vulnerable JS functions, in addition to the original:
- Function:
njs_array_prototype_to_spliced(the original bug described here)- Source:
array = njs_array_alloc(vm, 0, new_length, 0); - Sink:
njs_set_array(retval, array); - Trigger accessors:
njs_value_property_i64_set(...);,njs_value_property_i64_set(...);
- Source:
- Function:
njs_array_prototype_to_sorted- Source:
array = njs_array_alloc(vm, 0, length, 0); - Sink:
njs_set_array(retval, array);
- Source:
- Function:
njs_array_prototype_to_reversed- Sink:
njs_set_array(retval, array); - Trigger accessors:
njs_value_property_i64(...);
- Sink:
These were going to be reported too, but the project maintainer replied to the initial report with this message:
Thank you for the report and a good catch.
The root-cause here is in the step 2. We set a retval value too early. Unfortunately in NJS, the retval value will be visible outside the native JS function even if the exception was thrown. I found similar places in
The moral of the story: ctrl+shift+f is faster than modelling a vulnerability with CodeQL.
Bug #2: OOB Read
Description
It is possible to achieve an OOB read primitive and leak heap memory via String.prototype.replaceAll(). NJS stores UTF-8 strings by storing a string buffer followed by a map of offsets; the documentation for it is in njs_string.h#L45-L71.
A specially crafted JS script can trigger an off-by-one bug in the function that resolves an offset inside a UTF-8 string, which can then be leveraged to achieve a bigger out-of-bounds read, more than just one byte.
PoC
A fuzzer generated the first PoC. After playing around with the logic to figure out what causes the crash, a second PoC was written.
Analysis
In njs_string_prototype_replace (that is, String.prototype.replaceAll), during the last iteration of the do { ... } while (pos >= 0 ...); loop, the call to njs_string_utf8_offset() with a pos that points to the last byte of the string triggers unexpected behaviour (src/njs_string.c#L3429-L3430).
This leads to an out-of-bound access, one element beyond the UTF-8 offset table of the string (src/njs_string.c#L2102), which in turn advances the p pointer by 0x140 bytes, a value that is clearly too big.
From a debugging perspective, this is how the OOB looks:
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── source:src/njs_string.c+2090 ────
2085
2086 if (map[0] == 0) {
2087 njs_string_utf8_offset_map_init(start, end - start);
2088 }
2089
●→ 2090 start += map[index / NJS_STRING_MAP_STRIDE - 1];
2091 }
2092
2093 for (skip = index % NJS_STRING_MAP_STRIDE; skip != 0; skip--) {
2094 start = njs_utf8_next(start, end);
2095 }
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
gef➤ print index
$61 = 0x100
gef➤ print index/32-1
$62 = 0x7
gef➤ print map[7]
$63 = 0x140
The offset 0x140 is not a real offset, but rather part of a pointer whose last bytes are 0x140:
gef➤ x/wx map
0x613000002994: 0x00000020 --> map[0] first entry
0x613000002998: 0x00000040 --> map[1]
0x61300000299c: 0x00000060 --> map[2]
0x6130000029a0: 0x00000080 --> map[3]
0x6130000029a4: 0x000000a0 --> map[4]
0x6130000029a8: 0x000000c0 --> map[5]
0x6130000029ac: 0x000000e0 --> map[6] last entry
# ... continue reading, but switch to 8 byte alignment(bc this is 64bit system)
gef➤ x/gx (0x6130000029ac+4)
0x6130000029b0: 0x0000610000000140
0x6130000029b8: 0x0000610000000140
0x6130000029c0: 0x0000613000002b80
0x6130000029c8: 0x00000130bebe0200
# another representation
gef➤ print *map@10
$65 = {0x20, 0x40, 0x60, 0x80, 0xa0, 0xc0, 0xe0, 0x140, 0x6100, 0x140}
At first sight the root cause was thought to be somewhere in njs_string_utf8_offset(), but after reporting to the maintainer he helped to notice that it is actually in njs_string_index_of():
Thank you for the report. I looked into the issue. The root cause is the fact that
njs_string_index_of()which represent StringIndexOf() for zero-length search strings "finds" the search string even after the last character:
If searchValue is the empty String and fromIndex ≤ the length of string, this algorithm returns fromIndex. The empty String is effectively found at every position within a string, including after the last code unit.NJS stores strings as UTF8 (not as UTF16 with always 2 bytes characters), to efficiently find a char byte offset by its index NJS stores a sparse offset map after a string body (if a string is UTF8 and its length is >= 32 character).
The sparse map is available only for indices
[0, length - 1], so it is invalid to callnjs_string_utf8_offset()with indices outside this range.Because
njs_string_index_of()returns valid pos after the last characternjs_string_utf8_offset()is called with index equal tostring.length.It seems the bug is only visible when "this" string has >= 32 characters && s.length % 32 == 0.
Theoretical Exploit
The bug could not be exploited because of two lines at the end of the function (src/njs_string.c#L3445-L3447). Because an out-of-bounds access was achieved, p_start ends up bigger than string.start + string.size, which causes chain.error to go from 0 to 1. As a result, the next line, which creates the final string / return value, will not generate the string, since it checks whether chain.error is true or false.
Theoretically, if chain.error could somehow be made to stay 0, the exploit would work and leak heap data. Whether the verification of chain.error == 1 is absent in earlier versions of njs is left as a task for the reader.
Root cause
Bug #1 is an ordering mistake: njs_set_array(retval, array) publishes the freshly allocated, not yet populated array to retval before the members are copied in. In NJS, the retval value is visible outside the native JS function even if an exception is thrown, so a getter that throws leaves the caller holding an array backed by uninitialised heap memory. The same shape appears in njs_array_prototype_to_sorted and njs_array_prototype_to_reversed.
Bug #2 is a boundary error in the interaction between njs_string_index_of() and njs_string_utf8_offset(). StringIndexOf() semantics allow the empty search string to be "found" at fromIndex equal to the string length, so njs_string_utf8_offset() is called with an index one past the last valid one. The sparse offset map only covers indices [0, length - 1], so the lookup reads one element beyond the map. The bug is only visible when the string has at least 32 characters and its length is a multiple of 32.
Impact
Bug #1 gives an attacker who can run JavaScript inside njs a type confusion that was developed into a full chain: heap leak, addrOf, fakeObj, arbitrary read/write, ASLR bypass and PC control via the njs_engine_t::output function pointer, ending in system() called with a pointer to a modified njs_engine_t struct. That is code execution in the context of the njs process. Step 1 of the chain was still not fully reliable at the time of writing.
Bug #2 leaks heap memory through an out-of-bounds read, but the chain.error check prevents the corrupted string from being returned, so it was not exploited.
Fix
The maintainer's reply identifies the root cause of Bug #1 as setting the retval value too early, and states that similar places were found. The report does not describe the patch itself. For Bug #2, the maintainer's analysis points at njs_string_index_of() returning a position after the last character, which then reaches njs_string_utf8_offset() with an out-of-range index; the report does not describe the patch.
Variants to test
- Other array-copying built-ins that allocate a result, publish it to
retval, then populate it while running user getters. A positive result is an array whose elements contain heap data that was never written by the script, or a crash when those elements are read. - The same pattern in any native function that can throw between publishing
retvaland finishing initialisation. A positive result is a value visible to the caller after an exception was thrown. - String search and offset routines where an empty search string or a boundary index can reach a sparse offset map. A positive result is an offset read past the map, visible as an implausible pointer-sized value in the computed offset.
- Strings whose length is a multiple of the map stride (32 in this code) combined with
replaceAlland an empty search string. A positive result is an out-of-bounds read or a crash in the offset resolution path.
What happened, in plain words
A security researcher spent a few weekends looking at njs, a small JavaScript engine that nginx (a very popular web server) can use to run JavaScript on the server side. Think of nginx as a post office that hands out web pages; njs is a little scripting desk inside that post office where the staff can run small programs to decide what to hand out.
The researcher's goal was to break out of the interpreter's sandbox without using require("child_process") and similar escape hatches. The goal was to break out of the interpreter's sandbox.
Two bugs turned up. The first one, a type confusion in a built-in array function, was eventually turned into a full exploit that ends with a shell. The second one, an out-of-bounds read in a string function, was found and analysed but could not be turned into an exploit.
All the work was done against a specific snapshot of the njs source code, identified by a long hexadecimal string (a commit hash): [redacted]. That was the newest version at the time, May 2024. Pinning the exact version matters because code changes constantly; a bug report is only meaningful if everyone knows which version was tested.
The words you need before we start
A few ideas come up again and again, so here they are up front.
- Source code is the human-written text of a program. Compiling turns it into a binary that the computer runs.
- Memory is the computer's working space. Programs ask the operating system for chunks of it, use them, and give them back. A heap is the area where a program keeps things whose size is only known while it runs, like arrays and strings.
- Allocating means asking for a chunk of memory. Freeing means giving it back. A classic family of bugs comes from using memory after it has been freed, or from reading memory that was never written to.
- Uninitialised memory is memory that has been handed to your program but still contains whatever the previous user left there. It is like being given a hotel room where the previous guest's notes are still in the drawer.
- A pointer is a number that says where in memory something lives, like a street address. An address and a pointer are the same idea.
- A struct is a bundle of related values stored together in memory, like a form with several fields.
- A type confusion is a bug where the program treats one kind of thing as if it were another kind. If you can make the program believe a number is actually a pointer, or that a string is actually an array, you can often make it read or write memory it should not touch.
- An out-of-bounds (OOB) read is reading past the end of a buffer, into memory that belongs to something else. It leaks data.
- Arbitrary read/write means the attacker can read or write any memory address they choose. That is usually the last step before taking control of a program.
- ASLR (Address Space Layout Randomisation) is a defence where the operating system loads programs at random addresses each time, so an attacker cannot hard-code addresses. Breaking ASLR means finding out where things actually landed.
- PC control means control of the program counter, the CPU register that says which instruction runs next. If you control it, you decide what the program does.
- A fuzzer is a tool that throws huge numbers of random or semi-random inputs at a program and watches for crashes. Crashes often point at bugs.
- CodeQL is a tool that lets you ask questions about source code in a query language, like a search engine for code patterns.
- GDB is a debugger: it lets you pause a running program and inspect its memory. GEF is an add-on that makes GDB friendlier.
- glibc is the standard C library on Linux; it includes the memory allocator that hands out heap chunks.
- A getter is a JavaScript property that runs a function when you read it. A setter runs a function when you write it. They let ordinary-looking property access run arbitrary code, which is why they are so useful in exploit development.
- A sandbox is a restricted environment. The point of a sandbox is that even if code inside it is malicious, it cannot reach the rest of the system.
Bug #1: Type Confusion
What the bug is
The JavaScript standard has a method called Array.prototype.toSpliced. It is a non-destructive version of splice: instead of modifying the original array, it builds a new array with some elements removed and others inserted. The bug is that this new array can be handed back to your script while its memory is still uninitialised. In other words, you get an array whose elements are whatever bytes happened to be lying around in that memory.
That is the type confusion: the engine thinks it is giving you an array of JavaScript values, but the bytes in it are leftovers from something else.
The researcher's plan to turn this into something useful was:
- Allocate a
Uint8Arraybuffer. AUint8Arrayis a JavaScript object holding raw bytes; it is the easiest way to write exact byte patterns into memory. The bytes written will be shaped like annjs_value_t, which is the internal struct njs uses to represent any JavaScript value. - Free that buffer, so its memory goes back to the allocator.
- Call
Array.prototype.toSplicedin a way that triggers the bug. The new array is allocated, and the allocator hands back the same chunk that was just freed. Because the bug interrupts the initialisation, the array's elements still contain the bytes from step 1. - Now the script holds an array whose elements are attacker-chosen bytes interpreted as JavaScript values. That is the primitive.
The proof of concept (PoC) triggers a segfault.
Why it happens
In the C function njs_array_prototype_to_spliced, the code does four things in order:
- Allocate an array.
- Store a pointer to it in a variable called
retvalby callingnjs_set_array(). - Access the array's members to fill in the new array's content. This step can run user-supplied getters and setters, because JavaScript lets you define them.
- If anything goes wrong, abort and return
NJS_ERROR.
The relevant code is at src/njs_array.c#L1451-L1468.
The mistake is in step 2. retval is set too early. The freshly allocated chunk is published to retval before it has been filled in. Then a getter throws throw new Error(), and the function bails out in the middle of the operation. The memory that retval points to is never fully initialised, but the caller still receives it.
Here is how retval looks in memory:

The picture shows a JavaScript Array with elements. Each element is 16 bytes and is represented by an njs_value_t struct.
First attempt at an exploit
The first exploit attempt was close to the original PoC, with a few more strings and different allocation sizes. The goal at this stage was to shape the heap, meaning to arrange allocations so that the freed chunk lands next to something interesting. The researcher managed to get buggy[0] to land on a glibc main_arena pointer. main_arena is an internal glibc structure that tracks free memory.
gef➤ print value->data->u.array->start
$5 = (njs_value_t *) 0x555555649000
gef➤ hexdump byte 0x555555649000
0x0000555555649000 10 83 c4 f7 ff 7f 00 00 10 83 c4 f7 ff 7f 00 00 ................ <---- buggy[0]
0x0000555555649010 f0 8f 64 55 55 55 00 00 f0 8f 64 55 55 55 00 00 ..dUUU....dUUU.. buggy[1]
0x0000555555649020 07 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ ...
0x0000555555649030 07 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
0x0000555555649040 07 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
0x0000555555649050 07 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
0x0000555555649060 07 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
0x0000555555649070 07 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
gef➤ x/gx 0x0000555555649000
0x555555649000: 0x00007ffff7c48310
gef➤ info symbol 0x00007ffff7c48310
main_arena + 1680 in section .data of /lib/x86_64-linux-gnu/libc.so.6
Line by line:
print value->data->u.array->startasks GDB to show where the array's element storage begins. The answer is0x555555649000.hexdump bytedumps the raw bytes at that address. The first 16 bytes are marked asbuggy[0], the next 16 asbuggy[1], and so on.x/gxreads one 8-byte value at the start of the array. It is0x00007ffff7c48310.info symbolasks GDB what that address belongs to. The answer:main_arena + 1680, inside glibc.
So the array's first element is a pointer into glibc's allocator bookkeeping. The researcher was not interested in this type of primitive. The aim was a reusable, njs-oriented primitive: a fake njs_value_t that could be built up into arbitrary read/write and then code execution.
The full exploit
After brainstorming with a friend, @iamgweej, the exploit was ready. The breakthrough came from studying the allocator's logic: @iamgweej found the heap leak technique described in Step 0, which made the rest possible.
The exploits are published at:
- @iamgweej's exploit:
https://gist.github.com/iamgweej/[redacted] - The author's exploit:
https://github.com/0xbigshaq/njs-vr/blob/[redacted]/exp.js
What follows is a walkthrough of exp.js.
Step 0: Heap leak
A heap leak means learning the address of something on the heap. Without an address, you cannot point anything at anything.
The trick: allocate a chunk whose size is not a power of two. njs has a helper called njs_is_power_of_two() and uses it to decide how to lay out chunks. If the size is not a power of two, the alignment breaks, so the engine rounds the size up and pushes an njs_mp_block_t struct into the leftover space at the end of the chunk. The relevant code is at src/njs_mp.c#L617-L627.
The leaked value comes from that leftover struct. The steps are:
- Create a
Uint8Arraybuffer whose size is not a power of two. - In the last 8 bytes of that buffer, craft a fake array element (an
njs_value_t) and set its type toNJS_STRINGwith a size below0xf. Strings shorter than 15 characters are stored inline inside thenjs_value_titself, so no separate pointer is needed. That is what makes this work: the fake string's content can be the allocator's own metadata. - Free the
Uint8Arrayby callingUint8Array.prototype.sort(). The reference isnjs_typed_array.c#L2048. - Trigger the bug and get the freed chunk back as an array.
- The array's memory is uninitialised, so it still contains the
Uint8Array's bytes. - Read the last element of the array. It should be a short
NJS_STRINGwhose content is thenjs_mp_block_tdata that the allocator wrote into the last 8 bytes.
The PoC prints:
[*] heap leak = 0x55851b7e3fb8
That value is (njs_mp_block_t*)->node.left. The researcher set the first 8 bytes of the njs_value_t with the type information of a string, and the allocator wrote the other half, which becomes the string's content. Here is how it looks at runtime:

Step 1: Getting an addrOf primitive
An addrOf primitive means: given a JavaScript object, find out its memory address. This is the mirror image of the heap leak: instead of leaking a value, you learn where a specific object lives.
The method is the same as Step 0, with a twist. Now that there is a valid address, another string can be forged, but with a longer length. That was not possible before, because strings longer than 15 characters need a pointer to their contents. With a valid pointer in hand, a much bigger out-of-bounds read becomes possible, and that can be used to find the addresses of other objects on the heap.
The steps:
- Allocate
raw_buf = new Uint8Array(0x2000);. This buffer is a scratchpad used later to forge more complex objects. - Call
oob_read()with the heap pointer leaked in Step 0. This helper uses the same trick but forges a long string, so the pointer can be dereferenced and a very large string comes back. Internally it confuses(njs_string_t*)->startwith(njs_mp_block_t*)->node.rightand(njs_string_t*)->lengthwith(njs_mp_block_t*)->node.left. oob_read()returns a string that points somewhere on the heap with a very large size.- Search inside that large string for the contents of
raw_buf. - Once the offset of
raw_bufinside the large string is known, add that offset to the pointer leaked in Step 0. That gives the address ofraw_buf.
The implementation is at exp.js#L208-L223. Output:
[*] long string length: 0x60dbde40
[*] offset: 451168
[?] addrof raw_buf = 0x55bf60e28420
Line by line:
- The first line reports the length of the forged string:
0x60dbde40bytes. - The second line is where
raw_buf's bytes were found inside that stretch: byte 451168. - The third line is the computed address of
raw_buf:0x55bf60e28420.
Step 2: Build a fakeObj primitive
A fakeObj primitive means: make the engine treat attacker-controlled bytes as if they were a real object. Combined with addrOf, this is the classic pair that leads to arbitrary read/write.
The steps:
- Trigger the bug again, this time making one of the elements of
fake_arr[5]a JavaScript TypedArray. A TypedArray is a view over a raw byte buffer. - That TypedArray's information points to the contents of
raw_buf, which the attacker controls and whose address is known from Step 1. - At
raw_buf[0x100], spoof annjs_typed_array_tstruct that has a pointer to annjs_array_buffer_t0x100 bytes after it.
The implementation is at exp.js#L112-L139. After that, all that remains is to change the contents of raw_buf to change where fakeObj points. That is done with the arb_read() and arb_write() helpers at exp.js#L141-L190.
Step 3: Break ASLR
ASLR randomises where programs and libraries are loaded, so an attacker cannot just hard-code an address. To break it, you need to find one known pointer and work out the base address from it.
The allocator stores a function pointer to njs_mp_rbtree_compare() in its chunks' metadata (njs_mp.c#L217). A red-black tree is a balanced data structure the allocator uses to keep track of free chunks. Using arb_read(), the exploit walks that tree until it finds a pointer to njs_mp_rbtree_compare. That gives the base address of the njs binary, and from there any other address in the binary can be calculated. The implementation is at exp.js#L229-L245.
Step 4: Get PC control
At njs_process_script(), there is a call to njs_console->engine->output() (njs_shell.c#L3531). The njs_engine_t::output struct member is a function pointer: a variable holding the address of a function to call. If the attacker can overwrite it, they decide what runs next.
The exploit sets it to system(), the C library function that runs a shell command, as follows (exp.js#L254-L266).
When the script ends, the engine calls system() with a pointer to an njs_engine_t struct. The exploit has changed that struct's first bytes to /bin/sh\x00 to pop a shell. Output:

Step 1 was still not 100% reliable at the time of writing; the researcher was looking for ways to make it more stable.
Spotting more variants with CodeQL
A CodeQL query was written to check whether the same pattern appears elsewhere. The pattern is: allocate an array, assign it to retval via njs_set_array(), then trigger accessors while populating it, so that an exception can bail out with retval already set.
The query found two more vulnerable functions:
njs_array_prototype_to_spliced(the original bug)- Source:
array = njs_array_alloc(vm, 0, new_length, 0); - Sink:
njs_set_array(retval, array); - Trigger accessors:
njs_value_property_i64_set(...);,njs_value_property_i64_set(...);
- Source:
njs_array_prototype_to_sorted- Source:
array = njs_array_alloc(vm, 0, length, 0); - Sink:
njs_set_array(retval, array);
- Source:
njs_array_prototype_to_reversed- Sink:
njs_set_array(retval, array); - Trigger accessors:
njs_value_property_i64(...);
- Sink:
In plain words: "source" is where the uninitialised array is created, "sink" is where it is published to the caller, and "trigger accessors" are the calls that can run user code and throw in between.
These were going to be reported too, but the project maintainer replied to the initial report with this message:
Thank you for the report and a good catch.
The root-cause here is in the step 2. We set a retval value too early. Unfortunately in NJS, the retval value will be visible outside the native JS function even if the exception was thrown. I found similar places in
The moral, as the researcher puts it: ctrl+shift+f (plain text search in an editor) is faster than modelling a vulnerability with CodeQL.
Bug #2: OOB Read
What the bug is
It is possible to get an out-of-bounds read and leak heap memory through String.prototype.replaceAll(), which replaces every occurrence of a substring.
To understand the bug, you need to know how njs stores strings. It keeps the UTF-8 bytes of the string, followed by a map of offsets. UTF-8 is a way of encoding text where a character can take one or more bytes, so to jump to the Nth character quickly, njs keeps a small table of byte offsets. The documentation is at njs_string.h#L45-L71.
A specially crafted script can trigger an off-by-one in the function that resolves an offset inside a UTF-8 string. That off-by-one can then be leveraged into a bigger out-of-bounds read, more than one byte.
PoC
A fuzzer generated the first PoC. After experimenting to understand what caused the crash, a second PoC was written.
Analysis
In njs_string_prototype_replace (the C function behind String.prototype.replaceAll), during the last iteration of the do { ... } while (pos >= 0 ...); loop, njs_string_utf8_offset() is called with a pos that points to the last byte of the string. That triggers unexpected behaviour (src/njs_string.c#L3429-L3430).
This causes an out-of-bounds access, one element past the UTF-8 offset table (src/njs_string.c#L2102), which advances the p pointer by 0x140 bytes. That value is clearly too big to be a real offset.
Here is the OOB in the debugger:
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── source:src/njs_string.c+2090 ────
2085
2086 if (map[0] == 0) {
2087 njs_string_utf8_offset_map_init(start, end - start);
2088 }
2089
●→ 2090 start += map[index / NJS_STRING_MAP_STRIDE - 1];
2091 }
2092
2093 for (skip = index % NJS_STRING_MAP_STRIDE; skip != 0; skip--) {
2094 start = njs_utf8_next(start, end);
2095 }
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
gef➤ print index
$61 = 0x100
gef➤ print index/32-1
$62 = 0x7
gef➤ print map[7]
$63 = 0x140
Line by line:
- The listing shows the C code around line 2090. The arrow marks the line that is about to run:
start += map[index / NJS_STRING_MAP_STRIDE - 1];. It looks up an entry in the offset map and adds it tostart. print indexshows the index being resolved:0x100, which is 256.print index/32-1shows which map slot that index maps to:0x7, the eighth slot. The stride is 32, so every 32 characters share one map entry.print map[7]shows the value read from that slot:0x140. That is the bogus offset.
The 0x140 is not a real offset. It is part of a pointer whose last bytes happen to be 0x140:
gef➤ x/wx map
0x613000002994: 0x00000020 --> map[0] first entry
0x613000002998: 0x00000040 --> map[1]
0x61300000299c: 0x00000060 --> map[2]
0x6130000029a0: 0x00000080 --> map[3]
0x6130000029a4: 0x000000a0 --> map[4]
0x6130000029a8: 0x000000c0 --> map[5]
0x6130000029ac: 0x000000e0 --> map[6] last entry
# ... continue reading, but switch to 8 byte alignment(bc this is 64bit system)
gef➤ x/gx (0x6130000029ac+4)
0x6130000029b0: 0x0000610000000140
0x6130000029b8: 0x0000610000000140
0x6130000029c0: 0x0000613000002b80
0x6130000029c8: 0x00000130bebe0200
# another representation
gef➤ print *map@10
$65 = {0x20, 0x40, 0x60, 0x80, 0xa0, 0xc0, 0xe0, 0x140, 0x6100, 0x140}
Line by line:
x/wx mapreads 4-byte words starting at the map. The first seven entries are0x20,0x40,0x60,0x80,0xa0,0xc0,0xe0, which are sensible offsets. The eighth slot is one past the last real entry of the map.x/gx (0x6130000029ac+4)reads 8-byte values starting just after the last real entry. The value0x0000610000000140is a pointer whose last bytes are0x140, which is where the bogus offset comes from.print *map@10prints ten entries as an array, showing the same thing: the first seven are real, then0x140,0x6100,0x140are garbage from neighbouring memory.
At first the researcher thought the root cause was in njs_string_utf8_offset(). After reporting, the maintainer pointed out that it is actually in njs_string_index_of():
Thank you for the report. I looked into the issue. The root cause is the fact that
njs_string_index_of()which represent StringIndexOf() for zero-length search strings "finds" the search string even after the last character:
If searchValue is the empty String and fromIndex ≤ the length of string, this algorithm returns fromIndex. The empty String is effectively found at every position within a string, including after the last code unit.NJS stores strings as UTF8 (not as UTF16 with always 2 bytes characters), to efficiently find a char byte offset by its index NJS stores a sparse offset map after a string body (if a string is UTF8 and its length is >= 32 character).
The sparse map is available only for indices
[0, length - 1], so it is invalid to callnjs_string_utf8_offset()with indices outside this range.Because
njs_string_index_of()returns valid pos after the last characternjs_string_utf8_offset()is called with index equal tostring.length.It seems the bug is only visible when "this" string has >= 32 characters && s.length % 32 == 0.
In plain words: the JavaScript standard says that searching for the empty string always succeeds, even at a position one past the last character. njs follows that rule, so it asks for the byte offset of a character index equal to the string's length. But the offset map only covers indices from 0 to length minus 1. The lookup reads one slot past the map, and that slot contains unrelated bytes.
Theoretical exploit
The bug could not be exploited because of two lines at the end of the function (src/njs_string.c#L3445-L3447). Because the out-of-bounds access happened, p_start ends up bigger than string.start + string.size, which flips chain.error from 0 to 1. The next line, which builds the final string to return, checks chain.error and refuses to build it.
In theory, if chain.error could be kept at 0, the exploit would work and leak heap data. Whether the check is missing in earlier versions of njs is left as an exercise for the reader.
Root cause, in one place
Bug #1 is an ordering mistake. njs_set_array(retval, array) publishes the freshly allocated, not yet populated array before the members are copied in. In njs, retval is visible outside the native function even if an exception is thrown, so a getter that throws leaves the caller holding an array backed by uninitialised heap memory. The same shape appears in njs_array_prototype_to_sorted and njs_array_prototype_to_reversed.
Bug #2 is a boundary error between njs_string_index_of() and njs_string_utf8_offset(). The standard allows the empty search string to be found at fromIndex equal to the string length, so njs_string_utf8_offset() is called with an index one past the last valid one. The sparse offset map only covers [0, length - 1], so the lookup reads one element beyond the map. The bug is only visible when the string has at least 32 characters and its length is a multiple of 32.
Impact
Bug #1 gives anyone who can run JavaScript inside njs a type confusion that was developed into a full chain: heap leak, addrOf, fakeObj, arbitrary read/write, ASLR bypass, and PC control via the njs_engine_t::output function pointer, ending in system() called with a pointer to a modified njs_engine_t struct. That is code execution in the context of the njs process. Step 1 of the chain was still not fully reliable at the time of writing.
Bug #2 leaks heap memory through an out-of-bounds read, but the chain.error check prevents the corrupted string from being returned, so it was not exploited.
Fix
The maintainer's reply identifies the root cause of Bug #1 as setting the retval value too early, and states that similar places were found. The report does not describe the patch itself. For Bug #2, the maintainer's analysis points at njs_string_index_of() returning a position after the last character, which then reaches njs_string_utf8_offset() with an out-of-range index; the report does not describe the patch.
Variants to test
- Other array-copying built-ins that allocate a result, publish it to
retval, then populate it while running user getters. A positive result is an array whose elements contain heap data that was never written by the script, or a crash when those elements are read. - The same pattern in any native function that can throw between publishing
retvaland finishing initialisation. A positive result is a value visible to the caller after an exception was thrown. - String search and offset routines where an empty search string or a boundary index can reach a sparse offset map. A positive result is an offset read past the map, visible as an implausible pointer-sized value in the computed offset.
- Strings whose length is a multiple of the map stride (32 in this code) combined with
replaceAlland an empty search string. A positive result is an out-of-bounds read or a crash in the offset resolution path.
Glossary
- njs: a JavaScript interpreter that can be used inside the nginx web server to run scripts on the server side.
- nginx: a widely used web server and reverse proxy.
- Sandbox: a restricted environment that stops code inside it from reaching the rest of the system.
- Commit hash: a long hexadecimal identifier for one exact snapshot of a source code repository.
- Source code: the human-readable text of a program.
- Heap: the area of memory where a program keeps things whose size is only known at runtime.
- Allocate / free: ask the operating system or allocator for a chunk of memory / give it back.
- Uninitialised memory: memory that has been handed to a program but still contains whatever was there before.
- Pointer / address: a number that says where something lives in memory.
- Struct: a bundle of related values stored together in memory.
- Type confusion: a bug where the program treats one kind of value as another kind.
- Out-of-bounds (OOB) read: reading past the end of a buffer into neighbouring memory.
- Arbitrary read/write: the ability to read or write any memory address the attacker chooses.
- ASLR: Address Space Layout Randomisation, a defence that loads programs at random addresses each run.
- PC control: control of the program counter, the CPU register that decides which instruction runs next.
- Fuzzer: a tool that feeds many random or semi-random inputs to a program and watches for crashes.
- CodeQL: a tool for querying source code with a query language, like a search engine for code patterns.
- GDB: a debugger that lets you pause a program and inspect its memory.
- GEF: an add-on for GDB that makes it friendlier.
- glibc: the standard C library on Linux, which includes the memory allocator.
- main_arena: an internal glibc structure that tracks free memory.
- Getter / setter: a JavaScript property that runs a function when read or written.
Array.prototype.toSpliced: a JavaScript method that returns a new array with elements removed and inserted, without changing the original.Uint8Array: a JavaScript object holding raw bytes.njs_value_t: the internal njs struct that represents any JavaScript value.njs_mp_block_t: an internal njs struct that the allocator places in leftover space at the end of a chunk.njs_is_power_of_two(): an njs helper that checks whether a number is a power of two.- Heap leak: learning the address of something on the heap.
- addrOf primitive: given an object, find its memory address.
- fakeObj primitive: make the engine treat attacker-controlled bytes as a real object.
- TypedArray: a JavaScript view over a raw byte buffer.
- Red-black tree: a balanced data structure used by the allocator to track free chunks.
njs_mp_rbtree_compare(): a function used by the allocator's red-black tree, whose pointer in chunk metadata helps break ASLR.njs_engine_t::output: a function pointer in the njs engine struct that the exploit overwrites to gain PC control.system(): a C library function that runs a shell command./bin/sh: the standard Unix shell program.- UTF-8: a variable-length encoding of text where a character can take one or more bytes.
- Offset map: a small table of byte offsets that lets njs jump to the Nth character of a UTF-8 string quickly.
String.prototype.replaceAll(): a JavaScript method that replaces every occurrence of a substring.njs_string_index_of(): the njs function behind string search, which returns a position.njs_string_utf8_offset(): the njs function that converts a character index into a byte offset.chain.error: a flag in the string replacement code that marks whether something went wrong.- Segfault: a crash caused by accessing memory the operating system forbids.
- PoC (proof of concept): a small script or program that demonstrates a bug.
- RCE (remote code execution): running attacker-chosen code on a target machine.
ctrl+shift+f: the usual shortcut for searching all files in an editor, used here as a joke about how a plain search can beat a fancy tool.