Project

General

Profile

Actions

Bug #22652

open

Hidden autoload mutex is handed to Fiber::Scheduler#block, and any Ruby method call on it crashes the interpreter

Bug #22652: Hidden autoload mutex is handed to Fiber::Scheduler#block, and any Ruby method call on it crashes the interpreter

Added by altruby (Alt Ruby) 1 day ago. Updated 1 day ago.

Status:
Open
Target version:
-
ruby -v:
3.2.0, 3.2.11, 3.3.14, 3.4.9, 3.4.13, 4.0.7, 4.0.10, 4.1.0-preview1
[ruby-core:127749]

Description

About

Title: Hidden autoload mutex is handed to Fiber::Scheduler#block, and any Ruby method call on it crashes the interpreter
Repository: ruby/ruby
Location: variable.c:95
Severity: Medium
Impacted versions: 3.2.0, 3.2.11, 3.3.14, 3.4.9, 3.4.13, 4.0.7, 4.0.10, 4.1.0-preview1

Summary

Ruby supports a pluggable "fiber scheduler" that lets a library decide what a fiber does
when it has to wait - for a socket, a timer, or a lock. When a fiber waits on a mutex,
Ruby calls the scheduler's block method and passes along the object the fiber is waiting
on as a "blocker". The documentation says that value is "informational only (for debugging
and logging)"; in other words, schedulers are expected to print it. For one internal mutex

  • the global mutex that guards autoloading - Ruby passes an object that is deliberately
    hidden from Ruby programs: its class pointer is NULL. So when a scheduler inspects that
    value, the interpreter asks the object for its class, gets NULL, and dereferences it. A
    debugging build stops on an assertion in vm_cc_hit_p (vm_insnhelper.c:2366); a release
    build segfaults at address 0x0 on the very next line (rb_vm_search_method_slowpath,
    vm_insnhelper.c:2281, reached from vm_sendish at vm_insnhelper.c:6458).

Getting the hidden mutex into Ruby only takes two concurrent autoloads in one thread. The
first autoload takes the global autoload mutex and then yields while requiring the feature
(a require does file I/O, which a scheduler turns into a yield); the second fiber that
tries to autoload the same constant has to wait, so Ruby reports the wait to the scheduler

  • and the blocker it reports is the hidden autoload mutex (variable.c:94-96 hides it;
    thread_sync.c:299-312 and scheduler.c:772 pass it through). Any ordinary method call on it
    then crashes the interpreter. The same object, reached through Ruby's C-API dispatch path
    instead of a normal method call, raises NotImplementedError "method'inspect' called on
    hidden T_DATA object" - which shows both what the intended behaviour is and that only the
    bytecode dispatch path is missing the guard. Re-verified on ruby 4.1.0dev (debug and
    release builds, 6/6 crashes) and on the released ruby 3.4.9 (SIGSEGV), with an ordinary
    mutex in the same scheduler as a control (no crash).
Impact

An application that uses a fiber scheduler can be killed outright by a value the
interpreter itself hands to it. When a scheduler touches the "blocker" it is given -- by
logging it, interpolating it into a message, or calling any method on it, which is exactly
what the documentation says the value is for -- and that blocker happens to be Ruby's
internal autoload mutex, the interpreter dereferences a NULL class pointer and dies. There
is no exception, no rescue, no warning and no partial failure: the whole process, every
thread, every request and every tenant in it disappear instantly. Because the hidden mutex
is only handed over when two fibers in the same thread autoload at the same time, the
crash can also happen during ordinary concurrent operation (two requests that each lazily
load a library), so it is not limited to attacker-supplied input; an attacker who can
cause two overlapping autoloads in such a service triggers it at will.

The deeper problem is that the "hidden object" invariant is not a safety invariant. Ruby
keeps hidden internal objects that Ruby code is never supposed to touch, and the C-API
dispatch path defends itself by raising NotImplementedError when one is reached. The
bytecode dispatch path used by ordinary Ruby method calls has no such check, so any
internal hidden object that leaks into Ruby turns a would-be Ruby exception into an
interpreter crash. Here the leak is easy: the scheduler API is documented as handing over
a value that is safe to log. A crash is recoverable in the sense that a supervisor can
restart the process, but the data of in-flight requests is lost and, if the crash is
deterministic under concurrent autoload, the service will keep dying until the deployed
scheduler code changes -- and the application authors have no way to fix it themselves,
because the blocker is supplied by the interpreter.

Mitigations

