Saltar al contenido ForoHackers

malloc(n * size): the multiplication that eats your buffer

CGestión de memoriaProgramación segura
#984 · null_terminated_hopes · · Denunciar

A pattern I keep finding in reviews:

size_t n = read_count_from_header();
struct item *p = malloc(n * sizeof *p);
if (!p) return -1;
for (size_t i = 0; i < n; i++)
    p[i] = read_item();

The multiplication can wrap. If n * sizeof *p exceeds the range of size_t, the result silently wraps around to a small number, malloc happily returns a tiny block, and the loop then writes n items into it. The program writes far past the end of the allocation. Unsigned overflow is well-defined in C, which makes this worse: no UB, no warning, just a wrong size.

Safer options:

/* 1. let the allocator check it */
struct item *p = calloc(n, sizeof *p);

/* 2. check by hand */
if (n > SIZE_MAX / sizeof *p) return -1;
struct item *p = malloc(n * sizeof *p);

/* 3. reallocarray(NULL, n, sizeof *p) where available */

calloc is required to detect the overflow and fail. Also, validate n against what the file can possibly contain before allocating at all: a header that claims four billion items in a 2 KB file is lying.

The bug is old, boring, and still shows up in code written last week. As is tradition.

#1331 · heap_spray_and_pray · · Denunciar

This is the textbook way many heap overflows begin: the size is computed from attacker-controlled data, the check is missing, and the allocation ends up smaller than the writes. Worth noting that UBSan will not flag it by default since unsigned wrap is defined. Clang has an opt-in unsigned-overflow check, noisy but useful on a code base you are auditing in a lab.

#1332 · tabs_over_spaces_42 · · Denunciar

I would put the safe version in a tiny helper (xmalloc_array(n, size)) and ban the raw multiplication in review. One place to get it right, a grep-able pattern for everything else.

#1333 · null_terminated_hopes · · Denunciar

Agreed. A helper plus a lint rule. Though I admit I find some comfort in knowing the bug will outlive both of us.

Inicia sesión o únete para responder.