Libc Heap

Conceptos básicos del montón

El montón es básicamente el lugar donde un programa podrá almacenar datos cuando solicite datos llamando a funciones como malloc, calloc... Además, cuando esta memoria ya no sea necesaria, estará disponible llamando a la función free.

Como se muestra, está justo después de donde se carga el binario en la memoria (ver la sección [heap]):

Asignación básica de fragmentos

Cuando se solicita almacenar algunos datos en el montón, se asigna un espacio del montón para ello. Este espacio pertenecerá a un bin y solo se reservará para el fragmento los datos solicitados + el espacio de los encabezados del bin + el desplazamiento mínimo del tamaño del bin. El objetivo es reservar la menor cantidad de memoria posible sin complicar la búsqueda de cada fragmento. Para esto, se utiliza la información de fragmento de metadatos para saber dónde está cada fragmento usado/libre.

Existen diferentes formas de reservar el espacio, principalmente dependiendo del bin utilizado, pero una metodología general es la siguiente:

  • El programa comienza solicitando cierta cantidad de memoria.

  • Si en la lista de fragmentos hay alguno disponible lo suficientemente grande para cumplir con la solicitud, se utilizará.

  • Esto incluso podría significar que parte del fragmento disponible se utilizará para esta solicitud y el resto se agregará a la lista de fragmentos.

  • Si no hay ningún fragmento disponible en la lista pero aún hay espacio en la memoria del montón asignada, el administrador del montón crea un nuevo fragmento.

  • Si no hay suficiente espacio en el montón para asignar el nuevo fragmento, el administrador del montón solicita al kernel que expanda la memoria asignada al montón y luego use esta memoria para generar el nuevo fragmento.

  • Si todo falla, malloc devuelve nulo.

Tenga en cuenta que si la memoria solicitada supera un umbral, se utilizará mmap para asignar la memoria solicitada.

Arenas

En aplicaciones multihilo, el administrador del montón debe evitar condiciones de carrera que podrían provocar bloqueos. Inicialmente, esto se hacía utilizando un mutex global para garantizar que solo un hilo pudiera acceder al montón a la vez, pero esto causaba problemas de rendimiento debido al cuello de botella inducido por el mutex.

Para abordar esto, el asignador de montón ptmalloc2 introdujo "arenas", donde cada arena actúa como un montón separado con sus propias estructuras de datos y mutex, permitiendo que múltiples hilos realicen operaciones de montón sin interferir entre sí, siempre y cuando utilicen arenas diferentes.

La arena "principal" predeterminada maneja las operaciones de montón para aplicaciones de un solo hilo. Cuando se agregan nuevos hilos, el administrador del montón les asigna arenas secundarias para reducir la contención. Primero intenta adjuntar cada nuevo hilo a una arena no utilizada, creando nuevas si es necesario, hasta un límite de 2 veces el número de núcleos de CPU para sistemas de 32 bits y 8 veces para sistemas de 64 bits. Una vez que se alcanza el límite, los hilos deben compartir arenas, lo que puede provocar contención potencial.

A diferencia de la arena principal, que se expande utilizando la llamada al sistema brk, las arenas secundarias crean "submontones" utilizando mmap y mprotect para simular el comportamiento del montón, lo que permite flexibilidad en la gestión de la memoria para operaciones multihilo.

Submontones

