Christopher Thompson | 12 May 19:23
Favicon

Buffer overflow in Ruby 1.8.6?

I think I have found a minor buffer overflow in string.c in Ruby 1.8.6. 
  I could very easily be wrong.  I would appreciate feedback either way.

Roughly around line 739, we have the following code:
VALUE
rb_str_cat(str, ptr, len)
     VALUE str;
     const char *ptr;
     long len;
{
     if (len < 0) {
	rb_raise(rb_eArgError, "negative string size (or size too big)");
     }
     if (FL_TEST(str, STR_ASSOC)) {
	rb_str_modify(str);
	REALLOC_N(RSTRING(str)->ptr, char, RSTRING(str)->len+len);
	memcpy(RSTRING(str)->ptr + RSTRING(str)->len, ptr, len);
	RSTRING(str)->len += len;
	RSTRING(str)->ptr[RSTRING(str)->len] = '\0'; /* sentinel */
	return str;
     }

     return rb_str_buf_cat(str, ptr, len);
}

I believe the REALLOC_N line is incorrect.  Instead of:
REALLOC_N(RSTRING(str)->ptr, char, RSTRING(str)->len+len);
I believe it should be:
REALLOC_N(RSTRING(str)->ptr, char, RSTRING(str)->len+len+1);

Without this, the subsequent call to 
RSTRING(str)->ptr[RSTRING(str)->len] = '\0'; accesses memory outside of 
the allocated buffer.

I welcome confirmation of this error or a brief explanation as to why I 
am mistaken.

Thank you for your time.


Gmane