04 Buffer Overflow
04 Buffer Overflow
04 Buffer Overflow
Outline
● Understanding of Stack Layout
● Vulnerable code
● Challenges in exploitation
● Shellcode
● Countermeasures
Program Memory Stack
a,b, ptr
ptr points to
the memory
here
y
x
Order of the function arguments in stack
Function Call Stack
void f(int a, int b)
{
int x;
}
void main()
{
f(1,2);
printf("hello world");
}
Stack Layout for Function Call Chain
main()
foo()
bar()
Vulnerable Program
Reading 300 bytes of data from
badfile.
• Invalid instruction
• Non-existing address
• Access violation
• Attacker’s code Malicious code to gain access
How to Run Malicious Code
Environment Setup
Creation of The Malicious Input (badfile)
Task A : Find the offset distance between the base of the buffer and return address.
Task B : Find the address to place the shellcode
Task A : Distance Between Buffer Base
Address and Return Address
Challenges :
• Loader Issue
• Zeros in the code
Shelllcode
• Assembly code (machine instructions) for launching a shell.
• Registers used:
eax = 0x0000000b (11) : Value of system call execve()
ebx = address to “/bin/sh”
ecx = address of the argument array.
• argv[0] = the address of “/bin/sh”
• argv[1] = 0 (i.e., no more arguments)
edx = zero (no environment variables are passed).
int 0x80: invoke execve()
Shellcode
To randomize the start location of the stack that is every time the code
is loaded in the memory, the stack address changes.
1
2
3
ASLR : Defeat It
1. Turn on address randomization (countermeasure)
% sudo sysctl -w kernel.randomize_va_space=2