一、源代码仓库
源码链接:how2heap
二、源代码
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int main()
{
fprintf(stderr, "This file demonstrates a simple double-free attack with fastbins.\n");
fprintf(stderr, "Allocating 3 buffers.\n");
int *a = malloc(8);
int *b = malloc(8);
int *c = malloc(8);
fprintf(stderr, "1st malloc(8): %p\n", a);
fprintf(stderr, "2nd malloc(8): %p\n", b);
fprintf(stderr, "3rd malloc(8): %p\n", c);
fprintf(stderr, "Freeing the first one...\n");
free(a);
fprintf(stderr, "If we free %p again, things will crash because %p is at the top of the free list.\n", a, a);
// free(a);
fprintf(stderr, "So, instead, we'll free %p.\n", b);
free(b);
fprintf(stderr, "Now, we can free %p again, since it's not the head of the free list.\n", a);
free(a);
fprintf(stderr, "Now the free list has [ %p, %p, %p ]. If we malloc 3 times, we'll get %p twice!\n", a, b, a, a);
a = malloc(8);
b = malloc(8);
c = malloc(8);
fprintf(stderr, "1st malloc(8): %p\n", a);
fprintf(stderr, "2nd malloc(8): %p\n", b);
fprintf(stderr, "3rd malloc(8): %p\n", c);
assert(a == c);
}
三、个人翻译
//gcc -g -o esay_double_free esay_double_free.c
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int main()
{
fprintf(stderr, "该文件简单地演示了一下对fastbins的double free攻击.\n");
fprintf(stderr, "申请三个堆块.\n");
int *a = malloc(8);
int *b = malloc(8);
int *c = malloc(8);
fprintf(stderr, "1st malloc(8): %p\n", a); //输出堆块地址
fprintf(stderr, "2nd malloc(8): %p\n", b);
fprintf(stderr, "3rd malloc(8): %p\n", c);
fprintf(stderr, "释放第一个堆块...\n");
free(a);
fprintf(stderr, "如果我们再次释放第一个chunk %p , 程序将会崩溃 , 因为此时 %p 位于 free chunk 链表的顶部.\n", a, a);
//检查机制会检查当前free的chunk与即将放入的bins中的第一个chunk是否相同,相同则程序崩溃。
// free(a);
fprintf(stderr, "所以我们要先释放第二个chunk %p.\n", b);
free(b);
fprintf(stderr, "现在,我们可以再次释放第一个chunk %p 了 , 因为此时它已经不是 free chunk 链表的中的第一个chunk了.\n", a);
free(a);
fprintf(stderr, "\n现在我们的free shunk 链表中有:\n\t\t[ %p , %p , %p ]\n如果我们现在申请三个堆块,我们将申请 %p 两次!\n\n", a, b, a, a);
a = malloc(8);
b = malloc(8);
c = malloc(8);
fprintf(stderr, "1st malloc(8): %p\n", a);
fprintf(stderr, "2nd malloc(8): %p\n", b);
fprintf(stderr, "3rd malloc(8): %p\n", c);
assert(a == c);
}
四、调试
1、运行环境:ubuntu16.04 - glibc 2.23
2、一些用到的 gdb 指令
pwndbg> b main
pwndbg> r
pwndbg> ni
pwndbg> heap
pwndbg> top_chunk
pwndbg> bin
pwndbg> x/40gx 0x602000
3、调试结果
①:释放第一个堆块
②:释放第二个堆块
③:再次释放第一个堆块
④:申请一个堆块,奇怪的事情发生了
⑤:再次申请一个堆块
⑥:第6次malloc
4、fastbins 中的空闲堆块状态
5、小结
这个代码主要是介绍 glibc 2.23 存在的 double free 这一现象,但并没有介绍如何利用 double free 。