#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
void alarm_handler()
{
puts("TIME OUT");
exit(-1);
}
void initialize()
{
setvbuf(stdin, NULL, _IONBF, 0);
setvbuf(stdout, NULL, _IONBF, 0);
signal(SIGALRM, alarm_handler);
alarm(30);
}
void get_shell()
{
system("/bin/sh");
}
int main()
{
char buf[256];
int size;
initialize();
signal(SIGSEGV, get_shell);
printf("Size: ");
scanf("%d", &size);
if (size > 256 || size < 0)
{
printf("Buffer Overflow!\n");
exit(0);
}
printf("Data: ");
read(0, buf, size - 1);
return 0;
}
size가 0이라면 read(0, buf, -1)이 실행된다.
read 함수의 세 번째 인자는 size_t 자료형으로 받고, 이는 unsigned 형태이다.
따라서 형 변환이 발생하게 되고, 그 값은 이 된다. 즉 256바이트 넘게 read를 할 수 있게 된다.
이는 충분히 BOF 취약점으로 넘어가게 되며 segmentation fault가 뜨게 된다.
nc로 쉘을 딸 수 있다.