Libc Heap

Tip

AWS 해킹 배우기 및 연습하기:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기: HackTricks Training GCP Red Team Expert (GRTE) Azure 해킹 배우기 및 연습하기: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks 지원하기

Heap Basics

Heap은 프로그램이 malloc, calloc 등과 같은 함수를 호출해 데이터를 요청할 때 데이터를 저장하는 공간이다. 또한 이 메모리가 더 이상 필요하지 않으면 free 함수를 호출해 반환된다.

As it’s shown, its just after where the binary is being loaded in memory (check the [heap] section):

Basic Chunk Allocation

데이터를 heap에 저장하도록 요청하면 heap의 일부 공간이 할당된다. 이 공간은 bin에 속하며 요청한 데이터 + bin headers의 공간 + 최소 bin 크기 오프셋만 chunk로 예약된다. 목표는 각 chunk의 위치를 찾기 복잡하게 만들지 않으면서 가능한 최소 메모리만 예약하는 것이다. 이를 위해 metadata chunk 정보가 사용되어 각 사용/해제된 chunk의 위치를 파악한다.

공간을 예약하는 방법은 사용되는 bin에 따라 다르지만, 일반적인 절차는 다음과 같다:

  • 프로그램이 일정량의 메모리를 요청한다.
  • chunk 목록에서 요청을 충족할 수 있는 충분히 큰 가용 chunk가 있으면 그것을 사용한다.
  • 이는 가용 chunk의 일부만 이 요청에 사용되고 남은 부분은 chunk 목록에 다시 추가될 수 있음을 의미한다.
  • 목록에 사용 가능한 chunk가 없지만 아직 할당된 heap 메모리에 공간이 남아있다면, heap 관리자는 새 chunk를 생성한다.
  • 새 chunk를 할당할만한 heap 공간이 부족하면, heap 관리자는 커널에 heap에 할당된 메모리를 확장하도록 요청한 뒤 이 메모리를 사용해 새 chunk를 만든다.
  • 모든 것이 실패하면 malloc은 null을 반환한다.

요청한 메모리가 임계값을 넘으면, **mmap**이 사용되어 요청한 메모리를 매핑한다.

Arenas

멀티스레드 애플리케이션에서 heap 관리자는 충돌로 인한 크래시를 막기 위해 race conditions를 방지해야 한다. 초기에는 전역 mutex를 사용해 한 번에 하나의 스레드만 heap에 접근하도록 했지만, 이는 mutex로 인한 병목 현상 때문에 성능 문제를 일으켰다.

이를 해결하기 위해 ptmalloc2 heap allocator는 “arenas“를 도입했다. 각 arena는 자체 데이터 구조와 mutex를 가진 별도의 heap처럼 동작하여, 서로 다른 arena를 사용하는 한 여러 스레드가 서로 간섭하지 않고 heap 작업을 수행할 수 있다.

기본 “main” arena는 단일 스레드 애플리케이션의 heap 작업을 처리한다. 새로운 스레드가 추가되면 heap 관리자는 경쟁을 줄이기 위해 이들에게 secondary arenas를 할당한다. 관리자는 먼저 사용되지 않는 arena에 새로운 스레드를 붙이려 시도하고, 필요하면 새 arena를 생성하며, 32비트 시스템에서는 CPU 코어 수의 2배, 64비트 시스템에서는 8배까지 생성한다. 한도에 도달하면 스레드들이 arena를 공유해야 하므로 경쟁이 발생할 수 있다.

main arena는 brk 시스템 콜을 사용해 확장되는 반면, secondary arenas는 mmapmprotect를 사용해 subheaps를 생성하여 heap 동작을 시뮬레이션하므로 멀티스레드 작업에 대한 메모리 관리에 유연성을 제공한다.

Subheaps

Subheaps는 멀티스레드 애플리케이션에서 secondary arenas가 별도로 성장하고 자신만의 heap 영역을 관리할 수 있도록 하는 메모리 예약 공간이다. Subheaps가 초기 heap과 어떻게 다른지 및 어떻게 동작하는지는 다음과 같다:

  1. Initial Heap vs. Subheaps:
  • 초기 heap은 바이너리 바로 뒤에 위치하며 sbrk 시스템 콜을 사용해 확장된다.
  • secondary arenas에서 사용하는 subheaps는 지정된 메모리 영역을 매핑하는 시스템 콜인 mmap을 통해 생성된다.
  1. Memory Reservation with mmap:
  • heap 관리자가 subheap을 생성할 때, mmap을 통해 큰 블록의 메모리를 예약한다. 이 예약은 즉시 물리 메모리를 할당하지 않으며, 단지 다른 시스템 프로세스나 할당이 해당 영역을 사용하지 못하도록 영역을 지정하는 것이다.
  • 기본적으로 subheap의 예약 크기는 32비트 프로세스에서 1 MB, 64비트 프로세스에서 64 MB이다.
  1. Gradual Expansion with mprotect:
  • 예약된 메모리 영역은 처음에 PROT_NONE로 표시되어 커널이 아직 물리 메모리를 할당할 필요가 없음을 나타낸다.
  • subheap을 “성장“시키기 위해 heap 관리자는 mprotect를 사용하여 페이지 권한을 PROT_NONE에서 PROT_READ | PROT_WRITE로 변경하고, 이로 인해 커널은 이전에 예약된 주소에 물리 메모리를 할당한다. 이 단계별 접근 방식은 subheap이 필요에 따라 확장되도록 허용한다.
  • 전체 subheap이 소진되면 heap 관리자는 새로운 subheap을 생성하여 할당을 계속한다.

heap_info

이 struct는 heap에 대한 관련 정보를 할당한다. 또한 추가 할당 이후에는 heap 메모리가 연속적이지 않을 수 있으므로, 이 struct는 그 정보를 저장하기도 한다.

// 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

각 heap (main arena 또는 다른 스레드의 arenas)에는 malloc_state 구조체가 있습니다.
특히 main arena malloc_state 구조체는 libc 안의 전역 변수(따라서 libc 메모리 공간에 위치)라는 점이 중요합니다.
스레드들의 heap에 있는 malloc_state 구조체들은 각 스레드의 “heap” 내부에 위치합니다.

다음은 이 구조체에서 주목할 만한 몇 가지 사항입니다(아래 C 코드 참고):

  • __libc_lock_define (, mutex);는 heap의 이 구조체에 한 번에 한 스레드만 접근하도록 보장하기 위해 존재합니다.

  • 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)


- `mchunkptr bins[NBINS * 2 - 2];`는 small, large 및 unsorted bins의 first와 last chunks에 대한 pointers를 포함합니다( -2는 index 0이 사용되지 않기 때문입니다).
- 따라서 이 bins들의 **first chunk**는 이 구조체로 향하는 **backwards pointer**를 가지며, **last chunk**는 이 구조체로 향하는 **forward pointer**를 가집니다. 즉, main arena에서 이러한 주소를 leak할 수 있다면 libc 안의 구조체를 가리키는 포인터를 얻게 됩니다.
- `struct malloc_state *next;` 및 `struct malloc_state *next_free;` 구조체들은 arenas의 linked list입니다.
- `top` chunk은 마지막 "chunk"로, 기본적으로 남아있는 모든 heap 공간입니다. `top` chunk가 "비워지면", heap이 완전히 사용된 것이며 더 많은 공간을 요청해야 합니다.
- `last reminder` chunk는 정확한 크기의 chunk가 없을 때 더 큰 chunk를 분할하여 남는 부분의 포인터가 여기에 놓이는 경우에서 옵니다.
```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

이 구조체는 특정 메모리 chunk를 나타냅니다. 각 필드는 allocated 및 unallocated chunk에 대해 서로 다른 의미를 가집니다.

// 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;

As commented previously, these chunks also have some metadata, very good represented in this image:

https://azeria-labs.com/wp-content/uploads/2019/03/chunk-allocated-CS.png

The metadata is usually 0x08B indicating the current chunk size using the last 3 bits to indicate:

  • A: If 1 it comes from a subheap, if 0 it’s in the main arena
  • M: If 1, this chunk is part of a space allocated with mmap and not part of a heap
  • P: If 1, the previous chunk is in use

Then, the space for the user data, and finally 0x08B to indicate the previous chunk size when the chunk is available (or to store user data when it’s allocated).

Moreover, when available, the user data is used to contain also some data:

  • fd: Pointer to the next chunk
  • bk: Pointer to the previous chunk
  • fd_nextsize: Pointer to the first chunk in the list is smaller than itself
  • bk_nextsize: Pointer to the first chunk the list that is larger than itself

https://azeria-labs.com/wp-content/uploads/2019/03/chunk-allocated-CS.png

Tip

Note how liking the list this way prevents the need to having an array where every single chunk is being registered.

Chunk Pointers

When malloc is used a pointer to the content that can be written is returned (just after the headers), however, when managing chunks, it’s needed a pointer to the begining of the headers (metadata).
For these conversions these functions are used:

// 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))

정렬 및 최소 크기

chunk에 대한 pointer와 0x0f는 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);
}

Note that for calculating the total space needed it’s only added SIZE_SZ 1 time because the prev_size field can be used to store data, therefore only the initial header is needed.

Chunk 데이터 가져오기 및 metadata 변경

이 함수들은 chunk에 대한 pointer를 받아 동작하며 metadata를 확인/설정하는 데 유용합니다:

  • chunk의 flags 확인
// 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)
  • 크기 및 pointers to other chunks
/*
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)))
  • 사용 중 비트
/* 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))
  • 헤더와 푸터 설정 (chunk nos 사용 중일 때
/* 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))
  • 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;
}

예제

빠른 Heap 예제

https://guyinatuxedo.github.io/25-heap/index.html의 빠른 heap 예제이지만 arm64용:

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

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

main 함수의 끝에 breakpoint를 설정하고 정보가 어디에 저장되었는지 알아보자:

문자열 panda가 0xaaaaaaac12a0에 저장된 것을 확인할 수 있다(이 주소는 x0 안에서 malloc이 반환한 주소다). 0x10 바이트 앞을 확인해보면 0x0previous chunk is not used(길이 0)을 나타내며, 이 청크의 길이는 0x21이다.

추가로 예약된 공간(0x21-0x10=0x11)은 added headers(0x10)에서 온 것이며, 0x1은 0x21B가 예약되었다는 의미가 아니라 현재 헤더 길이의 마지막 3비트가 특별한 의미를 가진다는 뜻이다. 길이는 항상 16-byte aligned(64bits machines)이므로, 이 비트들은 실제 길이 숫자에서는 사용되지 않는다.

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

멀티스레딩 예제

멀티스레딩 ```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>