No application-level mitigation: the blocker is supplied by the interpreter, not the
application. Fibre schedulers should avoid Ruby-level method calls on the blocker (do not
inspect, interpolate, hash or compare it), which is only a workaround and contradicts the
documented API. The real fix belongs in Ruby: (1) do not hide the global autoload mutex,
or pass a visible placeholder/proxy as the blocker instead of the internal mutex, and (2)
mirror the hidden-object guard of rb_search_method_entry() (vm_eval.c:858,
NotImplementedError for klass == 0) in the VM dispatch path (vm_cc_hit_p /
rb_vm_search_method_slowpath) so a hidden receiver raises instead of dereferencing NULL.

Examples
example 1

An async HTTP server (Falcon/Async style, i.e. any server built on a Fiber scheduler) has
a scheduler whose block method logs what the fiber is waiting on: def block(blocker,
timeout = nil); logger.debug("fiber blocked on #{blocker.inspect}");...; end. Two requests
arrive at the same time and each triggers the lazy load of the same library; the second
fiber has to wait on Ruby's global autoload mutex, the scheduler logs that object, and the
process dies with SIGSEGV. Every connection in the process is dropped at once, with no
exception, no log line about the real cause and no chance to drain.

example 2

A custom scheduler written for debugging prints the blocker with warn block: #{blocker},
or stores it in a hash/array for later inspection (blocker.to_s, blocker.hash, blocker ==
other). Any of these is an ordinary Ruby method call on the hidden mutex and crashes the
VM exactly the same way. The API documentation invites this: "blocker is what we are
waiting on, informational only (for debugging and logging)."

example 3

