Skip to content
Memory corruption Disclosed report Advanced

Segfault and/or potential unwanted (byte)code execution with "break" and "||=" inside a loop

The mruby compiler generated an out-of-bounds jump instruction when a `||=` assignment to a constant appeared inside a loop with `break`, because a rescue loop context leaked out of the assignment code generation. An attacker supplying such a Ruby program could crash the interpreter or cause it to execute spurious bytecode, a limited form of unwanted code execution.

dkasak Follow

Originally disclosed on HackerOne

Bounty$10,000 High 8.6 View original
  • Triaged in 5 hours
  • Fixed in 7 days
  • Paid in 28 days
  • Disclosed after 28 days

Introduction

Certain invalid inputs (invalid Ruby programs) crash mruby and mruby_engine (including the parent MRI VM). The programs always involve the ||= operator, loops and the break keyword.

Proof of Concept

crash.rb

A ||= break while break
  1. Save the above code as crash.rb
  2. Run either: a) mruby crash.rb b) sandbox crash.rb
  3. Both cause a segmentation fault.

Discussion

Everything below assumes the latest master of the mruby repository as of Nov 18th, which is commit 0ff3ae1fbaed62010c54c43235e29cdc85da2f78.

The above crashing example isn't the only one that we've managed to produce but is the minimal one so far. An infinite family of programs is able to exploit this bug to crash the interpreter, execute spurious bytecode that wasn't generated for the current program or even set the machine instruction pointer to some junk value (making this a limited form of unwated code execution, even though the executed code isn't arbitrary).

The generated AST and bytecode for the crashing case is as follows:

mruby 1.2.0 (2015-11-17)
00001 NODE_SCOPE:
00001   NODE_BEGIN:
00001     NODE_WHILE:
00001       cond:
00001         NODE_BREAK:
00001       body:
00001         NODE_OP_ASGN:
00001           lhs:
00001             NODE_CONST A
00001           op='||' (666)
00001           NODE_BREAK:
irep 0x16b2970 nregs=2 nlocals=1 pools=0 syms=1 reps=0
file: crash.rb
    1 000 OP_JMP    010
    1 001 OP_ONERR  005
    1 002 OP_GETCONST       R1      :A
    1 003 OP_POPERR 1
    1 004 OP_JMP    007
    1 005 OP_RESCUE R1
    1 006 OP_LOADF  R1
    1 007 OP_JMPIF  R1      010
    1 008 OP_JMP    008
    1 009 OP_SETCONST       :A      R1
    1 010 OP_JMP    018
    1 011 OP_JMPIF  R1      001
    1 012 OP_LOADNIL        R1
    1 013 OP_STOP

