From b9fe516d2303388f2a7fb082ff62ea42cae0351d Mon Sep 17 00:00:00 2001 From: Oliver Chang Date: Thu, 14 Aug 2025 08:31:16 +0000 Subject: [PATCH] Fix a heap-buffer-overflow in in str strip! methods. This issue was originally discovered by OSS-Fuzz: https://issues.oss-fuzz.com/issues/428404023 The root cause was that str_strip_bang modified the string content and length in-place but failed to null-terminate the string at its new length. When this modified, non-null-terminated string was duplicated, the buffer may be resized, dropping the old null terminator (via str_uminus -> mrb_str_dup -> str_replace -> str_share). When this is later passed to mrb_raisef using the %!s format specifier, mrb_vformat called strlen on the underlying non-null terminated buffer pointer. The fix adds explicit null-termination in str_strip_bang, str_lstrip_bang, and str_rstrip_bang after the string length is updated. --- mrbgems/mruby-string-ext/src/string.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/mrbgems/mruby-string-ext/src/string.c b/mrbgems/mruby-string-ext/src/string.c index 95f98981b..fa22d397d 100644 --- a/mrbgems/mruby-string-ext/src/string.c +++ b/mrbgems/mruby-string-ext/src/string.c @@ -1513,10 +1513,12 @@ str_lstrip_bang(mrb_state *mrb, mrb_value self) if (start < len) { memmove(ptr, ptr + start, len - start); RSTR_SET_LEN(s, len - start); + ptr[len - start] = '\0'; } else { /* All whitespace - make empty */ RSTR_SET_LEN(s, 0); + ptr[0] = '\0'; } return self; @@ -1554,6 +1556,7 @@ str_rstrip_bang(mrb_state *mrb, mrb_value self) /* Truncate string */ RSTR_SET_LEN(s, end); + ptr[end] = '\0'; return self; } @@ -1608,6 +1611,7 @@ str_strip_bang(mrb_state *mrb, mrb_value self) /* Set new length */ RSTR_SET_LEN(s, end - start); + ptr[end - start] = '\0'; return self; }