Simple PWN - 0x14(Simple HEAP)

Simple PWN - 0x14(Simple HEAP)

tags: CTF PWN eductf

Version: Ubuntu 20.04

HEAP background

Advanced Binary Exploitation (Pwn) - Heap Exploitation SS111-Pwn2

Allocate a memory

Original Code

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

int main()
{
    void *ptr;
    ptr = malloc(0x30);
    return 0;
}
$ sudo gcc -o simple_heap simple_heap.c -no-pie

Analyze

  • Before executing malloc, there is no heap space in memory layout
  • After… And the size is 0x21000 that is 135168 bytes = 132 kB**main arena(大餅乾)**

  • main arena DON’T BE PANIC!!! We have useful tool to parse it automatically → pwngdb from AngelBoy

How about if we free the memory?

Original Code

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

int main()
{
    void *ptr;
    ptr = malloc(0x30);
    free(ptr)
    return 0;
}
  • Note that 0x30is for Tcache bin size

Analyze

  • Before freeing memory, we can observe the memory that system gave to us. The structure and meaning is as below. Header said we have no previous chunk(the first 8 bytes is 0x0) and the size of current chunk is 0x40. In addition, the last byte is 0001 means p flag is 1. Moreover, the data section told us that the system actually gave us a memory with size 0x30
  • After freeing…You can see that 0x40 has an address that we just free

How about we malloc another 0x30 and free it later?

Original Code

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

int main()
{
    void *ptr, *ptr2;
    ptr = malloc(0x30);
    ptr2 = malloc(0x30);
    free(ptr2);
    free(ptr);
    return 0;
}

Analyze

  • After malloc, before free
  • After free…, it’s a singly linked list(單向linked list)
  • Observe the memory we free, the metadata of ptr point to the initial data section of ptr2
  • In addition, the PREV_INUSE bit will maintain 1 even the previous chunk is free.

tcache_entry

Refer to lecture - SS111-Pwn2 So, we can use heap to check the situation In addition, tcache_entry will point to the data section instead of header like other bin

Reference

Advanced Binary Exploitation (Pwn) - Heap Exploitation