The odd thing to notice here is that the OP_JMP at 010 jumps beyond the last instruction. This is what leads to a potential execution of spurious bytecode since there may be valid opcodes beyond the end of the iseq array of the current irep (and indeed, we've seen this happen).

Furthermore, the index of the instruction onto which the invalid OP_JMP jumps to is equal I + A where I is the index of the instruction the OP_JMP at 000 jumps to (in this case 010) and A is the index of an OP_JMP instruction located prior to the invalid one (so in this case 010 + 008 = 018). Since each additional break inserted into the code inserts an additional OP_JMP instruction, this implies that the argument of the invalid OP_JMP can be increased almost without bounds (limited only by memory consumption and/or the maximum argument to OP_JMP instructions, which is 0xffff >> 1 = 32767).

As an example, the code:

larger.rb

A ||= break break break break while break

Yields the following bytecode:

file: larger.rb 1 000 OP_JMP 013 1 001 OP_ONERR 005 1 002 OP_GETCONST R1 :A 1 003 OP_POPERR 1 1 004 OP_JMP 007 1 005 OP_RESCUE R1 1 006 OP_LOADF R1 1 007 OP_JMPIF R1 013 1 008 OP_JMP 008 1 009 OP_JMP 017 1 010 OP_JMP 019 1 011 OP_JMP 021 1 012 OP_SETCONST :A R1 1 013 OP_JMP 024 1 014 OP_JMPIF R1 001 1 015 OP_LOADNIL R1 1 016 OP_STOP

After the jump is made, the memory location might contain a valid mruby instruction or even something with an opcode larger than the number of opcodes contained in the optable in vm.c. Since the code in mrb_vm_exec jumps to addresses contained in the optable, indexed by the opcode number, this leads to a limited form of unwanted code execution, since memory locations after the optable may contain pointers to executable code by accident.

It is interesting to note that a very similar program doesn't cause a crash:

non-crash.rb

a ||= break while break

The only difference from the crashing case is the use of a lowercase variable name instead of an uppercase (so a non-constant, in Ruby terms).

Another non-crashing case is the following:

non-crash-other.rb

A &&= break while break

The only difference here is the use of another assignment operator — &&, instead of ||.

This gives us a hint as to where the problem is. The invalid jump length is ultimately set during code generation for the NODE_WHILE node of the AST in codegen.c, line 1426. Specifically, the jump lengths are adjusted after the loop is generated, on line 1438 of the same file, during the call of the function loop_pop().

When this function is executed in the debugger when run on the crash.rb case, it may be noticed that the s->loop variable, which contains the loop context, contains two loops inside one another instead of only one: a LOOP_NORMAL (which is generated by the while) and a LOOP_RESCUE. The latter is generated during code generation for NODE_OP_ASGN, starting at line 1724 of codegen.c. Here we encounter this interesting special case:

  if ((len == 2 && name[0] == '|' && name[1] == '|') &&
      ((intptr_t)tree->car->car == NODE_CONST ||
       (intptr_t)tree->car->car == NODE_CVAR)) {

This explains why the problem only happens only when using the ||= operator on Ruby constants. It is here that an additional LOOP_RESCUE loop context is created, and it is using this context that is used later on by loop_pop/dispatch_linked to generate the final arguments to the jump instructions.

Since this "loop" is generated simply to catch potential NameError exceptions generated when an unexisting constant is reference, it seems that this loop context shouldn't escape the generation of the code for the assignment operator.

Solution

Therefore, the solution we chose was to pop this loop context after the assignment code is generated. This makes the loop_pop/dispatch_linked function calls inside the while code generation operate on the loop context for the while loop instead and fixes the generated jump.

undef-constant-or-assign.patch

diff --git a/mrbgems/mruby-compiler/core/codegen.c b/mrbgems/mruby-compiler/core/codegen.c
index 9b064b8..bbe0f51 100644
--- a/mrbgems/mruby-compiler/core/codegen.c
+++ b/mrbgems/mruby-compiler/core/codegen.c
@@ -1746,6 +1746,7 @@ codegen(codegen_scope *s, node *tree, int val)
        genop(s, MKOP_A(OP_RESCUE, exc));
        genop(s, MKOP_A(OP_LOADF, exc));
        dispatch(s, noexc);
+        loop_pop(s, val);
    }
    else if ((intptr_t)tree->car->car == NODE_CALL) {
        node *n = tree->car->cdr;

With the above patch, we were unable to crash the VM through this bug nor generated any more jumps with invalid jump lengths. Furthermore, all tests pass successfully.

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

Context

mruby is an embeddable Ruby implementation, and mruby_engine is the sandbox that runs mruby programs inside a host. The report concerns the compiler and VM of mruby: the code generator in codegen.c and the interpreter loop mrb_vm_exec in vm.c. The feature under scrutiny is ordinary Ruby syntax: the ||= operator applied to a constant, combined with a while loop and the break keyword. A valid program using these constructs should compile to bytecode whose jumps stay inside the current instruction sequence. The researcher found that certain invalid programs (programs that are not valid Ruby) break that invariant and crash the interpreter.

The report was filed against the shopify-scripts program on HackerOne, rated high severity with a CVSS of 8.6, classified as Uncontrolled Resource Consumption, and paid a bounty of 10,000 USD. It was disclosed on 16 December 2016.

Setup

The work was done against the latest master of the mruby repository as of 18 November, commit [redacted]. The interpreter identifies itself as:

Text
mruby 1.2.0 (2015-11-17)

Two execution paths were used to reproduce the crash: the standalone interpreter and the sandbox.

  1. mruby crash.rb runs the program directly under mruby.
  2. sandbox crash.rb runs it inside mruby_engine.

Both paths crash, and the report notes that the crash also takes down the parent MRI VM, meaning the host process embedding the engine is affected, not just the sandboxed program.

Finding it

The researcher produced a family of invalid Ruby programs that crash mruby. The minimal example is a single line:

Ruby
A ||= break while break

Saved as crash.rb and run through either mruby crash.rb or sandbox crash.rb, it causes a segmentation fault. The report states that this is the minimal crashing example found so far, but not the only one: an infinite family of programs exploits the same bug.

What made the behaviour worth pursuing was the range of outcomes. The programs can crash the interpreter, execute spurious bytecode that was not generated for the current program, or even set the machine instruction pointer to a junk value. The researcher characterises this as a limited form of unwanted code execution, with the explicit hedge that the executed code is not arbitrary.

Two near-identical programs do not crash, and the differences between them point at the cause:

Ruby
a ||= break while break

This is non-crash.rb. The only change from the crashing case is a lowercase variable name instead of an uppercase one, so a non-constant rather than a constant in Ruby terms.

Ruby
A &&= break while break

This is non-crash-other.rb. Here the only change is the assignment operator: &&= instead of ||=.

So the crash needs three things together: the ||= operator, a constant on the left-hand side, and the loop with break.

Exploitation

Step 1: compile the minimal program and inspect the output

The generated AST and bytecode for the crashing case are:

Text
mruby 1.2.0 (2015-11-17)
00001 NODE_SCOPE:
00001   NODE_BEGIN:
00001     NODE_WHILE:
00001       cond:
00001         NODE_BREAK:
00001       body:
00001         NODE_OP_ASGN:
00001           lhs:
00001             NODE_CONST A
00001           op='||' (666)
00001           NODE_BREAK:
irep 0x16b2970 nregs=2 nlocals=1 pools=0 syms=1 reps=0
file: crash.rb
    1 000 OP_JMP    010
    1 001 OP_ONERR  005
    1 002 OP_GETCONST       R1      :A
    1 003 OP_POPERR 1
    1 004 OP_JMP    007
    1 005 OP_RESCUE R1
    1 006 OP_LOADF  R1
    1 007 OP_JMPIF  R1      010
    1 008 OP_JMP    008
    1 009 OP_SETCONST       :A      R1
    1 010 OP_JMP    018
    1 011 OP_JMPIF  R1      001
    1 012 OP_LOADNIL        R1
    1 013 OP_STOP

The AST shows the structure: a NODE_WHILE whose condition is a NODE_BREAK and whose body is a NODE_OP_ASGN on the constant A with operator ||, whose right-hand side is another NODE_BREAK.

The anomaly is in the bytecode. The OP_JMP at index 010 jumps to 018, which is beyond the last instruction of the sequence (013). The report calls this out directly: the jump goes past the end of the iseq array of the current irep, and since memory beyond that array may contain valid opcodes, this is what allows spurious bytecode to be executed. The researcher confirms having seen that happen.

Step 2: work out how the jump target is computed

The index the invalid OP_JMP lands on equals I + A, where I is the index the OP_JMP at 000 jumps to (010 in this case) and A is the index of an OP_JMP instruction located before the invalid one (008 here), giving 010 + 008 = 018. Each additional break inserted into the program inserts an additional OP_JMP instruction, so the argument of the invalid jump can be increased almost without bounds. The only limits are memory consumption and the maximum argument of an OP_JMP instruction, which the report gives as 0xffff >> 1 = 32767.

Step 3: confirm the scaling with a larger program

The example that demonstrates the growth:

Ruby
A ||= break break break break while break

Saved as larger.rb, it yields:

Text
file: larger.rb
    1 000 OP_JMP        013
    1 001 OP_ONERR      005
    1 002 OP_GETCONST   R1      :A
    1 003 OP_POPERR     1
    1 004 OP_JMP        007
    1 005 OP_RESCUE     R1
    1 006 OP_LOADF      R1
    1 007 OP_JMPIF      R1      013
    1 008 OP_JMP        008
    1 009 OP_JMP        017
    1 010 OP_JMP        019
    1 011 OP_JMP        021
    1 012 OP_SETCONST   :A      R1
    1 013 OP_JMP        024
    1 014 OP_JMPIF      R1      001
    1 015 OP_LOADNIL    R1
    1 016 OP_STOP

The OP_JMP at 013 now targets 024, past the final instruction at 016. The extra break keywords have added OP_JMP instructions at 009, 010 and 011, and the out-of-range target has grown accordingly.

Step 4: reason about what happens after the jump

Once the jump is taken, the memory location it lands on may hold a valid mruby instruction, or something whose opcode number is larger than the number of opcodes in the optable in vm.c. The code in mrb_vm_exec jumps to addresses stored in optable, indexed by opcode number. If the opcode read from beyond the end of the sequence is out of range, the lookup reads memory past the end of optable, and those locations may by accident contain pointers to executable code. That is the mechanism behind the limited unwanted code execution.

Step 5: narrow down the cause with the non-crashing variants

The lowercase variant a ||= break while break does not crash, and neither does A &&= break while break. The difference between the crashing and non-crashing cases is the constant versus a non-constant left-hand side, and ||= versus &&=. This points the investigation at code generation for NODE_WHILE in codegen.c, line 1426. The jump lengths are adjusted after the loop is generated, on line 1438 of the same file, during the call to loop_pop().

Running that function in a debugger on the crash.rb case shows that s->loop, the variable holding the loop context, contains two loops nested inside one another instead of one: a LOOP_NORMAL, generated by the while, and a LOOP_RESCUE. The latter is generated during code generation for NODE_OP_ASGN, starting at line 1724 of codegen.c, where this special case appears:

C
  if ((len == 2 && name[0] == '|' && name[1] == '|') &&
      ((intptr_t)tree->car->car == NODE_CONST ||
       (intptr_t)tree->car->car == NODE_CVAR)) {

This explains why the problem only occurs with ||= on Ruby constants. The extra LOOP_RESCUE context is created here, and it is this context that loop_pop/dispatch_linked later use to generate the final arguments of the jump instructions. The rescue loop exists only to catch potential NameError exceptions raised when a non-existent constant is referenced, so it should not escape the generation of the code for the assignment operator.

Root cause

The ||= code generation for constants (and class variables) pushes a LOOP_RESCUE loop context so that a NameError from reading an undefined constant can be caught. That context is not popped when the assignment code generation finishes. When the enclosing while is generated, loop_pop/dispatch_linked operate on the leftover rescue context instead of the while loop's own context, and the jump arguments they patch are computed against the wrong loop. The result is an OP_JMP whose target lies beyond the end of the current iseq. Because mrb_vm_exec dispatches through optable indexed by opcode, an out-of-range opcode read from beyond the sequence can send execution to an address that was never meant to be a handler.

Impact

An invalid Ruby program of this shape crashes mruby and mruby_engine, and the crash propagates to the parent MRI VM. Beyond denial of service, the same bug can execute spurious bytecode that was not generated for the current program, or set the machine instruction pointer to a junk value. The researcher describes this as a limited form of unwanted code execution and is explicit that the executed code is not arbitrary. The reachable jump offset grows with each added break, bounded by memory and by the OP_JMP argument limit of 32767.

Fix

The chosen fix is to pop the loop context after the assignment code is generated, so that the loop_pop/dispatch_linked calls inside the while code generation operate on the while loop's context and the generated jump is correct. The patch:

Diff
diff --git a/mrbgems/mruby-compiler/core/codegen.c b/mrbgems/mruby-compiler/core/codegen.c
index 9b064b8..bbe0f51 100644
--- a/mrbgems/mruby-compiler/core/codegen.c
+++ b/mrbgems/mruby-compiler/core/codegen.c
@@ -1746,6 +1746,7 @@ codegen(codegen_scope *s, node *tree, int val)
         genop(s, MKOP_A(OP_RESCUE, exc));
         genop(s, MKOP_A(OP_LOADF, exc));
         dispatch(s, noexc);
+        loop_pop(s, val);
     }
     else if ((intptr_t)tree->car->car == NODE_CALL) {
         node *n = tree->car->cdr;

With the patch applied, the researcher was unable to crash the VM through this bug and no further jumps with invalid jump lengths were generated. All tests passed.

Variants to test

  • Replace the constant with a class variable (@@a ||= break while break). The special case in codegen.c covers NODE_CVAR as well as NODE_CONST, so the same leftover rescue context should be reachable. A positive result is a crash or an OP_JMP whose target lies past the last instruction of the irep.
  • Add more break keywords to the right-hand side, as in larger.rb. A positive result is a jump target that grows with each added break, up to the OP_JMP argument limit of 32767.
  • Try other constructs that generate a rescue loop context around an assignment and then interact with an enclosing loop's loop_pop/dispatch_linked. A positive result is a loop context stack that is deeper than the source nesting suggests when inspected in a debugger.
  • Run the same programs under both mruby and the sandbox. A positive result is a crash in both, with the host process affected as well.

Hunting notes

This class of bug lives in compilers and interpreters that emit jump instructions and patch their offsets after the fact, especially where a temporary context (here a rescue loop) is pushed for one construct and popped later by an unrelated one. The signals are small, invalid programs that crash the interpreter, and near-identical programs that do not: changing a constant to a local variable, or ||= to &&=, isolating the exact syntax that triggers the fault. Disassembling the generated bytecode and looking for jump targets beyond the end of the instruction sequence is the quickest confirmation. The researcher showed impact by demonstrating the segmentation fault, the out-of-range jump target and its growth with additional break keywords, and by reasoning that an out-of-range opcode read through optable may lead to unwanted code execution.

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

What happened, in plain words

A security researcher found that a small, deliberately broken Ruby program could crash a piece of software called mruby, and could do more than crash it: in some cases it could make the program jump to a place in memory it was never meant to reach. The report was filed against the shopify-scripts program on HackerOne, rated high severity with a CVSS of 8.6, classified as Uncontrolled Resource Consumption, and paid a bounty of 10,000 USD. It was disclosed on 16 December 2016.

To follow this, you only need a few ideas:

  • Ruby is a programming language. People write instructions in it, and a program called an interpreter reads those instructions and carries them out.
  • mruby is a small version of Ruby designed to be embedded inside other software. mruby_engine is a sandbox: a walled-off area where mruby programs run inside a host program, so that whatever the small program does stays contained.
  • A compiler is the part that turns the text you wrote into a lower-level list of simple steps, called bytecode. The part that actually performs those steps is the VM (virtual machine) or interpreter.
  • A segmentation fault (segfault) is the operating system stopping a program because it tried to touch memory it is not allowed to touch. It is the computer equivalent of someone reading a page number that does not exist in a book and the librarian shutting the reading room down.

The report concerns the compiler and VM of mruby: the code generator in codegen.c and the interpreter loop mrb_vm_exec in vm.c. The feature under scrutiny is ordinary Ruby syntax: the ||= operator applied to a constant, combined with a while loop and the break keyword. A valid program using these constructs should compile to bytecode whose jumps stay inside the current instruction sequence. The researcher found that certain invalid programs (programs that are not valid Ruby) break that invariant and crash the interpreter.

Setup

The work was done against the latest master of the mruby repository as of 18 November, commit [redacted]. A commit is a saved snapshot of a code project, identified by a long string of characters, so anyone can refer to exactly the same version. The interpreter identifies itself as:

Text
mruby 1.2.0 (2015-11-17)

This line is the version banner: the name of the software, its version number, and a date. Knowing the exact version matters because a bug may exist in one version and be fixed in the next.

Two execution paths were used to reproduce the crash: the standalone interpreter and the sandbox.

  1. mruby crash.rb runs the program directly under mruby. Here mruby is the program you start, and crash.rb is the file containing the Ruby code. The .rb ending is the usual file extension for Ruby source files.
  2. sandbox crash.rb runs it inside mruby_engine. Same file, but now it goes through the sandbox wrapper instead of the plain interpreter.

Both paths crash, and the report notes that the crash also takes down the parent MRI VM, meaning the host process embedding the engine is affected, not just the sandboxed program. MRI is the standard, main Ruby implementation; the "parent" is the bigger program that had loaded mruby inside itself. If the small embedded engine can crash its host, the sandbox wall has failed.

Finding it

The researcher produced a family of invalid Ruby programs that crash mruby. The minimal example is a single line:

Ruby
A ||= break while break

Line by line, in plain words:

  • A is a constant: in Ruby, a name that starts with an uppercase letter. Constants are meant to hold a value that does not change.
  • ||= is the "or-assign" operator. A ||= something means: if A is not set yet (or is false), assign something to it; otherwise leave it alone. It is a shortcut for "set this only if it is missing".
  • break is a keyword that means "leave the nearest loop right now".
  • while break is a loop whose condition is the word break. A loop repeats its body while a condition is true; here the condition itself is a jump out of the loop, which is nonsense in normal Ruby.
  • Putting it together, the line is not a valid Ruby program. That is the point: the researcher is feeding the compiler something it should reject or handle safely, and instead it mishandles it.

Saved as crash.rb and run through either mruby crash.rb or sandbox crash.rb, it causes a segmentation fault. The report states that this is the minimal crashing example found so far, but not the only one: an infinite family of programs exploits the same bug.

What made the behaviour worth pursuing was the range of outcomes. The programs can crash the interpreter, execute spurious bytecode that was not generated for the current program, or even set the machine instruction pointer to a junk value. The researcher characterises this as a limited form of unwanted code execution, with the explicit hedge that the executed code is not arbitrary. Two of those terms need unpacking:

  • Bytecode is the list of simple internal steps the compiler produced. "Spurious bytecode" means the interpreter ends up running steps that belong to some other program, or to no program at all, rather than the steps it generated for this one.
  • The instruction pointer is the internal bookmark that says which step the processor is about to run next. Setting it to a junk value means the machine is told to continue at an address that means nothing, like sending a letter to a house number that does not exist.

Two near-identical programs do not crash, and the differences between them point at the cause:

Ruby
a ||= break while break

This is non-crash.rb. The only change from the crashing case is a lowercase variable name instead of an uppercase one, so a non-constant rather than a constant in Ruby terms. A variable is a named box that holds a value and can be changed; a constant is the uppercase cousin that is not supposed to change. The compiler treats the two differently, and that difference is the clue.

Ruby
A &&= break while break

This is non-crash-other.rb. Here the only change is the assignment operator: &&= instead of ||=. &&= is the "and-assign" operator: assign only if the left side is already set and true. Again, the compiler takes a different path for this operator, and that path does not crash.

So the crash needs three things together: the ||= operator, a constant on the left-hand side, and the loop with break.

Exploitation

Step 1: compile the minimal program and inspect the output

The generated AST and bytecode for the crashing case are:

Text
mruby 1.2.0 (2015-11-17)
00001 NODE_SCOPE:
00001   NODE_BEGIN:
00001     NODE_WHILE:
00001       cond:
00001         NODE_BREAK:
00001       body:
00001         NODE_OP_ASGN:
00001           lhs:
00001             NODE_CONST A
00001           op='||' (666)
00001           NODE_BREAK:
irep 0x16b2970 nregs=2 nlocals=1 pools=0 syms=1 reps=0
file: crash.rb
    1 000 OP_JMP    010
    1 001 OP_ONERR  005
    1 002 OP_GETCONST       R1      :A
    1 003 OP_POPERR 1
    1 004 OP_JMP    007
    1 005 OP_RESCUE R1
    1 006 OP_LOADF  R1
    1 007 OP_JMPIF  R1      010
    1 008 OP_JMP    008
    1 009 OP_SETCONST       :A      R1
    1 010 OP_JMP    018
    1 011 OP_JMPIF  R1      001
    1 012 OP_LOADNIL        R1
    1 013 OP_STOP

This output has two halves. The first half is the AST, short for abstract syntax tree: a diagram of how the compiler understood the program's structure. Read it as an outline:

  • NODE_SCOPE and NODE_BEGIN are the outer wrappers: the whole program, and the start of its statements.
  • NODE_WHILE is the loop. It has a cond: (condition) and a body: (what repeats).
  • The condition is NODE_BREAK, a break statement.
  • The body is NODE_OP_ASGN, an assignment with an operator. Its left-hand side (lhs:) is NODE_CONST A, the constant A. Its operator is ||. Its right-hand side is another NODE_BREAK.

So the AST shows the structure: a NODE_WHILE whose condition is a NODE_BREAK and whose body is a NODE_OP_ASGN on the constant A with operator ||, whose right-hand side is another NODE_BREAK.

The second half is the bytecode, the actual list of steps. Each line has a line number (1), a step number (000, 001, ...), an opcode (the name of the step, such as OP_JMP), and sometimes arguments. A few opcodes to know:

  • OP_JMP means "jump": continue at the step number given as its argument instead of the next one.
  • OP_GETCONST reads a constant; OP_SETCONST writes one.
  • OP_ONERR, OP_POPERR, OP_RESCUE and OP_LOADF are the machinery for catching errors (exceptions) that might happen while reading the constant.
  • OP_JMPIF jumps only if a condition is true.
  • OP_STOP ends the program.

The irep line is a header describing this block of bytecode: its memory address, how many registers and local variables it uses, and so on. file: crash.rb says which source file it came from.

The anomaly is in the bytecode. The OP_JMP at index 010 jumps to 018, which is beyond the last instruction of the sequence (013). The report calls this out directly: the jump goes past the end of the iseq array of the current irep, and since memory beyond that array may contain valid opcodes, this is what allows spurious bytecode to be executed. The researcher confirms having seen that happen. An array here is just a numbered list stored in memory; iseq is the list of instructions. Jumping past its end is like a table of contents telling you to turn to page 18 when the book only has 13 pages: whatever is printed on the next sheet of paper gets read as if it were part of the book.

Step 2: work out how the jump target is computed

The index the invalid OP_JMP lands on equals I + A, where I is the index the OP_JMP at 000 jumps to (010 in this case) and A is the index of an OP_JMP instruction located before the invalid one (008 here), giving 010 + 008 = 018. Each additional break inserted into the program inserts an additional OP_JMP instruction, so the argument of the invalid jump can be increased almost without bounds. The only limits are memory consumption and the maximum argument of an OP_JMP instruction, which the report gives as 0xffff >> 1 = 32767.

In plain terms: the wrong jump distance is not random. It is built from two numbers that the compiler already had, added together. Because every extra break adds another jump instruction, and each of those shifts the numbers, the researcher can make the bad target larger and larger. 0xffff is a hexadecimal number (65535 in ordinary counting), and >> 1 means "shift the bits one place to the right", which halves it. So the biggest jump distance the instruction format can express is 32767 steps.

Step 3: confirm the scaling with a larger program

The example that demonstrates the growth:

Ruby
A ||= break break break break while break

This is the same shape as before, but with four break keywords in a row on the right-hand side of ||=. Each one is another "leave the loop" statement, and each one makes the compiler emit another jump instruction. Saved as larger.rb, it yields:

Text
file: larger.rb
    1 000 OP_JMP        013
    1 001 OP_ONERR      005
    1 002 OP_GETCONST   R1      :A
    1 003 OP_POPERR     1
    1 004 OP_JMP        007
    1 005 OP_RESCUE     R1
    1 006 OP_LOADF      R1
    1 007 OP_JMPIF      R1      013
    1 008 OP_JMP        008
    1 009 OP_JMP        017
    1 010 OP_JMP        019
    1 011 OP_JMP        021
    1 012 OP_SETCONST   :A      R1
    1 013 OP_JMP        024
    1 014 OP_JMPIF      R1      001
    1 015 OP_LOADNIL    R1
    1 016 OP_STOP

The OP_JMP at 013 now targets 024, past the final instruction at 016. The extra break keywords have added OP_JMP instructions at 009, 010 and 011, and the out-of-range target has grown accordingly. The more break keywords, the further past the end the jump goes.

Step 4: reason about what happens after the jump

Once the jump is taken, the memory location it lands on may hold a valid mruby instruction, or something whose opcode number is larger than the number of opcodes in the optable in vm.c. The code in mrb_vm_exec jumps to addresses stored in optable, indexed by opcode number. If the opcode read from beyond the end of the sequence is out of range, the lookup reads memory past the end of optable, and those locations may by accident contain pointers to executable code. That is the mechanism behind the limited unwanted code execution.

Unpacking that: optable is a lookup table, like a restaurant menu where each dish has a number. The interpreter reads an opcode number and looks up the matching handler in the table. If the number read from beyond the end of the instruction list is bigger than the menu has entries, the lookup reads past the end of the menu and picks up whatever happens to be written there. A pointer is a memory address, a note saying "the code you want is over there". If the stray entry happens to look like a pointer, the interpreter follows it and runs code that was never meant to be a handler. That is why the researcher calls it a limited form of code execution: the interpreter can be steered to the wrong place, but the attacker does not get to choose arbitrary code.

Step 5: narrow down the cause with the non-crashing variants

The lowercase variant a ||= break while break does not crash, and neither does A &&= break while break. The difference between the crashing and non-crashing cases is the constant versus a non-constant left-hand side, and ||= versus &&=. This points the investigation at code generation for NODE_WHILE in codegen.c, line 1426. The jump lengths are adjusted after the loop is generated, on line 1438 of the same file, during the call to loop_pop().

In plain words: the compiler does not know the final jump distances while it is still writing the loop, because it does not yet know how long the loop will be. So it writes placeholder jumps and later goes back to fill in the real numbers. loop_pop() is the function that finishes a loop and patches those numbers. If it patches them using the wrong loop's information, the numbers come out wrong.

Running that function in a debugger on the crash.rb case shows that s->loop, the variable holding the loop context, contains two loops nested inside one another instead of one: a LOOP_NORMAL, generated by the while, and a LOOP_RESCUE. The latter is generated during code generation for NODE_OP_ASGN, starting at line 1724 of codegen.c, where this special case appears:

C
  if ((len == 2 && name[0] == '|' && name[1] == '|') &&
      ((intptr_t)tree->car->car == NODE_CONST ||
       (intptr_t)tree->car->car == NODE_CVAR)) {

A debugger is a tool that lets you pause a program mid-run and inspect its internal state, like stopping a film frame by frame to see what the actors are holding. A loop context is a small record the compiler keeps while it is working on a loop, holding the information needed to patch that loop's jumps later. The debugger showed two such records stacked up where there should be one.

Line by line, the C snippet says:

  • if ((len == 2 && name[0] == '|' && name[1] == '|') && checks whether the operator's name is exactly two characters long and both are the pipe character |, that is, whether the operator is ||.
  • ((intptr_t)tree->car->car == NODE_CONST || checks whether the left-hand side of the assignment is a constant.
  • (intptr_t)tree->car->car == NODE_CVAR)) { checks whether it is a class variable instead. A class variable is a variable shared by a whole class of objects, written with two at-signs in Ruby.
  • So the whole condition means: "if this is ||= applied to a constant or a class variable, take the special path".

This explains why the problem only occurs with ||= on Ruby constants. The extra LOOP_RESCUE context is created here, and it is this context that loop_pop/dispatch_linked later use to generate the final arguments of the jump instructions. The rescue loop exists only to catch potential NameError exceptions raised when a non-existent constant is referenced, so it should not escape the generation of the code for the assignment operator. A NameError is Ruby's complaint when you mention a name that has never been defined. Because reading a constant can fail that way, the compiler wraps the read in error-catching machinery, and that machinery needs its own loop context. The bug is that this temporary context is left behind after the assignment is compiled, and the enclosing while then mistakenly uses it.

Root cause

The ||= code generation for constants (and class variables) pushes a LOOP_RESCUE loop context so that a NameError from reading an undefined constant can be caught. That context is not popped when the assignment code generation finishes. When the enclosing while is generated, loop_pop/dispatch_linked operate on the leftover rescue context instead of the while loop's own context, and the jump arguments they patch are computed against the wrong loop. The result is an OP_JMP whose target lies beyond the end of the current iseq. Because mrb_vm_exec dispatches through optable indexed by opcode, an out-of-range opcode read from beyond the sequence can send execution to an address that was never meant to be a handler.

A simple comparison: imagine a builder who sets up scaffolding for one job, finishes, and forgets to take it down. The next worker assumes the scaffolding belongs to their job and measures against it, and the measurements come out wrong. Here the "scaffolding" is the rescue loop context, and the wrong measurements are the jump distances.

Impact

An invalid Ruby program of this shape crashes mruby and mruby_engine, and the crash propagates to the parent MRI VM. Beyond denial of service, the same bug can execute spurious bytecode that was not generated for the current program, or set the machine instruction pointer to a junk value. The researcher describes this as a limited form of unwanted code execution and is explicit that the executed code is not arbitrary. The reachable jump offset grows with each added break, bounded by memory and by the OP_JMP argument limit of 32767.

Denial of service means making a service unusable, here by crashing it.

Fix

The chosen fix is to pop the loop context after the assignment code is generated, so that the loop_pop/dispatch_linked calls inside the while code generation operate on the while loop's context and the generated jump is correct. The patch:

Diff
diff --git a/mrbgems/mruby-compiler/core/codegen.c b/mrbgems/mruby-compiler/core/codegen.c
index 9b064b8..bbe0f51 100644
--- a/mrbgems/mruby-compiler/core/codegen.c
+++ b/mrbgems/mruby-compiler/core/codegen.c
@@ -1746,6 +1746,7 @@ codegen(codegen_scope *s, node *tree, int val)
         genop(s, MKOP_A(OP_RESCUE, exc));
         genop(s, MKOP_A(OP_LOADF, exc));
         dispatch(s, noexc);
+        loop_pop(s, val);
     }
     else if ((intptr_t)tree->car->car == NODE_CALL) {
         node *n = tree->car->cdr;

This is a diff, the standard format for showing a change to source code. Lines starting with - would be removed, lines starting with + are added, and lines with no sign are context so you can see where the change goes. Here only one line is added: loop_pop(s, val);. It sits right after the code that finishes the error-catching part of the assignment, and it takes down the temporary rescue loop context, exactly the scaffolding that was being left behind. The @@ -1746,6 +1746,7 @@ header says the change is around line 1746 of the file and that the hunk grows from six lines to seven.

With the patch applied, the researcher was unable to crash the VM through this bug and no further jumps with invalid jump lengths were generated. All tests passed.

Variants to test

  • Replace the constant with a class variable (@@a ||= break while break). The special case in codegen.c covers NODE_CVAR as well as NODE_CONST, so the same leftover rescue context should be reachable. A positive result is a crash or an OP_JMP whose target lies past the last instruction of the irep. The @@ prefix marks a class variable in Ruby.
  • Add more break keywords to the right-hand side, as in larger.rb. A positive result is a jump target that grows with each added break, up to the OP_JMP argument limit of 32767.
  • Try other constructs that generate a rescue loop context around an assignment and then interact with an enclosing loop's loop_pop/dispatch_linked. A positive result is a loop context stack that is deeper than the source nesting suggests when inspected in a debugger.
  • Run the same programs under both mruby and the sandbox. A positive result is a crash in both, with the host process affected as well.

Hunting notes

This class of bug lives in compilers and interpreters that emit jump instructions and patch their offsets after the fact, especially where a temporary context (here a rescue loop) is pushed for one construct and popped later by an unrelated one. The signals are small, invalid programs that crash the interpreter, and near-identical programs that do not: changing a constant to a local variable, or ||= to &&=, isolating the exact syntax that triggers the fault. Disassembling the generated bytecode and looking for jump targets beyond the end of the instruction sequence is the quickest confirmation. The researcher showed impact by demonstrating the segmentation fault, the out-of-range jump target and its growth with additional break keywords, and by reasoning that an out-of-range opcode read through optable may lead to unwanted code execution.

Glossary

  • AST (abstract syntax tree): a tree-shaped diagram of how a compiler understood the structure of a program.
  • Bytecode: the list of simple internal steps a compiler produces from source code, which the interpreter then performs.
  • Class variable: a variable shared by a whole class of objects in Ruby, written with a @@ prefix.
  • Commit: a saved snapshot of a code project, identified by a long string of characters.
  • Compiler: the part of a language implementation that turns source text into bytecode.
  • Constant: in Ruby, a name starting with an uppercase letter, meant to hold a value that does not change.
  • CVSS: a standard scoring system for the severity of a security vulnerability, from 0 to 10.
  • Debugger: a tool that lets you pause a running program and inspect its internal state.
  • Denial of service: making a service unusable, for example by crashing it.
  • Diff: a standard text format showing lines added to and removed from source code.
  • Exception: an error signal raised while a program runs, which can be caught and handled.
  • Instruction pointer: the internal bookmark saying which step the processor will run next.
  • Interpreter: the part of a language implementation that performs bytecode step by step.
  • irep: mruby's internal record describing one block of bytecode, including its instruction list.
  • iseq: the numbered list of instructions belonging to one irep.
  • Loop context: a small record a compiler keeps while generating a loop, holding the information needed to patch that loop's jumps later.
  • mruby: a small, embeddable implementation of the Ruby language.
  • mruby_engine: a sandbox that runs mruby programs inside a host program.
  • MRI: the standard, main implementation of Ruby.
  • NameError: Ruby's error when a name that has never been defined is mentioned.
  • Opcode: the name of a single bytecode step, such as OP_JMP.
  • optable: a lookup table in the interpreter mapping opcode numbers to the code that handles them.
  • Pointer: a memory address, a note saying where something is stored.
  • Sandbox: a walled-off environment where a program runs so that its effects stay contained.
  • Segmentation fault (segfault): the operating system stopping a program because it touched memory it is not allowed to touch.
  • Variable: a named box that holds a value and can be changed.
  • VM (virtual machine): the component that executes bytecode, also called the interpreter.

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.