Recursion causing uninitialized memory reads leading to a segfault
A recursive Ruby method with an ensure block caused uninitialised memory reads and a segfault in the mruby VM, affecting the sandbox.
- Triaged in 4 days
- Fixed in 10 days
- Paid in 30 days
- Disclosed after 30 days
The following code produces a segfault without causing a stack overflow, affecting the sandbox:
def fn(n)
return
ensure
if n == 0
else fn(n-1)
end
end
fn(24)
When the n parameter is less than 24, there is no segfault. However,
investigating with a memory sanitizer shows that uninitialized read errors
start to happen when n >= 15. The uninitialized read happens at the following
location in vm.c (with the relevant line marked):
1701 cipop(mrb);
1702 acc = ci->acc; [***]
1703 mrb->c->stack = ci->stackent;
The issue seems to be in using the ci data after the call to cipop. The following patch stops the read errors and segfaults, and passes make test:
diff --git a/src/vm.c b/src/vm.c
index 9684dab..66fb692 100644
--- a/src/vm.c
+++ b/src/vm.c
@@ -1698,9 +1698,10 @@ RETRY_TRY_BLOCK:
mrb->jmp = prev_jmp;
return v;
}
- cipop(mrb);
+ ci = mrb->c->ci;
acc = ci->acc;
mrb->c->stack = ci->stackent;
+ cipop(mrb);
if (acc == CI_ACC_SKIP) {
mrb->jmp = prev_jmp;
return v;
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
How it worked
Root cause
Likely the code used a pointer to a call info structure after it had been popped, causing a read of uninitialised memory.
Impact
The code crashes the interpreter, affecting the sandbox.
What the attacker needed
Ability to run code in the sandbox
The fix
The fix was to reorder the code so that the call info pointer is refreshed before being used, and the pop happens afterwards.
How it was found
- Define a recursive function with an ensure block that calls itself when n is not zero.
- Call the function with an argument of 24.
- Observe the segmentation fault.
Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
A segmentation fault is a crash when a program accesses memory it should not. Here, a recursive function (one that calls itself) with an ensure block made the interpreter read memory that had not been set, leading to a crash. The fix was to reorder two lines of code so the interpreter uses the correct pointer before cleaning up.
What is Memory corruption?
Native code reads or writes memory it should not: overflows, use-after-free, type confusion. The core of browser, kernel and parser bugs.