OS : Red Hat Linux 6.2
heap.c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *fd;
// Allocating memory on the heap
char *userinput = malloc(20);
char *outputfile = malloc(20);
if(argc < 2)
{
printf("Usage: %s <string to be written to /tmp/notes>\n", argv[0]);
exit(0);
}
// Copy data into heap memory
strcpy(outputfile, "/tmp/notes");
strcpy(userinput, argv[1]);
// Print out some debug messages
printf("---DEBUG--\n");
printf("[*] userinput @ %p: %s\n", userinput, userinput);
printf("[*] outputfile @ %p: %s\n", outputfile, outputfile);
printf("[*] distance between: %d\n", outputfile - userinput);
printf("----------\n\n");
// Writing the data out to the file.
printf("Writing to \"%s\" to the end of %s...\n", userinput, outputfile);
fd = fopen(outputfile, "a");
if (fd == NULL)
{
fprintf(stderr, "error opening %s\n", outputfile);
exit(1);
}
fprintf(fd, "%s\n", userinput);
fclose(fd);
return 0;
}
위 코드는 힙 오버플로우를 이해하기 위한 예제 코드 이다. 해당 코드는 간단하게 인자로 주는 문자열을 /tmp/notes 파일에 저장하는 코드 이다.
하지만 인자를 24개 이상 주게 되면 outputfile 부분을 덮어 쓸 수 있다. 이로 인해 우리는 원하는 파일에 원하는 메세지를 삽입할 수 있게 된다.
위와 같이 /etc/passwd 파일에 원하는 문자열을 삽입하여 루트권한을 획득한 화면이다.
Point!
파일 쓰기 관련된 프로그램에서 malloc 으로 변수를 선언할 경우 의심해보도록 하자...