Memory corruption after failed xrealloc_sized in pm_buffer_append_length
Mantenedores costumam responder em até 1 dia
Um pull request relacionado já foi integrado.
- #4352 de @kddnewton — integrado
Avaliação
- Dificuldade
- 3/5
- Tempo estimado
- 1-2 dias
- Facilidade para iniciantes
- 55/100
Direção de pesquisa
Start with src/buffer.c and trace pm_buffer_append_length and its callers; the issue also describes a lexer path in src/prism.c, in parser_lex under PM_LEX_STRING. Reproduce the failed reallocation followed by another append, then check that allocation failure cannot leave the buffer in a state that permits a write through a null pointer. The issue gives no test file or command, so locate the relevant buffer and lexer tests and verify the regression there.
Escrita pelo modelo de indexação a partir do texto da issue.
Descrição
I reported this to [email protected] and [email protected] suggested a github issue.
// src/buffer.c
static PRISM_INLINE bool
pm_buffer_append_length(pm_buffer_t *buffer, size_t length) {
if (length == 0) return false;
size_t next_length = buffer->length + length;
const size_t original_capacity = buffer->capacity;
if (next_length > buffer->capacity) {
if (buffer->capacity == 0) {
buffer->capacity = 1;
}
while (next_length > buffer->capacity) {
buffer->capacity *= 2;
}
buffer->value = xrealloc_sized(buffer->value, buffer->capacity, original_capacity);
if (buffer->value == NULL) return false;
}
buffer->length = next_length;
return true;
}
static PRISM_INLINE void
pm_buffer_append(pm_buffer_t *buffer, const void *source, size_t length) {
size_t cursor = buffer->length;
if (pm_buffer_append_length(buffer, length)) {
memcpy(buffer->value + cursor, source, length);
}
}
When xrealloc_sized(buffer->value, buffer->capacity, original_capacity) fails and returns NULL, pm_buffer_append_length:
- Overwrites
buffer->value = NULL(0x0), leaking the previous buffer allocation, - Leaves
buffer->capacityset to the newly doubled capacity, - Leaves
buffer->lengthset to the pre-append offset (cursor), and - Returns
falseinstead of callingPRISM_OOM()
Because buffer->capacity is already updated to the larger value while buffer->value is NULL and buffer->length remains at cursor, any subsequent append to the same pm_buffer_t with cursor + payload_len <= buffer->capacity succeeds on the fast path (next_length <= buffer->capacity is true) and executes:
memcpy(buffer->value + cursor, source, payload_len);
// i.e. memcpy((char *)NULL + cursor, source, payload_len);
On native targets, this causes a write fault at NULL + cursor. In 32-bit WebAssembly (wasm32), where address 0x00000000 is valid linear memory (containing the Wasm shadow stack and .rodata/.data), this turns a failed buffer reallocation during lexing or serialization into an arbitrary low-memory write primitive (memcpy((void *)cursor, payload, payload_len)).
Making a low-memory write gadget
1. Directly call pm_buffer_append_bytes (for demonstration purposes)
Any sequence of three pm_buffer_append_bytes calls on the same pm_buffer_t where the second call exceeds available heap memory (so xrealloc_sized returns NULL) and the third call fits within the newly doubled buffer->capacity will write to NULL + target_cursor:
#include "prism.h"
#include "prism/buffer.h"
#include "prism/internal/buffer.h"
#include <stdlib.h>
#include <string.h>
int main(void) {
pm_buffer_t buffer = { 0 };
size_t target_cursor = 0x800;
// 1. Advance buffer.length to target_cursor (0x800):
uint8_t *prefix = calloc(1, target_cursor);
pm_buffer_append_bytes(&buffer, prefix, target_cursor);
// Now: buffer.value != NULL, buffer.length == 0x800, buffer.capacity == 0x800
// 2. Request a growth that exceeds available heap memory so xrealloc_sized returns NULL
// (e.g., under RLIMIT_AS / Wasm max-memory, or a large chunk near SIZE_MAX / 2):
size_t unallocatable = (size_t) 1 << (sizeof(size_t) * 8 - 2);
pm_buffer_append_bytes(&buffer, prefix, unallocatable);
// xrealloc_sized returns NULL!
// Now: buffer.value == NULL, buffer.length == 0x800, buffer.capacity >= unallocatable
// 3. Append a small payload (0x800 + 16 <= buffer.capacity):
// pm_buffer_append_length sees next_length <= buffer.capacity, skips xrealloc_sized,
// returns true, and executes memcpy((char *)NULL + 0x800, "rubyrubyrubyruby", 16)!
pm_buffer_append_bytes(&buffer, (uint8_t *)"rubyrubyrubyruby", 16);
free(prefix);
return 0;
}
In lldb,
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x800)
frame #0: 0x000000018d807f08 libsystem_platform.dylib`_platform_memmove + 424
libsystem_platform.dylib`_platform_memmove:
-> 0x18d807f08 <+424>: str x6, [x3], #0x8
0x18d807f0c <+428>: subs x2, x2, #0x8
0x18d807f10 <+432>: b.hs 0x18d807f04 ; <+420>
0x18d807f14 <+436>: adds x2, x2, #0x8
Target 0: (testcase) stopped.
(lldb) bt
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x800)
* frame #0: 0x000000018d807f08 libsystem_platform.dylib`_platform_memmove + 424
frame #1: 0x0000000100011ab4 testcase`pm_buffer_append(buffer=0x000000016fdfe890, source=0x00000001000c0780, length=16) at buffer.c:92:9
frame #2: 0x0000000100011aec testcase`pm_buffer_append_bytes(buffer=0x000000016fdfe890, value="rubyrubyrubyruby", length=16) at buffer.c:153:5
frame #3: 0x00000001000b2074 testcase`main at test.c:26:5
frame #4: 0x000000018d427e80 dyld`start + 6688
2. Triggering Through pm_parse via a Single Escaped Ruby String Literal
In src/prism.c (parser_lex, case PM_LEX_STRING:), when a double-quoted string contains backslash escape sequences, the lexer scans from backslash to backslash in a while (breakpoint != NULL) loop, appending each literal slice between backslashes into a single token_buffer.buffer (pm_buffer_t) via pm_buffer_append_bytes before emitting PM_TOKEN_STRING_CONTENT.
This allows a single Ruby string literal of the form:
"<target_cursor - 1 spaces>\n<middle_padding_chunk>\u{}<16-byte payload>"
to drive the exact three-step sequence on token_buffer.buffer:
- Step 1 — Position
buffer->lengthattarget_cursor(e.g.,0x800):- The lexer encounters the first escape sequence
\naftertarget_cursor - 1spaces. - It initializes
token_buffer.bufferand appends thetarget_cursor - 1spaces plus the decoded0x0abyte, settingbuffer->length = target_cursor(0x800) andbuffer->capacity = 0x800.
- The lexer encounters the first escape sequence
- Step 2 — Trigger a failed
xrealloc_sizedon<middle_padding_chunk>:- Next, the lexer scans forward to the second backslash (
\u{}), spanning<middle_padding_chunk>, and callspm_buffer_append_bytes(&token_buffer.buffer, slice, middle_len). pm_buffer_append_lengthroundsbuffer->capacityup to the next power of two >= target_cursor + middle_len and callsxrealloc_sized.- Whenever that doubled capacity exceeds the remaining free heap — for example, in a 64 MB
wasm32module (or underRLIMIT_AS), a ~17 MB<middle_padding_chunk>forcesbuffer->capacityto double to 32 MB (0x2000000), which cannot be allocated alongside the input string and existing 16 MB buffer (or if earlier allocations in the file have already filled most of the heap, even a 1 MB chunk forcing a 2 MBxrealloc_sizedwill fail) —xrealloc_sizedreturnsNULL. pm_buffer_append_lengthsetsbuffer->value = NULL, leavesbuffer->capacityat the newly doubled size (e.g., 32 MB or 2 MB) andbuffer->lengthattarget_cursor(0x800), and returnsfalse(skipping thememcpyof<middle_padding_chunk>).
- Next, the lexer scans forward to the second backslash (
- Step 3 — Subsequent append after
\u{}writes to(char *)NULL + target_cursor:- Next, the lexer processes
\u{}(an empty Unicode escape, which writes 0 bytes and leavesbuffer->lengthunchanged attarget_cursor) and then reaches the closing"after the 16-byte<payload>("rubyrubyrubyruby"). - The lexer calls
pm_buffer_append_bytes(&token_buffer.buffer, payload, 16):cursor = buffer->length(0x800).pm_buffer_append_lengthcomputesnext_length = 0x800 + 16 = 0x810.- Because
next_length <= buffer->capacityis true,pm_buffer_append_lengthskipsxrealloc_sized, setsbuffer->length = 0x810, and returnstrue. pm_buffer_appendthen executes:memcpy((char *)NULL + 0x800, "rubyrubyrubyruby", 16);
- Next, the lexer processes
Suggested Fix
Update pm_buffer_append_length in src/buffer.c to check for addition and multiplication overflow and call PRISM_OOM() whenever xrealloc_sized returns NULL (matching pm_arena_zalloc and xmalloc handling elsewhere in Prism):
static PRISM_INLINE bool
pm_buffer_append_length(pm_buffer_t *buffer, size_t length) {
if (length == 0) return false;
size_t next_length = buffer->length + length;
if (next_length < buffer->length) {
PRISM_OOM();
}
const size_t original_capacity = buffer->capacity;
if (next_length > buffer->capacity) {
if (buffer->capacity == 0) {
buffer->capacity = 1;
}
while (next_length > buffer->capacity) {
if (buffer->capacity > SIZE_MAX / 2) {
PRISM_OOM();
}
buffer->capacity *= 2;
}
buffer->value = xrealloc_sized(buffer->value, buffer->capacity, original_capacity);
if (buffer->value == NULL) {
PRISM_OOM();
}
}
buffer->length = next_length;
return true;
}
- Linguagem predominante
- C
- Estrelas
- 1k
- Forks
- 202
- Merge médio
- 6h 4min
- PRs com merge (30d)
- 81
Preparar o ambiente
- Sem Dockerfile nem arquivo Docker Compose
- Sem modelo de pull request
- Ler o guia de contribuição
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Issues semelhantes
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 78/100
Mantenedores costumam responder em até 1 dia
-
follow-up Prio 📌
Dificuldade 1/5 Menos de uma hora Facilidade para iniciantes 84/100
Mantenedores costumam responder em até 1 dia
-
area: test kind: bug preview-effort: small priority: low
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 65/100
Mantenedores costumam responder em até 1 dia
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 65/100
libsdl-org/SDL#16684 ·
Mantenedores costumam responder em até 1 dia
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 82/100