Los submontones sirven como reservas de memoria para las arenas secundarias en aplicaciones multihilo, lo que les permite crecer y gestionar sus propias regiones de montón de forma independiente al montón principal. Así es como los submontones difieren del montón inicial y cómo operan:

  1. Montón inicial vs. Submontones:

  • El montón inicial se encuentra directamente después del binario del programa en la memoria, y se expande utilizando la llamada al sistema sbrk.

  • Los submontones, utilizados por las arenas secundarias, se crean a través de mmap, una llamada al sistema que asigna una región de memoria especificada.

  1. Reserva de memoria con mmap:

  • Cuando el administrador del montón crea un submontón, reserva un bloque grande de memoria a través de mmap. Esta reserva no asigna memoria de inmediato; simplemente designa una región que otros procesos del sistema o asignaciones no deben utilizar.

  • Por defecto, el tamaño reservado para un submontón es de 1 MB para procesos de 32 bits y 64 MB para procesos de 64 bits.

  1. Expansión gradual con mprotect:

  • La región de memoria reservada inicialmente se marca como PROT_NONE, lo que indica que el kernel no necesita asignar memoria física a este espacio aún.

  • Para "expandir" el submontón, el administrador del montón utiliza mprotect para cambiar los permisos de página de PROT_NONE a PROT_READ | PROT_WRITE, lo que hace que el kernel asigne memoria física a las direcciones previamente reservadas. Este enfoque paso a paso permite que el submontón se expanda según sea necesario.

  • Una vez que se agota todo el submontón, el administrador del montón crea un nuevo submontón para continuar con la asignación.

heap_info

Esta estructura asigna información relevante del montón. Además, la memoria del montón podría no ser continua después de más asignaciones, esta estructura también almacenará esa información.

// From https://github.com/bminor/glibc/blob/a07e000e82cb71238259e674529c37c12dc7d423/malloc/arena.c#L837

typedef struct _heap_info
{
mstate ar_ptr; /* Arena for this heap. */
struct _heap_info *prev; /* Previous heap. */
size_t size;   /* Current size in bytes. */
size_t mprotect_size; /* Size in bytes that has been mprotected
PROT_READ|PROT_WRITE.  */
size_t pagesize; /* Page size used when allocating the arena.  */
/* Make sure the following data is properly aligned, particularly
that sizeof (heap_info) + 2 * SIZE_SZ is a multiple of
MALLOC_ALIGNMENT. */
char pad[-3 * SIZE_SZ & MALLOC_ALIGN_MASK];
} heap_info;

malloc_state

Cada montón (principal o de otras arenas de hilos) tiene una estructura malloc_state. Es importante notar que la estructura malloc_state de la arena principal es una variable global en la libc (por lo tanto, ubicada en el espacio de memoria de la libc). En el caso de las estructuras malloc_state de los montones de hilos, están ubicadas dentro del "montón" del hilo correspondiente.

Hay algunas cosas interesantes para notar de esta estructura (ver código en C a continuación):

  • __libc_lock_define (, mutex); está ahí para asegurarse de que esta estructura del montón sea accedida por 1 hilo a la vez

  • Flags:

#define NONCONTIGUOUS_BIT (2U)

#define contiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) == 0) #define noncontiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) != 0) #define set_noncontiguous(M) ((M)->flags |= NONCONTIGUOUS_BIT) #define set_contiguous(M) ((M)->flags &= ~NONCONTIGUOUS_BIT)

