Certain inputs cause tight C-level recursion leading to process stack overflow
Certain legal mruby programs cause tight recursion at the C level while using little of the Ruby-level stack, so the interpreter never raises a Ruby stack overflow and instead crashes with a process stack overflow and segfault. An attacker who can supply Ruby code to mruby or the mruby sandbox could crash the process.
- Triaged in 8 days
- Fixed in 3 months
- Paid in 3 months
- Disclosed after 3 months
Introduction
Certain legal Ruby programs can cause a tight recursion on the C-level (without using eval) while spending very little of the Ruby-level stack. This precludes triggering a Ruby stack overflow exception and eventually leads to a process stack overflow and a segfault. Both vanilla mruby and mruby running inside mruby-engine are vulnerable.
Proof of concept
recursive_to_i.rb:
def to_i
'' * self
end
to_i
- Save the above code as
recursive_to_i.rb. - Run either:
a)
mruby recursive_to_i.rbb)sandbox recursive_to_i.rb - Both cause a segfault due to a process stack overflow.
Discussion
Everything below assumes the latest master of the mruby repository as of Dec 08th, which is commit b84e005fc36a3c669586cc66ab3c87630d7a5509.
Since the above POC redefines to_i on Object, it is very easy to trigger the crash afterwards, for instance, by trying to use any subclass of Object without its own to_i in an integer context.
Incidentally, that mruby uses to_i for implicit conversion to an Integer seems wrong (the offending code being in object.c, line 561). For instance, MRI Ruby gives the following for the above POC:
recursive_to_i.rb:2:in `*': no implicit conversion of Object into Integer (TypeError)
from recursive_to_i.rb:2:in `to_i'
from recursive_to_i.rb:5:in `<main>'<Paste>
However, the problem isn't limited to overriding to_i. Some other inputs that exploit the same bug:
nil_method_ensure.rb
def nil.m
m a ensure m + a
end
nil.m
This one crashes only mruby and not the sandbox:
module_new_do.rb
def a
Module.new do
a
end
end
a
There are probably others since the underlying cause is the same.
Solution
While there may be a way to fix these cases individually, it is our opinion that the C-level recursion depth should be tracked and, ideally, limited according to the size of the process stack.
We managed to produce recursions that spend as much as 3200 bytes of the process stack between two recursive mrb_vm_run calls while only spending 80 bytes of the Ruby stack. Based on some testing, we've derived a loose upper limit of the number of recursions needed to crash the interpreter in this scenario:
(stack_size * 0.98) / 3200
Tightening the factors up a bit, we arrive at the following formula that should give a good safety margin (assumptions: 10% of the stack used before first call to mrb_vm_run, 4096 bytes of the process stack used between two recursive calls):
(stack_size * 0.9) / 4096 - 1
We supply a patch where we've implemented C-level recursion depth tracking based on this formula, hardcoded to a stack size of 8 MiB (defined as a macro constant). Ideally, the process stack size should be determined using a method appropriate for the OS (for instance, getrlimit on POSIX).
-- Denis Kasak Damir Jelić
Context
mruby is an embeddable Ruby implementation with a C core. The report concerns the mruby interpreter itself and mruby running inside mruby-engine, which is exercised through a sandbox binary. The relevant feature is the interpreter's handling of Ruby-level recursion: mruby normally raises a Ruby stack overflow exception when a program recurses too deeply, which keeps a runaway script from taking down the host process. The report shows that certain legal Ruby programs recurse tightly on the C stack while consuming very little of the Ruby-level stack, so the Ruby-level guard never fires and the process stack overflows instead, ending in a segfault.
Setup
The analysis assumes the latest master of the mruby repository as of 8 December, commit [redacted]. Two ways of running the interpreter are used: the plain mruby binary and the sandbox binary that runs mruby inside mruby-engine.
Finding it
The researcher noticed that some legal Ruby programs, without using eval, produce a tight recursion at the C level while spending very little of the Ruby-level stack. Because the Ruby stack grows slowly, the interpreter's Ruby stack overflow exception is never triggered, and the recursion continues until the process stack is exhausted and the process segfaults. Both vanilla mruby and mruby inside mruby-engine are affected.
Exploitation
Step 1: write the recursive program
def to_i
'' * self
end
to_i
The program redefines to_i on Object. The body multiplies an empty string by self, and that multiplication needs an integer, so the interpreter calls to_i again on the same object, which re-enters the same multiplication, and so on. Each round trip goes through the C implementation of the operator and the method call machinery, so the C stack grows quickly while the Ruby-level stack barely moves.
Step 2: run it under either interpreter
Save the code as recursive_to_i.rb, then run either of the following:
mruby recursive_to_i.rb
sandbox recursive_to_i.rb
Both commands cause a segfault due to a process stack overflow. The Ruby stack overflow exception that should have stopped the recursion is never raised, because the Ruby-level stack usage stays small.
Step 3: trigger it indirectly
Because the proof of concept redefines to_i on Object, the crash is very easy to trigger afterwards. Any subclass of Object that does not define its own to_i will hit the redefined method when it is used in an integer context, and the same recursion follows.
Root cause
The report argues that C-level recursion depth should be tracked and limited. A program can therefore drive deep C-level recursion through ordinary method dispatch and operator implementations while the Ruby-level stack stays shallow, so the existing Ruby stack overflow check never fires. The report points at the implicit conversion to Integer in object.c, line 561, as the offending code for the first proof of concept, and notes that using to_i for implicit conversion seems wrong in itself. For comparison, MRI Ruby rejects the same program:
recursive_to_i.rb:2:in `*': no implicit conversion of Object into Integer (TypeError)
from recursive_to_i.rb:2:in `to_i'
from recursive_to_i.rb:5:in `<main>'
The problem is not limited to overriding to_i. The same underlying cause is reachable through other inputs.
Variant: ensure with a recursive call
def nil.m
m a ensure m + a
end
nil.m
This one crashes only mruby and not the sandbox.
Variant: Module.new with a block
def a
Module.new do
a
end
end
a
The report notes there are probably other inputs, since the underlying cause is the same.
Impact
An attacker who can get a Ruby program executed by mruby, directly or through mruby-engine, can crash the interpreter process with a segfault. The interpreter process segfaults. The report describes only a crash, not memory corruption. The nil.m variant crashes only mruby and not the sandbox.
Fix
The report argues that fixing the cases individually may be possible, but that the C-level recursion depth should be tracked and, ideally, limited according to the size of the process stack. The researchers measured recursions that spend as much as 3200 bytes of the process stack between two recursive mrb_vm_run calls while spending only 80 bytes of the Ruby stack. From testing they derived a loose upper limit on the number of recursions needed to crash the interpreter in this scenario:
(stack_size * 0.98) / 3200
Tightening the factors gives a formula with a safety margin, assuming 10% of the stack is used before the first call to mrb_vm_run and 4096 bytes of process stack are used between two recursive calls:
(stack_size * 0.9) / 4096 - 1
The researchers supplied a patch implementing C-level recursion depth tracking based on this formula, hardcoded to a stack size of 8 MiB defined as a macro constant. They note that ideally the process stack size should be determined with a method appropriate for the OS, for instance getrlimit on POSIX.
Variants to test
- Redefine a conversion method on a base class and use an object in a context that forces implicit conversion. A positive result is a segfault rather than a Ruby-level exception.
- Put a recursive call in an
ensureclause of a method invoked onnil. A positive result is a crash in the plain interpreter; the report observed no crash in the sandbox for this input. - Call a recursive method from inside a
Module.newblock. A positive result is a segfault from process stack exhaustion. - Measure stack consumption between two recursive interpreter calls to see whether the C stack grows much faster than the Ruby stack. A positive result is a large C-level delta against a small Ruby-level delta, which is the condition that defeats a Ruby-only recursion limit.
Hunting notes
This class of bug hides in interpreters and runtimes that enforce recursion limits at the script level only, particularly where untrusted code is embedded in a larger process, as with mruby-engine here. During recon, the signal is a sandbox or scripting feature that advertises a script-level stack overflow guard: if the guard counts only script frames, native frames consumed by method dispatch, operator implementations and implicit conversions are unaccounted for. The researcher showed a minimal, legal program that segfaults both the standalone interpreter and the sandboxed one.
What happened, in plain words
mruby is a small version of the Ruby programming language. Ruby is a language people write programs in, and mruby is a cut-down version designed to be built into other software, so that software can run small Ruby scripts. The report is about a way to make mruby crash.
Normally, mruby has a safety net. If a program calls itself over and over again (this is called recursion), mruby notices and stops it with an error message, instead of letting the program run forever. That safety net is meant to protect the computer running the script.
The researcher found that some perfectly legal Ruby programs get around this safety net. They make the program go round and round in a way that uses up a different kind of memory, one the safety net does not watch. Eventually the program runs out of that memory and the whole process crashes. This is called a segfault, short for segmentation fault: the operating system kills the program because it tried to use memory it should not have.
Background: what you need to know first
A few ideas come up again and again, so here they are from scratch.
Ruby and mruby. Ruby is a programming language. mruby is a smaller, lighter version of it. Because mruby is small, other programs can include it, the way a car can include a radio. The program that includes mruby can then run Ruby scripts that users give it. mruby-engine is one such way of embedding mruby, and the report uses a program called sandbox to run mruby inside mruby-engine.
The C stack. When a program runs, it keeps track of what it is doing on a stack, like a pile of sticky notes. Each time a function calls another function, a new note goes on the pile. When the function finishes, the note comes off. The pile has a fixed maximum height. If you keep adding notes without ever taking them off, the pile falls over. In a computer, that fall is a segfault.
The Ruby stack. mruby keeps a second, separate pile for Ruby-level calls. This is the pile its safety net watches. When the Ruby pile gets too tall, mruby raises a Ruby stack overflow exception, which is a polite error message that stops the script.
Recursion. Recursion is when a function calls itself. A simple example is a function that counts down: it calls itself with a smaller number until it reaches zero. Recursion is normal and useful, but runaway recursion is dangerous, which is why mruby has the safety net.
eval. eval is a Ruby feature that runs a piece of text as if it were code. It is a common way to cause trouble, so many sandboxes block it. The interesting thing about this report is that the crash does not need eval at all.
Implicit conversion. Sometimes a program needs a number but is given something else, like a piece of text. Ruby then quietly asks the object to turn itself into a number by calling a method named to_i (short for "to integer"). This quiet asking is called implicit conversion.
Object. In Ruby, almost everything is an object, and Object is the base class that most objects inherit from. If you change a method on Object, you change it for nearly everything.
Segfault. A segmentation fault is the operating system stepping in when a program touches memory it is not allowed to touch. The program is killed immediately. There is no error message from the script itself.
Setup
The analysis assumes the latest master of the mruby repository as of 8 December, commit [redacted]. A commit is a saved snapshot of the code, and the long string is its unique name, so anyone can find exactly the version that was tested.
Two ways of running the interpreter are used: the plain mruby binary and the sandbox binary that runs mruby inside mruby-engine. A binary is a ready-to-run program. The first is the standalone interpreter; the second is the interpreter wrapped in the embedding layer.
Finding it
The researcher noticed that some legal Ruby programs, without using eval, produce a tight recursion at the C level while spending very little of the Ruby-level stack. "Tight" here means the loop goes round very quickly, with very little work between one round and the next.
Because the Ruby stack grows slowly, the interpreter's Ruby stack overflow exception is never triggered. The safety net is watching the wrong pile. Meanwhile the C stack keeps growing, until the process stack is exhausted and the process segfaults. Both vanilla mruby and mruby inside mruby-engine are affected. "Vanilla" means the plain, unmodified interpreter.
Exploitation
Step 1: write the recursive program
def to_i
'' * self
end
to_i
Line by line:
def to_istarts the definition of a method calledto_i. Because it is written at the top level, it is being defined onObject, so every object in the program now has this version ofto_i.'' * selfis the body.''is an empty piece of text (an empty string).*means "repeat this text this many times".selfmeans "the object this method was called on". So the line says: repeat the empty string as many times as the object's own value.endcloses the method definition.to_ion its own line calls the method. There is no object in front of it, so it is called on the main object of the program.
The trap is in the multiplication. To repeat a string a number of times, Ruby needs a number. The object is not a number, so Ruby quietly asks it to convert itself by calling to_i. But to_i is now the method we just wrote, and its body again needs a number, so it calls to_i again, and so on. Each round trip goes through the C implementation of the operator and the method call machinery, so the C stack grows quickly while the Ruby-level stack barely moves.
Step 2: run it under either interpreter
Save the code as recursive_to_i.rb, then run either of the following:
mruby recursive_to_i.rb
sandbox recursive_to_i.rb
mruby recursive_to_i.rbruns the standalone interpreter on the saved file.sandbox recursive_to_i.rbruns the same file through the sandbox binary, which uses mruby-engine.
Both commands cause a segfault due to a process stack overflow. The Ruby stack overflow exception that should have stopped the recursion is never raised, because the Ruby-level stack usage stays small. Running both is what shows the problem is in mruby itself and not only in the embedding layer.
Step 3: trigger it indirectly
Because the proof of concept redefines to_i on Object, the crash is very easy to trigger afterwards. Any subclass of Object that does not define its own to_i will hit the redefined method when it is used in an integer context, and the same recursion follows. In plain terms: once the bad to_i is in place, almost any later attempt to use an object as a number sets off the same loop. The attacker does not need to call the dangerous method directly.
Root cause
The report argues that C-level recursion depth should be tracked and limited. A program can therefore drive deep C-level recursion through ordinary method dispatch and operator implementations while the Ruby-level stack stays shallow, so the existing Ruby stack overflow check never fires. Method dispatch is simply the process of deciding which method to run when a name is called; operator implementations are the built-in code behind things like * and +.
The report points at the implicit conversion to Integer in object.c, line 561, as the offending code for the first proof of concept, and notes that using to_i for implicit conversion seems wrong in itself. Integer is Ruby's whole-number type, and object.c is the source file where the base object behaviour lives.
For comparison, MRI Ruby rejects the same program. MRI is the standard, full-size Ruby implementation, as opposed to the small mruby:
recursive_to_i.rb:2:in `*': no implicit conversion of Object into Integer (TypeError)
from recursive_to_i.rb:2:in `to_i'
from recursive_to_i.rb:5:in `<main>'
This is an error message, not a crash. It says that on line 2, inside the * operator, Ruby refused to convert an Object into an Integer and raised a TypeError. The following lines show the trail of calls that led there: line 2 inside to_i, then line 5 in the main program. The point is that the full-size interpreter stops the program cleanly, while mruby does not.
The problem is not limited to overriding to_i. The same underlying cause is reachable through other inputs.
Variant: ensure with a recursive call
def nil.m
m a ensure m + a
end
nil.m
Line by line:
def nil.mdefines a method calledmon the special objectnil, which represents "nothing". Onlynilgets this method.m a ensure m + ais the body.m acalls the methodmagain, passinga. The wordensureintroduces a block of code that Ruby promises to run whatever happens, even if the main part fails or is interrupted. That block ism + a, which callsmagain and addsa.endcloses the definition.nil.mcalls the method onnilto start it all off.
Each call to m makes another call to m, and the ensure block adds more calls on the way out. The recursion again happens mostly in the C machinery rather than in the Ruby stack. This one crashes only mruby and not the sandbox, which shows the two setups do not behave identically.
Variant: Module.new with a block
def a
Module.new do
a
end
end
a
Line by line:
def adefines a method calleda.Module.new docreates a new module. A module in Ruby is a bundle of methods and constants that can be shared.Module.newwith adoblock runs that block while the module is being created.ainside the block calls the methodaagain, which creates another module, which callsaagain, and so on.endcloses the block, and the secondendcloses the method.aon its own line starts the whole thing.
The report notes there are probably other inputs, since the underlying cause is the same. The lesson is that fixing one spelling of the bug would not be enough.
Impact
An attacker who can get a Ruby program executed by mruby, directly or through mruby-engine, can crash the interpreter process with a segfault. The interpreter process segfaults. This kind of attack, where the goal is to make something unavailable rather than to steal data, is called denial of service.
The report describes only a crash, not memory corruption. The nil.m variant crashes only mruby and not the sandbox.
Fix
The report argues that fixing the cases individually may be possible, but that the C-level recursion depth should be tracked and, ideally, limited according to the size of the process stack. In other words, instead of patching each trick one by one, count how deep the C pile has grown and stop before it topples.
The researchers measured recursions that spend as much as 3200 bytes of the process stack between two recursive mrb_vm_run calls while spending only 80 bytes of the Ruby stack. mrb_vm_run is the internal C function that runs Ruby code, so two of them nested means the interpreter has gone one level deeper. A byte is a unit of computer memory; 3200 bytes is a lot compared with 80.
From testing they derived a loose upper limit on the number of recursions needed to crash the interpreter in this scenario:
(stack_size * 0.98) / 3200
Read it as: take the total stack size, keep 98% of it, and divide by 3200 bytes per level. That gives roughly how many levels fit before the crash. It is described as a loose upper limit.
Tightening the factors gives a formula with a safety margin, assuming 10% of the stack is used before the first call to mrb_vm_run and 4096 bytes of process stack are used between two recursive calls:
(stack_size * 0.9) / 4096 - 1
Here 90% of the stack is used, the per-level cost is rounded up to 4096 bytes, and one level is subtracted as extra headroom. The result is a limit that should stop the program before the real edge is reached.
The researchers supplied a patch implementing C-level recursion depth tracking based on this formula, hardcoded to a stack size of 8 MiB defined as a macro constant. A patch is a proposed change to the source code. A macro constant is a named value written once in the code and used everywhere, so it is easy to change later. 8 MiB means 8 mebibytes, a common default size for a process stack.
They note that ideally the process stack size should be determined with a method appropriate for the OS, for instance getrlimit on POSIX. getrlimit is a system call that asks the operating system for a limit, such as how big the stack is allowed to be. POSIX is a family of operating system standards that includes Linux and similar systems. Hardcoding 8 MiB works, but asking the operating system would be more accurate on machines where the default differs.
Variants to test
These are the kinds of inputs worth trying if you are looking at a similar interpreter. Each one is a small experiment with a clear pass or fail.
- Redefine a conversion method on a base class and use an object in a context that forces implicit conversion. A positive result is a segfault rather than a Ruby-level exception. The idea is to put the dangerous method where many objects will inherit it, then let ordinary code call it by accident.
- Put a recursive call in an
ensureclause of a method invoked onnil. A positive result is a crash in the plain interpreter; the report observed no crash in the sandbox for this input. Theensureclause is interesting because it runs on the way out, adding calls in a place that is easy to overlook. - Call a recursive method from inside a
Module.newblock. A positive result is a segfault from process stack exhaustion. This checks whether module creation adds its own C-level frames on top of the method call. - Measure stack consumption between two recursive interpreter calls to see whether the C stack grows much faster than the Ruby stack. A positive result is a large C-level delta against a small Ruby-level delta, which is the condition that defeats a Ruby-only recursion limit. A delta is simply the difference between the value before and after.
Hunting notes
This class of bug hides in interpreters and runtimes that enforce recursion limits at the script level only, particularly where untrusted code is embedded in a larger process, as with mruby-engine here. A runtime is the software that actually executes a program while it runs.
During recon, the signal is a sandbox or scripting feature that advertises a script-level stack overflow guard. Recon means the early looking-around phase, before trying anything clever. If the guard counts only script frames, native frames consumed by method dispatch, operator implementations and implicit conversions are unaccounted for. A frame is one entry on the stack, one sticky note in the pile; a native frame is one created by compiled C code rather than by the script.
The researcher showed a minimal, legal program that segfaults both the standalone interpreter and the sandboxed one. Reproducible means anyone can run it again and get the same result. No privileged input means the attacker does not need an account, a password or special rights: being allowed to submit a script is enough.
Glossary
- mruby: a small, embeddable implementation of the Ruby programming language, written with a C core.
- Ruby: a programming language; mruby is a reduced version of it.
- mruby-engine: a way of embedding mruby inside another program.
- sandbox: here, a binary that runs mruby inside mruby-engine; more generally, an isolated environment for running untrusted code.
- binary: a ready-to-run program file.
- C: a low-level programming language used to build interpreters and operating systems.
- C stack / process stack: the region of memory where a running program keeps its chain of function calls; it has a fixed maximum size.
- Ruby stack: mruby's separate record of Ruby-level calls, which its safety net watches.
- Stack overflow: the condition where a stack runs out of room because too many entries were added without being removed.
- Segfault (segmentation fault): the operating system killing a program because it touched memory it is not allowed to touch.
- Recursion: a function calling itself.
- Tight recursion: recursion that goes round very quickly with very little work between rounds.
- Exception: a signal raised by a program to report an error, which can be caught and handled.
- Ruby stack overflow exception: mruby's polite error raised when the Ruby-level stack gets too deep.
eval: a Ruby feature that runs text as code; often blocked in sandboxes.- Implicit conversion: quietly turning an object into another type, such as a number, when a context needs it.
to_i: the Ruby method that converts an object to an integer.Integer: Ruby's whole-number type.Object: the base class most Ruby objects inherit from; changing a method on it changes it almost everywhere.nil: Ruby's special object meaning "nothing".ensure: a Ruby keyword introducing code that is guaranteed to run, whatever happens in the main part.Module.new: Ruby code that creates a new module, optionally running a block while doing so.- Module: a bundle of methods and constants that can be shared in Ruby.
- Method dispatch: the process of deciding which method to run when a name is called.
- Operator implementation: the built-in code behind symbols such as
*and+. mrb_vm_run: the internal C function in mruby that runs Ruby code.- Frame: one entry on a call stack; a native frame is one created by compiled C code.
- Byte: a unit of computer memory.
- MiB (mebibyte): about one million bytes; 8 MiB is a common default process stack size.
- Macro constant: a named value defined once in source code and reused.
- Patch: a proposed change to source code.
- Commit: a saved snapshot of a code repository, identified by a long unique string.
getrlimit: a system call that asks the operating system for a resource limit, such as the stack size.- POSIX: a family of operating system standards that includes Linux and similar systems.
- MRI Ruby: the standard, full-size Ruby implementation, as opposed to mruby.
TypeError: the Ruby error raised when a value is of the wrong type for an operation.- Denial of service: an attack that makes a service unavailable rather than stealing data.
- Memory corruption: a class of bug where a program uses memory incorrectly; here the report classifies the crash under this label.
- CVSS: a standard scoring system for the severity of a security issue; 8.6 is a high score.
- Recon: the early phase of looking around a target before attempting anything.
- Reproducible: a result that anyone can obtain again by following the same steps.