The contrast that pinpoints the defect: the very same hidden object, handed to the C-API
dispatch path (Kernel.public_send(:p, blocker), which ends in rb_inspect via rb_funcall),
raises NotImplementedError - "method'inspect' called on hidden T_DATA object" - and the
program continues. The equivalent bytecode send (blocker.inspect) dereferences the NULL
class pointer instead. Debug builds stop at vm_insnhelper.c:2366 (vm_cc_hit_p, "klass:
T_FALSE"); release builds segfault at address 0x0.

example 4

Minimal reproduction (19 lines, no gems needed) - two fibers autoloading the same
constant, with a scheduler that inspects the blocker: class Scheduler
def block(blocker, timeout = nil)
blocker.inspect # hidden autoload mutex => klass == 0
@main.transfer
end
end autoload:TARGET, "target" Thread.new do
Fiber.set_scheduler(Scheduler.new)
Fiber.schedule { TARGET } # yields inside the autoload mutex
Fiber.schedule { TARGET } # contends on it -> block(hidden mutex) -> SIGSEGV
end.join Control: the same scheduler inspecting an ordinary Thread::Mutex blocker prints
"#Thread::Mutex:0x..." and does not crash.

Proof of concept
# Proof of concept: hidden internal mutex escapes to Ruby through the fiber
# scheduler, and the VM dereferences its NULL class pointer.
#
# variable.c:94-95 creates the global autoload mutex and hides it:
#
#     autoload_mutex = rb_mutex_new();
#     rb_obj_hide(autoload_mutex);          /* RBASIC_CLASS(autoload_mutex) == 0 */
#
# When an autoload has to wait for that mutex, do_mutex_lock() reports the wait
# to the fiber scheduler and passes the mutex VALUE as the "blocker"
# (thread_sync.c:312 -> thread_sync.c:249 -> scheduler.c:772):
#
#     rb_funcall(scheduler, id_block, 2, blocker, timeout)
#
# Scheduler#block is documented as receiving a "blocker" that is "informational
# only (for debugging and logging)", so schedulers routinely inspect it.  Any
# bytecode-level send on the hidden mutex (blocker.inspect, blocker.class, ...)
# goes through vm_sendish -> vm_search_method_fastpath with CLASS_OF(recv) == 0:
#
#   * debug / VM_CHECK_MODE build: assertion failure in vm_cc_hit_p()
#     ("klass: T_FALSE"), SIGABRT
#   * release build: rb_vm_search_method_slowpath() calls RB_BUILTIN_TYPE(klass)
#     on a NULL klass -> read of the NULL page -> SIGSEGV
#
# The C-API dispatch path guards against this (vm_eval.c:858 raises
# NotImplementedError for hidden objects); the bytecode send path does not.
#
# Self-contained: it writes the feature it autoloads into $TMPDIR and uses a
# minimal fiber scheduler.  The first scheduled fiber enters
# rb_autoload_load() and is suspended (a blocking operation in the require path
# yields to Scheduler#blocking_operation_wait) while holding autoload_mutex.
# The second fiber then autoloads the same constant, contends on that mutex and
# gets the hidden mutex handed to Scheduler#block.

$stdout.sync = true

# --- a feature to autoload (no gems, no external files) ---------------------
base = "poc_autoload_target_#{$$}"
dir  = ENV["TMPDIR"] || "/tmp"
File.write(File.join(dir, "#{base}.rb"), "POC_TARGET = :loaded\n")
$LOAD_PATH.unshift(dir)
at_exit { File.unlink(File.join(dir, "#{base}.rb")) rescue nil }

# --- minimal fiber scheduler -------------------------------------------------
class Scheduler
  def initialize = @main = Fiber.current
  def close = nil
  def fiber(&block) = Fiber.new(blocking: false, &block).tap(&:transfer)
  def unblock(blocker, fiber) = nil
  def fiber_interrupt(fiber, exception) = nil
  def kernel_sleep(duration = nil) = block(:sleep, duration)
  def io_wait(io, events, timeout) = block(:io_wait, timeout)
  def blocking_operation_wait(work) = block(:blocking_operation_wait, nil)

  def block(blocker, timeout = nil)
    # A logging line, exactly what the documentation says this value is for.
    # For ordinary blockers this just prints a symbol/IO/Thread; for the
    # hidden autoload mutex it crashes the interpreter.
    $stderr.puts "block(#{blocker.inspect})"
    @main.transfer
  end
end

# --- the attack -------------------------------------------------------------
autoload :POC_TARGET, base
$LOADED_FEATURES << "dummy"       # force the slow feature look-up

Thread.new do
  Fiber.set_scheduler(Scheduler.new)
  Fiber.schedule { POC_TARGET }   # suspends while holding autoload_mutex
  $stderr.puts "first fiber suspended while holding the autoload mutex"
  Fiber.schedule { POC_TARGET }   # contends -> block(hidden autoload mutex)
end.join

puts "no crash"
stdout
Author's original observations:
debug build (./ruby, VM_CHECK_MODE=1), 3/3 runs -> exit 134 (SIGABRT):
  block(:blocking_operation_wait)
  first fiber suspended while holding the autoload mutex
  ./vm_insnhelper.c:2366: Assertion Failed: vm_cc_hit_p:RB_TYPE_2_P(klass, RUBY_T_CLASS, RUBY_T_ICLASS): klass: T_FALSE
  rb_assert_failure_detail -> vm_cc_hit_p (vm_insnhelper.c:2366)
  -> vm_search_method_fastpath -> vm_sendish -> rb_fiber_scheduler_block (scheduler.c:772)
  -> call_rb_fiber_scheduler_block (thread_sync.c:249) -> do_mutex_lock (thread_sync.c:312)
  -> rb_autoload_load (variable.c:3391)
release build (./ruby_hard, VM_CHECK_MODE=0), 3/3 runs -> exit 139 (SIGSEGV):
  fiber_autoload_hidden_mutex_poc.rb:59: [BUG] Segmentation fault at 0x0000000000000000

Neo's re-verification (HEAD 19adb76051 + released ruby 3.4.9, /usr/local/bin/ruby):
  debug build   3/3: exit 134, "vm_insnhelper.c:2366: Assertion Failed: vm_cc_hit_p ... klass: T_FALSE"
  release build 3/3: exit 139, "[BUG] Segmentation fault at 0x0000000000000000" at the blocker.inspect line
  ruby 3.4.9    1/1: "[BUG] Segmentation fault at 0x0000000000000038" at the same line
  same poc without the "$LOADED_FEATURES << 'dummy'" line: still crashes (debug: assertion, release: SIGSEGV)
  control, ordinary Thread::Mutex blocker, same scheduler:
     block(#<Thread::Mutex:0x00000008137a2b58>) class=Thread::Mutex  -> no crash
  control, C-API dispatch on the SAME hidden blocker (Kernel.public_send(:p, blocker), which calls
  rb_inspect via rb_funcall):
     C-API dispatch raised NotImplementedError: method 'inspect' called on hidden T_DATA object
     (0x0000000813612ce8 flags=0x401800000000000c)
     -> the object handed to Scheduler#block really is the hidden autoload mutex, and the C-API
        path is guarded while the bytecode send path is not
Actions

Also available in: PDF Atom