TOCTTOU bug in mrb_str_setbyte leading the memory corruption
The String#setbyte method cached the string's length before argument conversion, and a malicious to_i method could shrink the string during that conversion so the write went out of bounds. An attacker could cause a native crash and potentially achieve remote code execution.
- Triaged in 38 hours
- Fixed in 3 days
- Paid in 33 days
- Disclosed after 33 days
The String#setbyte function caches the length of the string before loading the function arguments. Loading function arguments through mrb_get_args can call into ruby code to run type conversion methods (to_i, to_s and the like). A malicious conversion method is able to force the string to be reallocated shorter so that the setbyte goes on to overwrite out of bounds memory.
Following is a POC that causes a native crash with under mruby on Mac OS X. I plan to follow up with a reliable RCE exploit against mruby-engine using this vulnerability in the next day or so.
$s = "9" + ("\n" * (1024*1024-1))
$k = []
class Tmp
def to_i
$k.push("a"*1024)
$s.chomp! ''
$s.succ!
95
end
end
tmp = Tmp.new
$s.setbyte(128, tmp)
puts $k[0]
Attached is a patch to mruby to resolve this issue.
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
The length of the string was read before mrb_get_args ran, and argument conversion can invoke Ruby code that reallocates the string, so the cached length no longer matched the buffer.
Impact
An attacker could crash the interpreter, and the author planned to follow up with a reliable RCE exploit.
What the attacker needed
Ability to pass an object to setbyte; attacker controls a conversion method
The fix
A patch to mruby was attached that is intended to resolve the issue.
How it was found
- Create a large string and an object whose to_i method shrinks that string.
- Call setbyte on the string, passing the object as the index argument.
- The to_i conversion runs and reallocates the string shorter.
- setbyte then writes using the stale length, causing an out-of-bounds write and a native crash.
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 program sometimes checks something (like how big a buffer is) and then does something else that can change it before the check is used. Here, the string's size was noted first, then user-supplied code ran and made the string smaller, so the later write landed past the end of the memory. That kind of out-of-bounds write can crash the program and, in the worst case, let an attacker run their own code.
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.