Skip to content

Commit

Permalink
[klibc] malloc: Fail if requested size > PTRDIFF_MAX
Browse files Browse the repository at this point in the history
malloc() adds some overhead to the requested size, which may result in
an integer overflow and subsequent buffer overflow if it is close to
SIZE_MAX.  It should fail if size is large enough for this to happen.

Further, it's not legal for a C object to be larger than
PTRDIFF_MAX (half of SIZE_MAX) as pointer arithmetic within it could
overflow.  So return failure immediately if size is greater than that.

CVE-2021-31873

Signed-off-by: Ben Hutchings <ben@decadent.org.uk>
  • Loading branch information
bwhacks committed Apr 29, 2021
1 parent 7f6626d commit a31ae8c
Showing 1 changed file with 9 additions and 0 deletions.
9 changes: 9 additions & 0 deletions usr/klibc/malloc.c
Expand Up @@ -147,6 +147,15 @@ void *malloc(size_t size)
if (size == 0)
return NULL;

/* Various additions below will overflow if size is close to
SIZE_MAX. Further, it's not legal for a C object to be
larger than PTRDIFF_MAX (half of SIZE_MAX) as pointer
arithmetic within it could overflow. */
if (size > PTRDIFF_MAX) {
errno = ENOMEM;
return NULL;
}

/* Add the obligatory arena header, and round up */
size = (size + 2 * sizeof(struct arena_header) - 1) & ARENA_SIZE_MASK;

Expand Down

0 comments on commit a31ae8c

Please sign in to comment.