Skip to content

[BUG] Array replacement from callbacks causes out-of-bounds reads in case splats and IO#puts #7092

Closed

Description

@kimaiden1984-boop

Title: [BUG] Array replacement from callbacks causes out-of-bounds reads in case splats and IO#puts

Version

Tested on current master at 77eca771af72b8ff018369b8aead3ad86e5d0195
on x86-64 Linux with Clang 18.1.3. The ASan build used the repository's
build_config/asan.rb configuration.

Summary

Two Array iteration loops save RARRAY_LEN() before invoking Ruby code but
reload RARRAY_PTR() on each iteration. If the callback replaces the same
Array with a shorter Array, later iterations use the new pointer with the old
length and read beyond the replacement allocation.

The two independently reachable sites are:

  1. mrb_obj_ceqq() in src/kernel.c, reached by ordinary
    case value; when *patterns syntax. A pattern's === method is the
    invalidating callback.
  2. io_puts_ary() in mrbgems/mruby-io/src/io.c, reached by
    IO#puts(array). An element's to_s method is the invalidating callback.

Neither reproducer needs a C extension, malformed bytecode, allocation
failure, or a custom allocator.

Reproduction

Build the full-core sanitizer configuration:

rake MRUBY_CONFIG=build_config/asan.rb

Then run the two Ruby files provided in the follow-up comment:

build/asan/bin/mruby poc/case-splat-array-replacement.rb
build/asan/bin/mruby poc/io-puts-array-replacement.rb

The case reproducer reports an eight-byte heap-buffer-overflow in
mrb_obj_ceqq() at src/kernel.c:635. The IO reproducer reports an eight-byte
heap-buffer-overflow while io_puts_ary() loads the next element at
mrbgems/mruby-io/src/io.c:1027.

In an unsanitized full-core build, each reproducer terminated with SIGSEGV in
three out of three fresh processes. Replacing the Array with another Array of
the original length is clean in both sanitizer and unsanitized builds.

Root cause

Both loops have the same lifetime pattern:

mrb_int len = RARRAY_LEN(ary);
for (mrb_int i = 0; i < len; i++) {
  /* load current RARRAY_PTR(ary)[i], then invoke Ruby code */
}

Array#replace can change both the pointer and length during the callback.
The next condition still admits indices below the old len, even when those
indices are outside the current owner.

Proposed fix

Keep the saved length as the upper bound so growth does not extend an
in-progress traversal, and also check the current length before each load:

i < len && i < RARRAY_LEN(ary)

The two-commit series provided in the follow-up comments keeps separate source changes and regression
tests for the core and mruby-io sites.

Validation of the patched tree:

  • full-core ASan/UBSan mrbtest: 2230 passed, 0 failed, 0 crashed, 2 skipped;
  • full-core unsanitized mrbtest: 2222 passed, 0 failed, 0 crashed, 10 skipped;
  • both positive reproducers: 3/3 clean in ASan/UBSan and 3/3 clean in the
    unsanitized build;
  • unchanged-length callback control: clean in all tested builds.

Related reports and impact

PR #6876 is not the same issue: it caps recursion depth for cyclic Arrays in
IO#puts; it does not cover Array replacement from to_s or a stale extent.
Issue #6854 concerns case ... in pattern-matching semantics, not
case ... when *patterns callback mutation.

The demonstrated consequences are native invalid reads and repeatable process
crashes from valid Ruby code. The IO#puts case can print a value interpreted
from beyond the replacement Array before crashing, but testing has not shown a
controlled value, stable address disclosure, arbitrary read/write, or code
execution.

