Libc Heap
Tip
Jifunze na fanya mazoezi ya AWS Hacking:
HackTricks Training AWS Red Team Expert (ARTE)
Jifunze na fanya mazoezi ya GCP Hacking:HackTricks Training GCP Red Team Expert (GRTE)
Jifunze na fanya mazoezi ya Azure Hacking:
HackTricks Training Azure Red Team Expert (AzRTE)
Support HackTricks
- Angalia mpango wa usajili!
- Jiunge na 💬 kikundi cha Discord au kikundi cha telegram au tufuatilie kwenye Twitter 🐦 @hacktricks_live.
- Shiriki mbinu za hacking kwa kuwasilisha PRs kwa HackTricks na HackTricks Cloud repos za github.
Misingi ya Heap
Heap ni sehemu ambapo programu inaweza kuhifadhi data inapohitaji kutumia memori, kwa kuita functions kama malloc, calloc… Zaidi ya hayo, pale memori hii inapokwisha kuwa muhimu inarejeshwa kwa kuita function free.
Kama inavyoonekana, iko tu baada ya sehemu binary kuingizwa kwenye memori (angalia sehemu ya [heap]):
.png)
Ugawaji wa Chunk Msingi
Wakati data inaombwa kuhifadhiwa kwenye heap, sehemu ya heap inatengwa kwake. Sehemu hii itakuwa sehemu ya bin na tu data iliyoombwa + eneo la headers za bin + offset ya ukubwa mdogo wa bin itahifadhiwa kwa chunk. Lengo ni kutenga memori chache iwezekanavyo bila kufanya ugunduzi wa kila chunk kuwa mgumu. Kwa hili, metadata ya chunk hutumiwa kujua wapi kila chunk iliyotumika/iliyo huru iko.
Kuna njia tofauti za kutenga nafasi kulingana na bin inayotumika, lakini mbinu ya jumla ni kama ifuatavyo:
- Programu inaanza kwa kuomba kiasi fulani cha memori.
- Ikiwa katika orodha ya chunks kuna moja ya kutosha kukidhi ombi, itatumika.
- Hii inaweza pia kumaanisha kwamba sehemu ya chunk iliyopo itatumika kwa ombi hili na iliyobaki itaongezwa kwenye orodha ya chunks.
- Ikiwa hakuna chunk inayopatikana kwenye orodha lakini bado kuna nafasi katika heap iliyotengwa, heap manager huunda chunk mpya.
- Ikiwa hakuna nafasi ya kutosha kwenye heap kuunda chunk mpya, heap manager huomba kernel kupanua memori iliyotengwa kwa heap kisha kutumia memori hiyo kuunda chunk mpya.
- Kama kila kitu kinashindwa,
mallocinarudisha null.
Kumbuka kwamba ikiwa kiasi cha memori kilichohitajika kinapopita kikomo, mmap itatumika kupangilia memori iliyohitajika.
Arenas
Katika multithreaded applications, heap manager lazima izui race conditions ambazo zinaweza kusababisha crashes. Awali, hili lilifanywa kwa kutumia global mutex kuhakikisha thread moja tu inaweza kufikia heap kwa wakati mmoja, lakini hii ilisababisha masuala ya utendaji kutokana na kizuizi kinachosababishwa na mutex.
Kwa kukabiliana na hili, ptmalloc2 heap allocator ilianzisha “arenas”, ambapo kila arena inafanya kazi kama heap tofauti yenye muundo wake wa data na mutex, kuruhusu threads nyingi kufanya operesheni za heap bila kuingiliana, mradi zinatumia arenas tofauti.
Arena ya chaguo-msingi “main” inashughulikia operesheni za heap kwa programu za single-threaded. Wakati threads mpya zinaongezwa, heap manager huzipa secondary arenas ili kupunguza contention. Kwanza inajaribu kuhusisha kila thread mpya na arena isiyotumika, ikitengeneza mpya inapohitajika, hadi mpaka wa mara 2 ya idadi ya CPU cores kwa mifumo ya 32-bit na mara 8 kwa mifumo ya 64-bit. Mara mpaka huo unapofikiwa, threads lazima zishirikiane arenas, jambo linaloweza kusababisha contention.
Tofauti na main arena, ambayo inapanuka kwa kutumia system call brk, secondary arenas huunda “subheaps” kwa kutumia mmap na mprotect kuiga tabia ya heap, kuruhusu urejeleo zaidi katika kusimamia memori kwa operesheni za multithreaded.
Subheaps
Subheaps hutumika kama akiba ya memori kwa secondary arenas katika programu multithreaded, zikiruhusu kukua na kusimamia maeneo yao ya heap tofauti na main heap. Hapa jinsi subheaps zinavyotofautiana na heap ya awali na jinsi zinavyofanya kazi:
- Initial Heap vs. Subheaps:
- Initial heap iko moja kwa moja baada ya binary ya programu kwenye memori, na inapanuka kwa kutumia system call
sbrk. - Subheaps, zinazotumika na secondary arenas, huundwa kupitia
mmap, system call inayopanga eneo maalum la memori.
- Memory Reservation with
mmap:
- Wakati heap manager anapounda subheap, anatenga block kubwa ya memori kupitia
mmap. Utengenezaji huu hauagawi memori mara moja; badala yake unatenga eneo ambalo mchakato mwingine wa mfumo au mgao haupaswi kutumia. - Kwa default, ukubwa uliotengwa kwa subheap ni 1 MB kwa michakato ya 32-bit na 64 MB kwa michakato ya 64-bit.
- Gradual Expansion with
mprotect:
- Eneo la memori lililotengwa awali limewekwa kama
PROT_NONE, ikionyesha kwamba kernel bado haidai kugawa memori ya kimwili kwa nafasi hii. - Ili “kukua” subheap, heap manager hutumia
mprotectkubadili ruhusa za kurasa kutokaPROT_NONEhadiPROT_READ | PROT_WRITE, kuchochea kernel kugawa memori ya kimwili kwa anwani zilizotengwa hapo awali. Njia hii hatua kwa hatua inaruhusu subheap kupanuka kadri inavyohitajika. - Mara subheap nzima inapochakaa, heap manager huunda subheap mpya ili kuendelea na ugawaji.
heap_info
Struct hii inahifadhi taarifa muhimu kuhusu heap. Zaidi ya hayo, memori ya heap inaweza isiwe mfululizo baada ya ugawaji zaidi; struct hii pia itahifadhi taarifa hiyo.
// 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
Kila heap (main arena au other threads arenas) ina malloc_state structure.
Ni muhimu kutambua kwamba main arena malloc_state structure ni global variable in the libc (hivyo ziko katika libc memory space).
Katika kesi ya malloc_state structures za heaps za threads, ziko ndani ya own thread “heap”.
Kuna mambo kadhaa ya kuvutia ya kutambua kutoka kwenye muundo huu (tazama C code hapa chini):
-
__libc_lock_define (, mutex);Iko ili kuhakikisha muundo huu kutoka kwenye heap unafikiwa na thread 1 kwa wakati -
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)
- The `mchunkptr bins[NBINS * 2 - 2];` contains **pointers** to the **first and last chunks** of the small, large and unsorted **bins** (the -2 is because the index 0 is not used)
- Therefore, the **first chunk** of these bins will have a **backwards pointer to this structure** and the **last chunk** of these bins will have a **forward pointer** to this structure. Which basically means that if you can l**eak these addresses in the main arena** utakuwa na pointer kwa muundo uliopo ndani ya **libc**.
- The structs `struct malloc_state *next;` and `struct malloc_state *next_free;` ni linked lists za arenas
- The `top` chunk ni chunk ya mwisho, ambayo kwa msingi ni **nafasi yote iliyobaki ya heap**. Mara `top` chunk inapokuwa "empty", heap imekwisha kabisa na inahitaji kuomba nafasi zaidi.
- The `last reminder` chunk hutokea katika matukio ambapo chunk ya ukubwa sawa haipatikani na kwa hivyo chunk kubwa hugawanywa, na sehemu iliyobaki (pointer) inawekwa hapa.
```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
Muundo huu unaonyesha kipande maalum cha kumbukumbu. Vipengele mbalimbali vina maana tofauti kwa chunks zilizotengwa na zisizotengwa.
// 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;
Kama ilivyotajwa hapo awali, chunks hizi pia zina metadata, zilizoonyeshwa vizuri katika picha hii:
.png)
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: Ikiwa 1 inatoka subheap, ikiwa 0 iko kwenye main arenaM: Ikiwa 1, chunk hii ni sehemu ya space allocated na mmap na si sehemu ya heapP: Ikiwa 1, previous chunk inatumika
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 chunkbk: Pointer to the previous chunkfd_nextsize: Pointer to the first chunk in the list that is smaller than itselfbk_nextsize: Pointer to the first chunk in the list that is larger than itself
.png)
https://azeria-labs.com/wp-content/uploads/2019/03/chunk-allocated-CS.png
Tip
Kumbuka jinsi kuunganisha list kwa njia hii kunazuia hitaji la kuwa na array ambapo kila chunk mmoja mmoja anasajiliwa.
Chunk Pointers
Wakati malloc inatumiwa, pointer kwa content inayoweza kuandikwa hurudishwa (mara tu baada ya headers), hata hivyo, wakati wa kusimamia chunks, inahitajika pointer kuelekea mwanzoni mwa headers (metadata).
Kwa conversions hizi functions zifuatazo zimetumika:
// 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))
Ulinganifu & ukubwa wa chini
Pointer kwa chunk na 0x0f lazima ziwe 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);
}
Kumbuka kwamba kwa kuhesabu jumla ya nafasi inayohitajika, SIZE_SZ inaongezwa mara 1 tu kwa sababu uwanja wa prev_size unaweza kutumika kuhifadhi data; kwa hivyo kichwa cha awali pekee kinahitajika.
Pata Chunk data na badilisha metadata
Funsi hizi zinafanya kazi kwa kupokea pointer kwa chunk na ni muhimu kwa kukagua/kuweka metadata:
- Kagua 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)
- Saizi na viashiria kwa chunks nyingine
/*
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))
- Weka head na footer (wakati chunk nos zikitumika
/* 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))
- Pata ukubwa wa data halisi inayoweza kutumika ndani ya 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;
}
Mifano
Mfano mfupi wa heap
Mfano mfupi wa heap kutoka https://guyinatuxedo.github.io/25-heap/index.html lakini katika arm64:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main(void)
{
char *ptr;
ptr = malloc(0x10);
strcpy(ptr, "panda");
}
Weka breakpoint mwishoni mwa main function na tuone wapi taarifa zilihifadhiwa:
.png)
Inaonekana kwamba string panda ilihifadhiwa kwenye 0xaaaaaaac12a0 (ambayo ilikuwa address iliyotolewa kama jibu na malloc ndani ya x0). Ukikagua 0x10 bytes kabla yake, inaonekana kwamba 0x0 inaonyesha kuwa previous chunk is not used (length 0) na kwamba urefu wa chunk hii ni 0x21.
Sehemu za ziada zilizotengwa (0x21-0x10=0x11) zinatokana na added headers (0x10) na 0x1 haimaanishi kwamba ilitengwa 0x21B, bali ni bits tatu za mwisho za urefu wa header ya sasa zilizo na maana maalum. Kwa kuwa urefu daima huwa 16-byte aligned (kwa mashine za 64bits), bits hizi kwa vitendo hazitawahi kutumika katika nambari ya urefu.
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
Mfano wa Multithreading
Multithread
```c #includevoid* 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>
Uchambuzi wa mfano uliopita unaonyesha jinsi mwanzoni kungekuwa na arena 1 tu:
<figure><img src="../../images/image (1) (1) (1) (1) (1) (1) (1) (1) (1).png" alt=""><figcaption></figcaption></figure>
Kisha, baada ya kuiita thread ya kwanza, ile inayoiita malloc, arena mpya imeundwa:
<figure><img src="../../images/image (1) (1) (1) (1) (1) (1) (1) (1) (1) (1).png" alt=""><figcaption></figcaption></figure>
na ndani yake baadhi ya chunks zinaonekana:
<figure><img src="../../images/image (2) (1) (1) (1) (1) (1).png" alt=""><figcaption></figcaption></figure>
## Bins & Memory Allocations/Frees
Angalia ni bins zipi zipo na jinsi zinaandaliwa na jinsi kumbukumbu inavyotengwa na kuachiliwa katika:
<a class="content_ref" href="bins-and-memory-allocations.md"><span class="content_ref_label">Bins & Memory Allocations</span></a>
## Heap Functions Security Checks
Functions zinazohusiana na heap zitafanya ukaguzi fulani kabla ya kutekeleza hatua zao ili kujaribu kuhakikisha heap haikuharibika:
<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 hutumia mmap()'d groups ambazo slots zao zinafanywa `munmap()` kabisa zinapokuwa tupu. Kwa nakala ndefu za mfululizo (~0x15555555 bytes), weka span ikibaki mapped (epuka mapengo yanayotokana na groups zilizotolewa) na weka victim allocation karibu na source slot.
- **Cycling offset mitigation:** On slot reuse mallocng inaweza kuendeleza user-data start kwa `UNIT` (0x10) multiples wakati slack inafaa extra 4-byte header. Hii inabadilisha overwrite offsets (mfano, LSB pointer hits) isipokuwa udhibiti reuse counts au ubaki kwa strides bila slack (mfano, Lua `Table` objects kwa stride 0x50 zinaonyesha offset 0). Angalia offsets na muslheap’s `mchunkinfo`:
```gdb
pwndbg> mchunkinfo 0x7ffff7a94e40
... stride: 0x140
... cycling offset : 0x1 (userdata --> 0x7ffff7a94e40)
- Prefer runtime-object corruption over allocator metadata: mallocng hutumia cookies/guarded out-of-band metadata, kwa hivyo lenga vitu vya kiwango cha juu zaidi. In Redis’s Lua 5.1,
Table->arraypoints to an array ofTValuetagged values; overwriting the LSB of a pointer inTValue->value(e.g., with the JSON terminator byte0x22) can pivot references without touching malloc metadata. - Debugging stripped/static Lua on Alpine: Jenga toleo la Lua linalofanana, orodhesha symbols kwa
readelf -Ws, futa function symbols kwa kutumiaobjcopy --strip-symbolili kufichua struct layouts katika GDB, kisha tumia Lua-aware pretty-printers (GdbLuaExtension for Lua 5.1) pamoja na muslheap kukagua stride/reserved/cycling-offset values kabla ya kuanzisha overflow.
Masomo ya Kesi
Chunguza primitives maalum za allocator zilizotokana na bug halisi:
Virtualbox Slirp Nat Packet Heap Exploitation
Gnu Obstack Function Pointer Hijack
Marejeo
- 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/
- Pumping Iron on the Musl Heap – Real World CVE-2022-24834 Exploitation on an Alpine mallocng Heap
- musl mallocng enframe (v1.2.4)
- muslheap GDB plugin
- GdbLuaExtension (Lua 5.1 support)
Tip
Jifunze na fanya mazoezi ya AWS Hacking:
HackTricks Training AWS Red Team Expert (ARTE)
Jifunze na fanya mazoezi ya GCP Hacking:HackTricks Training GCP Red Team Expert (GRTE)
Jifunze na fanya mazoezi ya Azure Hacking:
HackTricks Training Azure Red Team Expert (AzRTE)
Support HackTricks
- Angalia mpango wa usajili!
- Jiunge na 💬 kikundi cha Discord au kikundi cha telegram au tufuatilie kwenye Twitter 🐦 @hacktricks_live.
- Shiriki mbinu za hacking kwa kuwasilisha PRs kwa HackTricks na HackTricks Cloud repos za github.


