HEAP

Heap 与 Stack 的根本区别

  1. Stack (LIFO)

  2. Heap

  • 任意顺序分配/释放
  • 内存块可以乱序释放
  • 由程序员负责 free
  • 需要记录大量 metadata

Heap exploitation = 攻击 glibc malloc 的实现,不是攻击业务代码本身。

malloc/free 的基础概念

void *p = malloc(size)

glibc:

  • 找到适当大小的空闲 chunk
  • 返回一块至少 size 的内存
  • 前面会附带 metadata(chunk header)

Free:free(p)

  • chunk会变成 “free chunk”, payload 会被 “回收” 为链表结点内部的指针结构
  • 所有 free chunk 会被放入不同 bin(tcache, fastbin, unsorted, smll, large)

Chunk的结构

  1. Allocated chunk(in-use chunk)
  2. Free chunk (未使用 chunk)

Chunk 大小对齐

  • 16 bytes

三类chunk

  1. Allocated chunks
  2. Free chunks
  3. Top chunk / Wilderness chunk

glibc 2.39 5类bins

  1. Tcache
  • size 7
  • 单链表
  1. Fastbins
  • 小 (<=0x80)
  • 单链表
  • 不会合并
  • 下次 malloc 优先使用
  1. Unsorted bin

  2. Small bins

  3. Large bins

Heap 典型漏洞类型

  1. Use-After-Free (UAF)
  • 写 UAF
  • 读 UAF
  1. Double Free
free(a);
free(b);
free(a);

Heap攻击流程

  1. Identify bug type
  • Use- After-Free
  • double free
  • heap overflow
  1. Explain its impact on heap metadate

  2. Link to allocator behaviour

  3. Show gained primitive

  • arbitrary malloc
  • arbitrary write
  • libc leak
  1. Show final impact