* El `mchunkptr bins[NBINS * 2 - 2];` contiene **punteros** a los **primeros y últimos fragmentos** de los **contenedores** pequeños, grandes y desordenados (el -2 es porque el índice 0 no se usa)
* Por lo tanto, el **primer fragmento** de estos contenedores tendrá un **puntero hacia atrás a esta estructura** y el **último fragmento** de estos contenedores tendrá un **puntero hacia adelante** a esta estructura. Lo que básicamente significa que si puedes **filtrar estas direcciones en la arena principal** tendrás un puntero a la estructura en la **libc**.
* Las estructuras `struct malloc_state *next;` y `struct malloc_state *next_free;` son listas enlazadas de arenas
* El fragmento `top` es el último "fragmento", que es básicamente **todo el espacio restante del montón**. Una vez que el fragmento superior está "vacío", el montón está completamente utilizado y necesita solicitar más espacio.
* El fragmento `last reminder` proviene de casos en los que no está disponible un fragmento de tamaño exacto y, por lo tanto, se divide un fragmento más grande, una parte restante del puntero se coloca aquí.
```c
// From https://github.com/bminor/glibc/blob/a07e000e82cb71238259e674529c37c12dc7d423/malloc/malloc.c#L1812

struct malloc_state
{
/* Serialize access.  */
__libc_lock_define (, mutex);

/* Flags (formerly in max_fast).  */
int flags;

/* Set if the fastbin chunks contain recently inserted free blocks.  */
/* Note this is a bool but not all targets support atomics on booleans.  */
int have_fastchunks;

/* Fastbins */
mfastbinptr fastbinsY[NFASTBINS];

/* Base of the topmost chunk -- not otherwise kept in a bin */
mchunkptr top;

/* The remainder from the most recent split of a small request */
mchunkptr last_remainder;

/* Normal bins packed as described above */
mchunkptr bins[NBINS * 2 - 2];

/* Bitmap of bins */
unsigned int binmap[BINMAPSIZE];

/* Linked list */
struct malloc_state *next;

/* Linked list for free arenas.  Access to this field is serialized
by free_list_lock in arena.c.  */
struct malloc_state *next_free;

/* Number of threads attached to this arena.  0 if the arena is on
the free list.  Access to this field is serialized by
free_list_lock in arena.c.  */
INTERNAL_SIZE_T attached_threads;

/* Memory allocated from the system in this arena.  */
INTERNAL_SIZE_T system_mem;
INTERNAL_SIZE_T max_system_mem;
};

malloc_chunk

Esta estructura representa un fragmento particular de memoria. Los diversos campos tienen diferentes significados para fragmentos asignados y no asignados.

// https://github.com/bminor/glibc/blob/master/malloc/malloc.c
struct malloc_chunk {
INTERNAL_SIZE_T      mchunk_prev_size;  /* Size of previous chunk, if it is free. */
INTERNAL_SIZE_T      mchunk_size;       /* Size in bytes, including overhead. */
struct malloc_chunk* fd;                /* double links -- used only if this chunk is free. */
struct malloc_chunk* bk;
/* Only used for large blocks: pointer to next larger size.  */
struct malloc_chunk* fd_nextsize; /* double links -- used only if this chunk is free. */
struct malloc_chunk* bk_nextsize;
};

typedef struct malloc_chunk* mchunkptr;

Como se comentó anteriormente, estos fragmentos también tienen metadatos, muy bien representados en esta imagen:

Los metadatos suelen ser 0x08B indicando el tamaño actual del fragmento utilizando los últimos 3 bits para indicar:

  • A: Si es 1, proviene de un submontón; si es 0, está en la arena principal

  • M: Si es 1, este fragmento es parte de un espacio asignado con mmap y no es parte de un montón

  • P: Si es 1, el fragmento anterior está en uso

Luego, el espacio para los datos del usuario, y finalmente 0x08B para indicar el tamaño del fragmento anterior cuando el fragmento está disponible (o para almacenar los datos del usuario cuando está asignado).

Además, cuando está disponible, los datos del usuario se utilizan para contener también algunos datos:

  • fd: Puntero al siguiente fragmento

  • bk: Puntero al fragmento anterior

  • fd_nextsize: Puntero al primer fragmento en la lista que es más pequeño que él mismo

  • bk_nextsize: Puntero al primer fragmento en la lista que es más grande que él mismo

Observa cómo al enlazar la lista de esta manera se evita la necesidad de tener una matriz donde se registra cada fragmento individualmente.

Punteros de Fragmentos

Cuando se utiliza malloc, se devuelve un puntero al contenido que se puede escribir (justo después de los encabezados), sin embargo, al administrar fragmentos, se necesita un puntero al comienzo de los encabezados (metadatos). Para estas conversiones se utilizan estas funciones:

// https://github.com/bminor/glibc/blob/master/malloc/malloc.c

/* Convert a chunk address to a user mem pointer without correcting the tag.  */
#define chunk2mem(p) ((void*)((char*)(p) + CHUNK_HDR_SZ))

/* Convert a user mem pointer to a chunk address and extract the right tag.  */
#define mem2chunk(mem) ((mchunkptr)tag_at (((char*)(mem) - CHUNK_HDR_SZ)))

/* The smallest possible chunk */
#define MIN_CHUNK_SIZE        (offsetof(struct malloc_chunk, fd_nextsize))

/* The smallest size we can malloc is an aligned minimal chunk */

#define MINSIZE  \
(unsigned long)(((MIN_CHUNK_SIZE+MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK))

Alineación y tamaño mínimo

El puntero al fragmento y 0x0f deben ser 0.

// From https://github.com/bminor/glibc/blob/a07e000e82cb71238259e674529c37c12dc7d423/sysdeps/generic/malloc-size.h#L61
#define MALLOC_ALIGN_MASK (MALLOC_ALIGNMENT - 1)

// https://github.com/bminor/glibc/blob/a07e000e82cb71238259e674529c37c12dc7d423/sysdeps/i386/malloc-alignment.h
#define MALLOC_ALIGNMENT 16


// https://github.com/bminor/glibc/blob/master/malloc/malloc.c
/* Check if m has acceptable alignment */
#define aligned_OK(m)  (((unsigned long)(m) & MALLOC_ALIGN_MASK) == 0)

#define misaligned_chunk(p) \
((uintptr_t)(MALLOC_ALIGNMENT == CHUNK_HDR_SZ ? (p) : chunk2mem (p)) \
& MALLOC_ALIGN_MASK)


/* pad request bytes into a usable size -- internal version */
/* Note: This must be a macro that evaluates to a compile time constant
if passed a literal constant.  */
#define request2size(req)                                         \
(((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE)  ?             \
MINSIZE :                                                      \
((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)

/* Check if REQ overflows when padded and aligned and if the resulting
value is less than PTRDIFF_T.  Returns the requested size or
MINSIZE in case the value is less than MINSIZE, or 0 if any of the
previous checks fail.  */
static inline size_t
checked_request2size (size_t req) __nonnull (1)
{
if (__glibc_unlikely (req > PTRDIFF_MAX))
return 0;

/* When using tagged memory, we cannot share the end of the user
block with the header for the next chunk, so ensure that we
allocate blocks that are rounded up to the granule size.  Take
care not to overflow from close to MAX_SIZE_T to a small
number.  Ideally, this would be part of request2size(), but that
must be a macro that produces a compile time constant if passed
a constant literal.  */
if (__glibc_unlikely (mtag_enabled))
{
/* Ensure this is not evaluated if !mtag_enabled, see gcc PR 99551.  */
asm ("");

req = (req + (__MTAG_GRANULE_SIZE - 1)) &
~(size_t)(__MTAG_GRANULE_SIZE - 1);
}

return request2size (req);
}

Obtener datos del Chunk y modificar metadatos

Estas funciones funcionan recibiendo un puntero a un chunk y son útiles para verificar/establecer metadatos:

  • Verificar flags del chunk

// From https://github.com/bminor/glibc/blob/master/malloc/malloc.c


/* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */
#define PREV_INUSE 0x1

/* extract inuse bit of previous chunk */
#define prev_inuse(p)       ((p)->mchunk_size & PREV_INUSE)


/* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */
#define IS_MMAPPED 0x2

/* check for mmap()'ed chunk */
#define chunk_is_mmapped(p) ((p)->mchunk_size & IS_MMAPPED)


/* size field is or'ed with NON_MAIN_ARENA if the chunk was obtained
from a non-main arena.  This is only set immediately before handing
the chunk to the user, if necessary.  */
#define NON_MAIN_ARENA 0x4

/* Check for chunk from main arena.  */
#define chunk_main_arena(p) (((p)->mchunk_size & NON_MAIN_ARENA) == 0)

/* Mark a chunk as not being on the main arena.  */
#define set_non_main_arena(p) ((p)->mchunk_size |= NON_MAIN_ARENA)
  • Tamaños y punteros a otros bloques

/*
Bits to mask off when extracting size

Note: IS_MMAPPED is intentionally not masked off from size field in
macros for which mmapped chunks should never be seen. This should
cause helpful core dumps to occur if it is tried by accident by
people extending or adapting this malloc.
*/
#define SIZE_BITS (PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)

/* Get size, ignoring use bits */
#define chunksize(p) (chunksize_nomask (p) & ~(SIZE_BITS))

/* Like chunksize, but do not mask SIZE_BITS.  */
#define chunksize_nomask(p)         ((p)->mchunk_size)

/* Ptr to next physical malloc_chunk. */
#define next_chunk(p) ((mchunkptr) (((char *) (p)) + chunksize (p)))

/* Size of the chunk below P.  Only valid if !prev_inuse (P).  */
#define prev_size(p) ((p)->mchunk_prev_size)

/* Set the size of the chunk below P.  Only valid if !prev_inuse (P).  */
#define set_prev_size(p, sz) ((p)->mchunk_prev_size = (sz))

/* Ptr to previous physical malloc_chunk.  Only valid if !prev_inuse (P).  */
#define prev_chunk(p) ((mchunkptr) (((char *) (p)) - prev_size (p)))

/* Treat space at ptr + offset as a chunk */
#define chunk_at_offset(p, s)  ((mchunkptr) (((char *) (p)) + (s)))
  • Insue bit

/* extract p's inuse bit */
#define inuse(p)							      \
((((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size) & PREV_INUSE)

/* set/clear chunk as being inuse without otherwise disturbing */
#define set_inuse(p)							      \
((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size |= PREV_INUSE

#define clear_inuse(p)							      \
((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size &= ~(PREV_INUSE)


/* check/set/clear inuse bits in known places */
#define inuse_bit_at_offset(p, s)					      \
(((mchunkptr) (((char *) (p)) + (s)))->mchunk_size & PREV_INUSE)

#define set_inuse_bit_at_offset(p, s)					      \
(((mchunkptr) (((char *) (p)) + (s)))->mchunk_size |= PREV_INUSE)

#define clear_inuse_bit_at_offset(p, s)					      \
(((mchunkptr) (((char *) (p)) + (s)))->mchunk_size &= ~(PREV_INUSE))
  • Establecer encabezado y pie de página (cuando los números de fragmento están en uso)

/* Set size at head, without disturbing its use bit */
#define set_head_size(p, s)  ((p)->mchunk_size = (((p)->mchunk_size & SIZE_BITS) | (s)))

/* Set size/use field */
#define set_head(p, s)       ((p)->mchunk_size = (s))

/* Set size at footer (only when chunk is not in use) */
#define set_foot(p, s)       (((mchunkptr) ((char *) (p) + (s)))->mchunk_prev_size = (s))
  • Obtener el tamaño de los datos reales utilizables dentro del chunk

#pragma GCC poison mchunk_size
#pragma GCC poison mchunk_prev_size

/* This is the size of the real usable data in the chunk.  Not valid for
dumped heap chunks.  */
#define memsize(p)                                                    \
(__MTAG_GRANULE_SIZE > SIZE_SZ && __glibc_unlikely (mtag_enabled) ? \
chunksize (p) - CHUNK_HDR_SZ :                                    \
chunksize (p) - CHUNK_HDR_SZ + (chunk_is_mmapped (p) ? 0 : SIZE_SZ))

/* If memory tagging is enabled the layout changes to accommodate the granule
size, this is wasteful for small allocations so not done by default.
Both the chunk header and user data has to be granule aligned.  */
_Static_assert (__MTAG_GRANULE_SIZE <= CHUNK_HDR_SZ,
"memory tagging is not supported with large granule.");

static __always_inline void *
tag_new_usable (void *ptr)
{
if (__glibc_unlikely (mtag_enabled) && ptr)
{
mchunkptr cp = mem2chunk(ptr);
ptr = __libc_mtag_tag_region (__libc_mtag_new_tag (ptr), memsize (cp));
}
return ptr;
}

Ejemplos

Ejemplo rápido de Heap

Ejemplo rápido de heap de https://guyinatuxedo.github.io/25-heap/index.html pero en arm64:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main(void)
{
char *ptr;
ptr = malloc(0x10);
strcpy(ptr, "panda");
}

Establece un punto de interrupción al final de la función principal y descubramos dónde se almacenó la información:

Es posible ver que la cadena panda se almacenó en 0xaaaaaaac12a0 (que fue la dirección dada como respuesta por malloc dentro de x0). Revisando 0x10 bytes antes, es posible ver que el 0x0 representa que el fragmento anterior no está en uso (longitud 0) y que la longitud de este fragmento es 0x21.

Los espacios adicionales reservados (0x21-0x10=0x11) provienen de los encabezados añadidos (0x10) y 0x1 no significa que se reservaron 0x21B, sino que los últimos 3 bits de la longitud del encabezado actual tienen algunos significados especiales. Dado que la longitud siempre está alineada en bloques de 16 bytes (en máquinas de 64 bits), estos bits en realidad nunca se van a utilizar por el número de longitud.

0x1:     Previous in Use     - Specifies that the chunk before it in memory is in use
0x2:     Is MMAPPED          - Specifies that the chunk was obtained with mmap()
0x4:     Non Main Arena      - Specifies that the chunk was obtained from outside of the main arena

Ejemplo de Multihilo

Multihilo

```c #include #include #include #include #include