이전 예제를 디버깅하면 시작할 때 arena가 1개만 있음을 확인할 수 있다:

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

그런 다음 첫 번째 thread, 즉 malloc을 호출하는 thread를 실행하면 새로운 arena가 생성된다:

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

그 내부에는 몇몇 chunks가 존재한다:

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

## Bins & Memory Allocations/Frees

bins가 무엇인지, 어떻게 조직되는지, 그리고 메모리가 어떻게 할당되고 해제되는지 확인하라:


<a class="content_ref" href="bins-and-memory-allocations.md"><span class="content_ref_label">Bins & Memory Allocations</span></a>

## Heap 함수 보안 검사

Heap과 관련된 함수들은 동작을 수행하기 전에 heap이 손상되지 않았는지 확인하기 위해 특정 검사를 수행한다:


<a class="content_ref" href="heap-memory-functions/heap-functions-security-checks.md"><span class="content_ref_label">Heap Functions Security Checks</span></a>

## musl mallocng exploitation notes (Alpine)

- **Slab group/slot grooming for huge linear copies:** mallocng sizeclasses는 슬롯이 비어 있을 때 완전히 `munmap()`되는 mmap()'d 그룹을 사용한다. 긴 선형 복사(~0x15555555 bytes)의 경우, span을 매핑된 상태로 유지(해제된 그룹으로 인한 구멍을 피함)하고 victim allocation을 source slot에 인접하게 배치하라.
- **Cycling offset mitigation:** slot 재사용 시 mallocng은 slack이 추가 4-byte header를 수용할 때 user-data 시작을 `UNIT` (0x10) 배수만큼 앞당길 수 있다. 이로 인해 overwrite offsets(예: LSB pointer hits)가 이동한다. reuse counts를 제어하거나 slack이 없는 strides(예: stride 0x50의 Lua `Table` 객체는 offset 0을 보임)를 고수하지 않는 한 그렇다. offsets는 muslheap’s `mchunkinfo`로 검사하라:
```gdb
pwndbg> mchunkinfo 0x7ffff7a94e40
... stride: 0x140
... cycling offset : 0x1 (userdata --> 0x7ffff7a94e40)
  • Prefer runtime-object corruption over allocator metadata: mallocng mixes cookies/guarded out-of-band metadata, so target higher-level objects. In Redis’s Lua 5.1, Table->array points to an array of TValue tagged values; overwriting the LSB of a pointer in TValue->value (e.g., with the JSON terminator byte 0x22) can pivot references without touching malloc metadata.
  • Debugging stripped/static Lua on Alpine: 일치하는 Lua를 빌드하고, readelf -Ws로 심볼을 확인한 다음 objcopy --strip-symbol로 함수 심볼을 제거해 GDB에서 구조체 레이아웃을 노출시키세요. 그런 다음 Lua-aware pretty-printers (GdbLuaExtension for Lua 5.1)와 muslheap을 사용해 오버플로를 트리거하기 전에 stride/reserved/cycling-offset 값들을 확인하세요.

Case Studies

실제 버그에서 파생된 allocator-specific primitives를 연구하세요:

Virtualbox Slirp Nat Packet Heap Exploitation

Gnu Obstack Function Pointer Hijack

References

Tip

AWS 해킹 배우기 및 연습하기:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기: HackTricks Training GCP Red Team Expert (GRTE) Azure 해킹 배우기 및 연습하기: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks 지원하기