Skip to content
Memory corruption Disclosed report Advanced

Incorrect code generation when result of NODE_NEGATE is not used

The mruby compiler's code generator recursed into the argument of a negation node without checking it was a valid syntax tree node, so a crafted numeric literal could set an internal filename index to an attacker-chosen value. This caused an assertion failure and crash of the interpreter, and the author notes it could potentially allow arbitrary bytecode generation.

dkasak Follow

Originally disclosed on HackerOne

Bounty$1,000 Low View original
  • Triaged in 4 hours
  • Fixed in 24 days
  • Paid in 26 days
  • Disclosed after 26 days

Introduction

Not using the result of NODE_NEGATE leads to incorrect code generation which could possibly result in arbitrary bytecode generation. Currently it is possible to produce a crash through a SIGABRT via an assert failure.

Proof of concept

assert_failure.rb

-0E00;0
  1. Run either:

    a. mruby assert_failure.rb b. sandbox assert_failure.rb

  2. Both cause a crash via an assert failure.

Discussion

The flaw was introduced in commit d56a19cbf526190de036130fe3a5bf14a0705ee2.

The problem is that codegen is called recursively on the argument of NODE_NEGATE without checking whether it is a valid node. This is problematic because codegen assumes that its tree argument is a valid node (i.e. that the node's type is stored under the car member, further nodes or data under the cdr member and that filename_index and lineno are set properly). This creates an opportunity for the attacker to control further code generation, though it might not be possible to place a valid node type in car with the current codebase. Nevertheless, filename_index can be controlled and this is what allows the POC to make the assertion on line 135 of debug.c fail:

ruby: ext/mruby_engine/mruby/src/debug.c:135: mrb_debug_info_append_file: Assertion `irep->filename' failed.
zsh: abort      mruby-engine/bin/sandbox assert_failure.rb

Running mruby with the following input in gdb:

-0.5555555555555555555;0

And breaking on parse.y:2885, we can see that filename_index is set to 13621 (which is two '5' characters interpreted as an integer):

(gdb) x/16hd yyvsp[0].nd->cdr
0x79162c:       11824   13621   13621   13621   13621   13621   13621   13621
0x79163c:       13621   13621   53      0       52      0       0       0
(gdb) p yyvsp[0].nd->cdr->filename_index 
$21 = 13621

Then, breaking codegen.c:1230, we see that tree->filename_index is indeed set to 13621:

(gdb) p tree->filename_index
$22 = 13621

This eventually leads to assert to fail.

Solution

To fix the problem, we should ensure tree->car is a valid node before calling codegen on tree in the case of NODE_NEGATE.

negate_node.patch

diff --git a/mrbgems/mruby-compiler/core/codegen.c b/mrbgems/mruby-compiler/core/codegen.c
index 90bafb3..9d47cca 100644
--- a/mrbgems/mruby-compiler/core/codegen.c
+++ b/mrbgems/mruby-compiler/core/codegen.c
@@ -2232,7 +2232,9 @@ codegen(codegen_scope *s, node *tree, int val)
    nt = (intptr_t)tree->car;
    tree = tree->cdr;
    if (!val) {
-        codegen(s, tree, NOVAL);
+        if (tree && (intptr_t)tree->car < NODE_LAST) {
+          codegen(s, tree, NOVAL);
+        }
        break;
    }
    switch (nt) {

-- Denis Kasak

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

Context

mruby is an embeddable Ruby implementation with its own compiler. The compiler parses source into a node tree and then walks that tree in codegen to emit bytecode. The report concerns a code generation flaw in that compiler, specifically in the handling of NODE_NEGATE, the node that represents unary minus. The bug was filed against the Shopify scripts program and rated low severity, with a bounty of 1000 USD.

The flaw appears when the result of the negation is not used, that is, when codegen is called with NOVAL.

Setup

The report does not describe any account, role or remote service. The proof of concept is a local source file executed either with the mruby interpreter or with the sandbox binary shipped with the engine. The researcher also used gdb to inspect the node tree during parsing and code generation.

Finding it

The researcher states that not using the result of NODE_NEGATE leads to incorrect code generation, which could possibly result in arbitrary bytecode generation. In the current state it is possible to produce a crash through a SIGABRT caused by an assert failure. The flaw was introduced in commit [redacted].

The underlying problem is that codegen is called recursively on the argument of NODE_NEGATE without checking whether it is a valid node. codegen assumes its tree argument is a valid node: the node type is stored under the car member, further nodes or data under the cdr member, and filename_index and lineno are set properly. Passing something that is not a valid node breaks those assumptions.

Exploitation

Step 1: the minimal crashing input

The proof of concept is a single line of Ruby source:

Ruby
-0E00;0

Because the result of the negation is discarded, codegen is invoked on the negated operand with NOVAL, which is the path that triggers the bug.

Step 2: run it

The file is saved as assert_failure.rb and executed in either of two ways:

Bash
mruby assert_failure.rb
Bash
sandbox assert_failure.rb

Both cause a crash via an assert failure. The output shown in the report is:

Text
ruby: ext/mruby_engine/mruby/src/debug.c:135: mrb_debug_info_append_file: Assertion `irep->filename' failed.
zsh: abort      mruby-engine/bin/sandbox assert_failure.rb

Step 3: observing the corrupted field

To understand why the assertion fails, the researcher ran mruby under gdb with a longer input:

Text
-0.5555555555555555555;0

Breaking on parse.y:2885, the node's cdr contents show that filename_index has been set to 13621, which is two 5 characters interpreted as an integer:

Text
(gdb) x/16hd yyvsp[0].nd->cdr
0x79162c:       11824   13621   13621   13621   13621   13621   13621   13621
0x79163c:       13621   13621   53      0       52      0       0       0
(gdb) p yyvsp[0].nd->cdr->filename_index
$21 = 13621

Breaking at codegen.c:1230, the same value is visible on the tree being processed:

Text
(gdb) p tree->filename_index
$22 = 13621

This eventually leads to the assert failing.

Root cause

In the NODE_NEGATE case, codegen recurses into the argument of the node without verifying that the argument is a valid node. The recursive call then reads car as a node type and cdr as node data, and uses filename_index and lineno as if they had been set by the parser. When the negation result is unused, the code path taken is the one that performs this unchecked recursion.

The researcher notes that this creates an opportunity for the attacker to control further code generation, though it might not be possible to place a valid node type in car with the current codebase. What can be controlled is filename_index, and that is what makes the assertion on line 135 of debug.c fail. The impact is therefore demonstrated as a crash rather than as controlled bytecode generation.

Impact

The demonstrated impact is a crash: a short piece of source causes the compiler to abort via an assertion failure. The report frames the wider risk as possible arbitrary bytecode generation, but explicitly hedges that placing a valid node type in car may not be possible with the current codebase. The severity assigned by the program was low.

Fix

The proposed fix is to ensure tree->car is a valid node before calling codegen on tree in the NODE_NEGATE case. The patch adds a bounds check against NODE_LAST:

Diff
diff --git a/mrbgems/mruby-compiler/core/codegen.c b/mrbgems/mruby-compiler/core/codegen.c
index 90bafb3..9d47cca 100644
--- a/mrbgems/mruby-compiler/core/codegen.c
+++ b/mrbgems/mruby-compiler/core/codegen.c
@@ -2232,7 +2232,9 @@ codegen(codegen_scope *s, node *tree, int val)
     nt = (intptr_t)tree->car;
     tree = tree->cdr;
     if (!val) {
-        codegen(s, tree, NOVAL);
+        if (tree && (intptr_t)tree->car < NODE_LAST) {
+          codegen(s, tree, NOVAL);
+        }
         break;
     }
     switch (nt) {

Variants to test

  • Other unary or prefix operators whose result can be discarded, such as unary plus or bitwise complement, followed by a statement separator and a second expression. A positive result is an assertion failure or a crash in the compiler.
  • Numeric literals with long digit runs after a discarded unary operator, as in the gdb input, to see whether the digits are interpreted as a filename_index and reach the same assertion.
  • Other compiler paths that recurse into a child node without validating its type. A positive result is a crash or a corrupted field visible in a debugger.

Hunting notes

This class of bug lives in compilers and interpreters that build an intermediate tree and then walk it without validating node types, particularly on paths where a value is discarded. The signal during review is a recursive call into a child node guarded only by an assumption about the node's shape.

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

What happened, in plain words

mruby is a small version of the Ruby programming language that other programs can embed inside themselves. Like any language, it has to turn the text a programmer writes into instructions the computer can run. The part that does this is called a compiler. This report is about a mistake in that compiler: a very short piece of Ruby source, just a few characters, makes the compiler crash instead of producing a program.

To understand the mistake you need one idea: before running anything, the compiler builds a tree-shaped map of the program. Each branch of the tree is a labelled box. One label might mean "add these two things", another might mean "this is a minus sign in front of a number". The compiler then walks the tree and writes out the final instructions, a step called code generation. The bug is that on one particular kind of box, the minus-sign box, the compiler walks into the box without first checking that what is inside really is a proper box. It then reads random-looking values as if they were labels and line numbers, and later a safety check in the program notices something impossible and stops everything.

The demonstrated effect is a crash: the program stops working. The report also suggests that in principle an attacker might be able to steer the compiler into producing arbitrary instructions, but it is honest that this may not be reachable with the current code.

Background: what mruby is and what a compiler does

mruby is an embeddable Ruby implementation. "Embeddable" means it is designed to be built into another application rather than run on its own, so an app can offer Ruby scripting to its users. It comes with its own compiler.

The compiler works in two stages:

  1. A node is a small record describing one piece of the program: a number, a variable, an operation, and so on. In mruby's C code, each node has a car member holding the node's type, a cdr member holding further nodes or data, and fields called filename_index and lineno recording which file and line the node came from.
  2. Code generation. A function called codegen walks the tree and emits bytecode, the low-level instructions the interpreter executes.

The report concerns one node type, NODE_NEGATE, which represents a unary minus, the minus sign placed in front of a value as in -5. Normally the compiler generates code for the value being negated and then emits the negation. The flaw appears when the result of the negation is not used, that is, when codegen is called with NOVAL, meaning "I do not need a value back from this".

A useful comparison: imagine a postal sorting office. Each parcel has a label saying what is inside and where it came from. The sorter trusts the label and sends the parcel down the matching chute. If someone hands the sorter an unlabelled object, the sorter still reads whatever is written on it as if it were a label, and parcels end up in the wrong place. Here the "label" is the node type in car, and the "return address" is filename_index.

Setup

The report does not describe any account, role or remote service. Everything happens locally on the researcher's own machine. The proof of concept is a small source file run either with the mruby interpreter or with a sandbox binary that ships with the engine. The researcher also used gdb, a debugger, to pause the program at chosen points and inspect the tree while it was being parsed and compiled.

Finding it

The researcher states that not using the result of NODE_NEGATE leads to incorrect code generation, which could possibly result in arbitrary bytecode generation. In its current state the bug produces a crash through a SIGABRT, which is the signal a program receives when it aborts itself, here caused by an assert failure. An assert is a check a programmer writes into the code saying "this must always be true"; if it is ever false, the program stops immediately rather than continuing in an unknown state.

The flaw was introduced in commit [redacted]. A commit is a recorded change in a code repository, so this identifies the exact edit that brought the bug in.

The underlying problem is that codegen is called recursively on the argument of NODE_NEGATE without checking whether it is a valid node. Recursion means a function calling itself; here codegen calls itself on the thing being negated. codegen assumes its tree argument is a valid node: the node type is stored under the car member, further nodes or data under the cdr member, and filename_index and lineno are set properly. Passing something that is not a valid node breaks those assumptions.

Exploitation

Step 1: the minimal crashing input

The proof of concept is a single line of Ruby source:

Ruby
-0E00;0

Line by line:

  • -0E00 is a number written in scientific notation, zero times ten to the power zero, with a unary minus in front of it. The minus makes it a NODE_NEGATE.
  • ; is a statement separator, so the next part is a separate expression.
  • 0 is a second expression, and its value is what the program would return.

Because the result of the negation is thrown away (nothing uses it), codegen is invoked on the negated operand with NOVAL, which is the path that triggers the bug.

Step 2: run it

The file is saved as assert_failure.rb and executed in either of two ways:

Bash
mruby assert_failure.rb
  • mruby is the interpreter binary.
  • assert_failure.rb is the file just created.
Bash
sandbox assert_failure.rb
  • sandbox is the engine's own binary, which runs the same file in the environment the engine provides.

Both cause a crash via an assert failure. The output shown in the report is:

Text
ruby: ext/mruby_engine/mruby/src/debug.c:135: mrb_debug_info_append_file: Assertion `irep->filename' failed.
zsh: abort      mruby-engine/bin/sandbox assert_failure.rb

Line by line:

  • The first line says the program stopped in debug.c at line 135, inside a function called mrb_debug_info_append_file, because the assertion irep->filename was false.
  • The second line is the shell reporting that the process was aborted.

Step 3: observing the corrupted field

To understand why the assertion fails, the researcher ran mruby under gdb with a longer input:

Text
-0.5555555555555555555;0

This is the same shape as before: a negated number, a separator, and a second expression.

Breaking on parse.y:2885, that is, pausing the program at that line of the parser, the node's cdr contents show that filename_index has been set to 13621, which is two 5 characters interpreted as an integer:

Text
(gdb) x/16hd yyvsp[0].nd->cdr
0x79162c:       11824   13621   13621   13621   13621   13621   13621   13621
0x79163c:       13621   13621   53      0       52      0       0       0
(gdb) p yyvsp[0].nd->cdr->filename_index
$21 = 13621

Line by line:

  • x/16hd is a gdb command that displays 16 half-word (two-byte) values in decimal starting at an address. It shows the raw contents of the node's cdr area.
  • The two address lines are the memory dump. The repeated 13621 values are the digit pairs from the long run of 5s being read as numbers.
  • p yyvsp[0].nd->cdr->filename_index asks gdb to print the filename_index field of that node, and it answers 13621.

Breaking at codegen.c:1230, the same value is visible on the tree being processed:

Text
(gdb) p tree->filename_index
$22 = 13621

Line by line:

  • p tree->filename_index prints the filename_index of the node that codegen is currently working on.
  • The answer is again 13621, confirming that the corrupted value travels from the parser into code generation.

Root cause

In the NODE_NEGATE case, codegen recurses into the argument of the node without verifying that the argument is a valid node. The recursive call then reads car as a node type and cdr as node data, and uses filename_index and lineno as if they had been set by the parser. When the negation result is unused, the code path taken is the one that performs this unchecked recursion.

The researcher notes that this creates an opportunity for the attacker to control further code generation, though it might not be possible to place a valid node type in car with the current codebase. What can be controlled is filename_index, and that is what makes the assertion on line 135 of debug.c fail. The impact is therefore demonstrated as a crash rather than as controlled bytecode generation.

Impact

The immediate, demonstrated impact is a denial of service: a short piece of source causes the compiler to abort via an assertion failure. The report frames the wider risk as possible arbitrary bytecode generation, meaning an attacker could in theory make the compiler emit instructions of their choosing, but it explicitly hedges that placing a valid node type in car may not be possible with the current codebase. The severity assigned by the program was low.

Fix

The proposed fix is to ensure tree->car is a valid node before calling codegen on tree in the NODE_NEGATE case. The patch adds a bounds check against NODE_LAST, a constant marking the end of the list of valid node types:

Diff
diff --git a/mrbgems/mruby-compiler/core/codegen.c b/mrbgems/mruby-compiler/core/codegen.c
index 90bafb3..9d47cca 100644
--- a/mrbgems/mruby-compiler/core/codegen.c
+++ b/mrbgems/mruby-compiler/core/codegen.c
@@ -2232,7 +2232,9 @@ codegen(codegen_scope *s, node *tree, int val)
     nt = (intptr_t)tree->car;
     tree = tree->cdr;
     if (!val) {
-        codegen(s, tree, NOVAL);
+        if (tree && (intptr_t)tree->car < NODE_LAST) {
+          codegen(s, tree, NOVAL);
+        }
         break;
     }
     switch (nt) {

Line by line:

  • The diff --git and index lines identify the file being changed and the two versions of it.
  • The --- and +++ lines name the old and new file.
  • The @@ line says the change sits around line 2232 of codegen.c.
  • nt = (intptr_t)tree->car; reads the node type from car.
  • tree = tree->cdr; moves tree on to the node's data.
  • if (!val) { is the branch taken when no value is needed, the path that triggers the bug.
  • The removed line codegen(s, tree, NOVAL); is the unchecked recursive call.
  • The added lines wrap that call in a check: tree must not be null, and its car value must be less than NODE_LAST, that is, it must be one of the known node types. Only then is codegen called.
  • break; and switch (nt) { are unchanged context showing where the branch ends.

Variants to test

  • Other unary or prefix operators whose result can be discarded, such as unary plus or bitwise complement, followed by a statement separator and a second expression. A positive result is an assertion failure or a crash in the compiler.
  • Numeric literals with long digit runs after a discarded unary operator, as in the gdb input, to see whether the digits are interpreted as a filename_index and reach the same assertion.
  • Other compiler paths that recurse into a child node without validating its type. A positive result is a crash or a corrupted field visible in a debugger.

Hunting notes

This class of bug lives in compilers and interpreters that build an intermediate tree and then walk it without validating node types, particularly on paths where a value is discarded. The signal during review is a recursive call into a child node guarded only by an assumption about the node's shape.

Glossary

  • mruby: a small, embeddable implementation of the Ruby programming language with its own compiler.
  • Compiler: a program that turns source text into instructions a computer can execute.
  • Bytecode: the low-level instructions an interpreter runs, produced by the compiler.
  • Parser: the part of the compiler that reads source text and builds a tree of nodes.
  • Node: a small record in the compiler's tree describing one piece of the program, with a type and associated data.
  • car / cdr: the two members of a node; car holds the node type, cdr holds further nodes or data.
  • filename_index / lineno: fields on a node recording which source file and line it came from.
  • NODE_NEGATE: the node type representing a unary minus, a minus sign in front of a value.
  • codegen: the compiler function that walks the node tree and emits bytecode.
  • NOVAL: a flag passed to codegen meaning the caller does not need a value back.
  • Recursion: a function calling itself.
  • assert: a check written into code that stops the program if a condition is ever false.
  • SIGABRT: the signal a program receives when it aborts itself.
  • gdb: a debugger that lets you pause a program and inspect its memory and variables.
  • Commit: a recorded change in a code repository, identified by a hash.
  • NODE_LAST: a constant marking the end of the list of valid node types.
  • Denial of service: making a system unavailable to its users, for example by crashing it.
  • Arbitrary bytecode generation: making the compiler emit instructions of an attacker's choosing.
  • Bounty: a payment a program makes to a researcher who reports a valid security bug.
  • Severity: a rating of how serious a bug is, here low.

More by dkasak

View all

6 more disclosed reports, best first.

More from shopify-scripts

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.