void* threadFuncMalloc(void* arg) { printf("Hello from thread 1\n"); char* addr = (char*) malloc(1000); printf("After malloc and before free in thread 1\n"); free(addr); printf("After free in thread 1\n"); }

void* threadFuncNoMalloc(void* arg) { printf("Hello from thread 2\n"); }

int main() { pthread_t t1; void* s; int ret; char* addr;

printf("Before creating thread 1\n"); getchar(); ret = pthread_create(&t1, NULL, threadFuncMalloc, NULL); getchar();

printf("Before creating thread 2\n"); ret = pthread_create(&t1, NULL, threadFuncNoMalloc, NULL);

printf("Before exit\n"); getchar();

return 0; }

</details>

Depurando el ejemplo anterior es posible ver cómo al principio solo hay 1 arena:

<figure><img src="../../.gitbook/assets/image (1).png" alt=""><figcaption></figcaption></figure>

Luego, después de llamar al primer hilo, el que llama a malloc, se crea una nueva arena:

<figure><img src="../../.gitbook/assets/image (1) (1).png" alt=""><figcaption></figcaption></figure>

y dentro de ella se pueden encontrar algunos fragmentos:

<figure><img src="../../.gitbook/assets/image (2).png" alt=""><figcaption></figcaption></figure>

## Bins y Asignaciones/Liberaciones de Memoria

Verifique cuáles son los bins y cómo están organizados y cómo se asigna y libera memoria en:

<div data-gb-custom-block data-tag="content-ref" data-url='bins-and-memory-allocations.md'>

[bins-and-memory-allocations.md](bins-and-memory-allocations.md)

</div>

## Verificaciones de Seguridad de Funciones de Heap

Las funciones involucradas en el heap realizarán ciertas comprobaciones antes de realizar sus acciones para intentar asegurarse de que el heap no esté corrompido:

<div data-gb-custom-block data-tag="content-ref" data-url='heap-memory-functions/heap-functions-security-checks.md'>

[heap-functions-security-checks.md](heap-memory-functions/heap-functions-security-checks.md)

</div>

## Referencias

* [https://azeria-labs.com/heap-exploitation-part-1-understanding-the-glibc-heap-implementation/](https://azeria-labs.com/heap-exploitation-part-1-understanding-the-glibc-heap-implementation/)
* [https://azeria-labs.com/heap-exploitation-part-2-glibc-heap-free-bins/](https://azeria-labs.com/heap-exploitation-part-2-glibc-heap-free-bins/)

Last updated