Buffer Overflow
Buffer Overflow
#
A simple function
void f() {
int i;
int buf[9];
for (i=0; i < 5; i++)buf[4+i] = buf[4-i] = 0;}#A simple functionvoid f() {int i;int buf[9];for (i=0; i < 10; i++)buf[4+i] = buf[4-i] = 0;}#The call stackA data structure that stores information about function calls in a programIn X86 the stack is bottom-upThe stack bottom is at a high addressThe stack top is at a low addressThe stack grows towards lower addressesBottom of stackTop of stack#ImplementationRegister %esp points to the top of the stackThe push instruction pushes a value onto the stackxorl %eax,%eaxpushl %eaxpop pops a valuepopl %eax%esp0%esp#Calling a functionCalling a function pushes a stack frame onto the stackThe stack base pointer register (%ebp) points to the frame of the current functionReturn pops the stack frameStack frame%esp%ebp#Calling conventionsCaller does:Save registersPush argumentsCall functionCallee doesSave %ebpSet new %ebpCreate space for local variablesCallers stack frame%esp%ebpSaved RegistersArgumentsReturn addressSaved %ebpLocal Variables%esp%esp%esp%esp%esp%ebp%esp, %ebp#Exampleint g(int a, int b) {int x = a + 1;int y = b + 2;return x*y;}g:pushl %ebpmovl%esp, %ebpsubl$16, %espmovl8(%ebp), %eaxaddl$1, %eaxmovl%eax, -8(%ebp)movl12(%ebp), %eaxaddl$2, %eaxmovl%eax, -4(%ebp)movl-8(%ebp), %eaximull -4(%ebp), %eaxleaveretbaReturn addressSaved %ebpyx%ebp%esp%esp%esp%ebp%esp, %ebp%esp#Back to a simple functionvoid f() {int i;char buf[9];for (i=0; i < 10; i++)buf[4+i] = buf[4-i] = 0;}i00buf1000200000300000004000000000500000000000000000000Saved %ebpReturn address#05ibufSaved %ebpReturn address155255355455With a minor changevoid f() {int i;char buf[9];for (i=0; i < 10; i++)buf[4+i] = buf[4-i] = 5;}55556557#bufStack smashingvoid f() {char buf[512];gets(buf);doSomething(buf);}The attacker diverts execution to data it injectedHow does the attacker know where to jump to?Callers stack frameReturn addressSaved %ebpgets stack framebufbufReturn addressSaved %ebpCallers stack frame#NOP SledA sequence of NOP instructions leading to the attack codeNOPNOPNOP…NOPNOPAttackCode#Problem patternsAny use of getsstrcpy, sprintf, strcat, etc.sprintf(buf, “https://%s/index.html”, argv[1])buf=new char[strlen(argv[1])]strcpy(buf, argv[1])wchar_t buf[MAXLEN];swprintf(buf, sizeof(buf), “%s”, argv[1]);Any low-level implementation of similar codewhile (*src != ‘;’)*dst++ = *src++;*dst = ‘