首页 > 代码库 > how2heap分析系列:1_first_fit

how2heap分析系列:1_first_fit

一些基础知识不再赘述,可以自行搜索解决

程序源码first_fit.c

 1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4  5 int main() 6 { 7 printf("This file doesn‘t demonstrate an attack, but shows the nature of glibc‘s allocator.\n"); 8 printf("glibc uses a first-fit algorithm to select a free chunk.\n"); 9 printf("If a chunk is free and large enough, malloc will select this chunk.\n");10 printf("This can be exploited in a use-after-free situation.\n");11 12 printf("Allocating 2 buffers. They can be large, don‘t have to be fastbin.\n");13 char* a = malloc(512);14 char* b = malloc(256);15 char* c;16 17 printf("1st malloc(512): %p\n", a);18 printf("2nd malloc(256): %p\n", b);19 printf("we could continue mallocing here...\n");20 printf("now let‘s put a string at a that we can read later \"this is A!\"\n");21 strcpy(a, "this is A!");22 printf("first allocation %p points to %s\n", a, a);23 24 printf("Freeing the first one...\n");25 free(a);26 27 printf("We don‘t need to free anything again. As long as we allocate less than 512, it will end up at %p\n", a);28 29 printf("So, let‘s allocate 500 bytes\n");30 c = malloc(500);31 printf("3rd malloc(500): %p\n", c);32 printf("And put a different string here, \"this is C!\"\n");33 strcpy(c, "this is C!");34 printf("3rd allocation %p points to %s\n", c, c);35 printf("first allocation %p points to %s\n", a, a);36 printf("If we reuse the first allocation, it now holds the data from the third allocation.");37 }

 

执行程序后的输出

junmoxiao@ubuntu:~/pwn/how2heap$ ./first_fit This file doesnt demonstrate an attack, but shows the nature of glibcs allocator.glibc uses a first-fit algorithm to select a free chunk.If a chunk is free and large enough, malloc will select this chunk.This can be exploited in a use-after-free situation.Allocating 2 buffers. They can be large, dont have to be fastbin.1st malloc(512): 0x245b4202nd malloc(256): 0x245b630we could continue mallocing here...now lets put a string at a that we can read later "this is A!"first allocation 0x245b420 points to this is A!Freeing the first one...We dont need to free anything again. As long as we allocate less than 512, it will end up at 0x245b420So, lets allocate 500 bytes3rd malloc(500): 0x245b420And put a different string here, "this is C!"3rd allocation 0x245b420 points to this is C!first allocation 0x245b420 points to this is C!If we reuse the first allocation, it now holds the data from the third allocation.

 

这个案例只是讲了glibc分配chunk时的first fit原则,可以用于use after free漏洞,比较简单,对照看看源码和输出即可,

how2heap分析系列:1_first_fit