Activity

  1. kimaiden1984-boop commented on Aug 11, 2026

    @kimaiden1984-boop
    Author

    Complete Ruby reproducers and unchanged-length control:

    case ... when *patterns

    class Pattern
      attr_accessor :owner, :replacement
    
      def ===(_value)
        @owner.replace(@replacement)
        false
      end
    end
    
    pattern = Pattern.new
    patterns = [pattern] + Array.new(39) { Object.new }
    pattern.owner = patterns
    pattern.replacement = Array.new(21) { Object.new }
    
    result = case :value
             when *patterns
               :matched
             else
               :not_matched
             end
    
    puts "result=#{result} length=#{patterns.length}"

    IO#puts(Array)

    class Element
      attr_accessor :owner, :replacement
    
      def to_s
        @owner.replace(@replacement)
        "callback"
      end
    end
    
    element = Element.new
    values = [element] + Array.new(39) { "old" }
    element.owner = values
    element.replacement = Array.new(21) { "new" }
    
    STDOUT.puts(values)
    puts "complete length=#{values.length}"

    unchanged-length control

    class StablePattern
      attr_accessor :owner
    
      def ===(_value)
        @owner.replace(Array.new(40) { Object.new })
        false
      end
    end
    
    class StableElement
      attr_accessor :owner
    
      def to_s
        @owner.replace(Array.new(40) { "new" })
        "callback"
      end
    end
    
    pattern = StablePattern.new
    patterns = [pattern] + Array.new(39) { Object.new }
    pattern.owner = patterns
    case :value
    when *patterns
      raise "unexpected match"
    end
    
    element = StableElement.new
    values = [element] + Array.new(39) { "old" }
    element.owner = values
    STDOUT.puts(values)
    puts "control complete"
  2. kimaiden1984-boop commented on Aug 11, 2026

    @kimaiden1984-boop
    Author

    Proposed patch 1/2, including the core regression test:

    From 18347b1965c6f8361e434a85d1261a8fd15dfa59 Mon Sep 17 00:00:00 2001
    From: Reporter <reporter@example.invalid>
    Date: Tue, 11 Aug 2026 17:57:04 +0000
    Subject: [PATCH 1/2] kernel: bound case splat iteration after callbacks
    
    ---
     src/kernel.c     |  2 +-
     test/t/syntax.rb | 25 +++++++++++++++++++++++++
     2 files changed, 26 insertions(+), 1 deletion(-)
    
    diff --git a/src/kernel.c b/src/kernel.c
    index 2d07d0380..16955e090 100644
    --- a/src/kernel.c
    +++ b/src/kernel.c
    @@ -631,7 +631,7 @@ mrb_obj_ceqq(mrb_state *mrb, mrb_value self)
         mrb_ensure_array_type(mrb, ary);
       }
       mrb_int len = RARRAY_LEN(ary);
    -  for (mrb_int i=0; i<len; i++) {
    +  for (mrb_int i=0; i<len && i<RARRAY_LEN(ary); i++) {
         mrb_value c = mrb_funcall_argv(mrb, RARRAY_PTR(ary)[i], eqq, 1, &v);
         if (mrb_test(c)) return mrb_true_value();
       }
    diff --git a/test/t/syntax.rb b/test/t/syntax.rb
    index 8337c85b0..88b676bf5 100644
    --- a/test/t/syntax.rb
    +++ b/test/t/syntax.rb
    @@ -647,6 +647,31 @@ assert('splat in case statement') do
       assert_equal [3,8], resultc
     end
     
    +assert('splat in case statement with pattern array replacement') do
    +  pattern_class = Class.new do
    +    attr_accessor :patterns, :replacement
    +
    +    def ===(_value)
    +      @patterns.replace(@replacement)
    +      false
    +    end
    +  end
    +  pattern = pattern_class.new
    +  patterns = [pattern] + Array.new(39) { Object.new }
    +  replacement = Array.new(21) { Object.new }
    +  pattern.patterns = patterns
    +  pattern.replacement = replacement
    +
    +  result = case :value
    +           when *patterns
    +             :matched
    +           else
    +             :not_matched
    +           end
    +  assert_equal :not_matched, result
    +  assert_equal 21, patterns.length
    +end
    +
     assert('External command execution.') do
       module Kernel
         sym = '`'.to_sym
    -- 
    2.43.0
    
  3. kimaiden1984-boop commented on Aug 11, 2026

    @kimaiden1984-boop
    Author

    Proposed patch 2/2, including the mruby-io regression test:

    From 16b20ca758da2d78bae24113c8b644c5e3312c59 Mon Sep 17 00:00:00 2001
    From: Reporter <reporter@example.invalid>
    Date: Tue, 11 Aug 2026 17:57:10 +0000
    Subject: [PATCH 2/2] mruby-io: bound puts array iteration after conversion
    
    ---
     mrbgems/mruby-io/src/io.c   |  2 +-
     mrbgems/mruby-io/test/io.rb | 28 ++++++++++++++++++++++++++++
     2 files changed, 29 insertions(+), 1 deletion(-)
    
    diff --git a/mrbgems/mruby-io/src/io.c b/mrbgems/mruby-io/src/io.c
    index 6ca57dbff..d8fa9ba61 100644
    --- a/mrbgems/mruby-io/src/io.c
    +++ b/mrbgems/mruby-io/src/io.c
    @@ -1023,7 +1023,7 @@ io_puts_ary(mrb_state *mrb, int fd, mrb_value ary, int depth)
         return;
       }
     
    -  for (mrb_int i = 0; i < len; i++) {
    +  for (mrb_int i = 0; i < len && i < RARRAY_LEN(ary); i++) {
         mrb_value elem = RARRAY_PTR(ary)[i];
         if (mrb_array_p(elem)) {
           io_puts_ary(mrb, fd, elem, depth + 1);
    diff --git a/mrbgems/mruby-io/test/io.rb b/mrbgems/mruby-io/test/io.rb
    index 35d58a277..85bc8f44f 100644
    --- a/mrbgems/mruby-io/test/io.rb
    +++ b/mrbgems/mruby-io/test/io.rb
    @@ -121,6 +121,34 @@ end
     #assert('IO#putc', '15.2.20.5.12') do
     #assert('IO#puts', '15.2.20.5.13') do
     
    +assert('IO#puts with array replacement from to_s') do
    +  element_class = Class.new do
    +    attr_accessor :values, :replacement
    +
    +    def to_s
    +      @values.replace(@replacement)
    +      "callback"
    +    end
    +  end
    +  element = element_class.new
    +  values = [element] + Array.new(39) { "old" }
    +  replacement = Array.new(21) { "new" }
    +  element.values = values
    +  element.replacement = replacement
    +
    +  io = IO.new(IO.sysopen($mrbtest_io_wfname, 'w'), 'w')
    +  begin
    +    assert_nil io.puts(values)
    +  ensure
    +    io.close
    +  end
    +
    +  IO.open(IO.sysopen($mrbtest_io_wfname, 'r'), 'r') do |input|
    +    assert_equal "callback\n" + "new\n" * 20, input.read
    +  end
    +  assert_equal 21, values.length
    +end
    +
     assert('IO#read', '15.2.20.5.14') do
       IO.open(IO.sysopen($mrbtest_io_rfname)) do |io|
         assert_raise(ArgumentError) { io.read(-5) }
    -- 
    2.43.0
    
  4. added a commit that references this issue on Aug 12, 2026
    c3b287d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions