2. Buffer Overflow: the Basics
● Buffer overflow problems always have been associated with
security vulnerabilities.
● A buffer is a contiguous allocated chunk of memory, such as
an array or a pointer in C.
● In C and C++, there are no automatic bounds checking on
the buffer, which means a user can write past a buffer.
int main () {
int buffer[10];
buffer[20] = 10;
}
3. Problem with the program
● The above C program is a valid program, and
every compiler can compile it without any
errors.
● However, the program attempts to write
beyond the allocated memory for the buffer.
● Programs written in C/C++ languages, where
more focus is given to the programming
efficiency and code length than to the security
aspect.
4. Memory layout of a Process
primarily the program code, i.e., a series of executable
program instructions.
initialized and uninitialized
global data
allocated at run time
The heap holds dynamic variables. To
allocate memory, the heap uses the malloc
function or the new operator.
The stack is used to store function call-by
arguments, local variables and values of selected
registers
5. Example
void function (int a, int b, int c) {
char buffer1[5];
char buffer2[10]
FP is need to access a, b, c, buffer1 and buffer2 variables.
}
●
● All these variables are cleaned up from the stack as the
int main() { function terminates
function(1,2,3);
}
10 bytes
5 bytes
frame
pointer
6. Example 2
void function (char *str) {
char buffer[16];
strcpy (buffer, str);
}
int main () {
char *str = "This is greater than 16 bytes"; // length of str = 27 bytes
function (str);
}
● Guaranteed to cause unexpected behavior.
● String (str) of 27 bytes has been copied to a location (buffer) that has been allocated for only 16 bytes.
● The extra bytes run past the buffer and overwrites the space allocated for the FP & return addresses.
● This, in turn, corrupts the process stack.
This is a example how buffer overflow can overwrite a function's return address,
● which in turn can alter the program's execution path.
● Recall that a function's return address is the address of the next instruction in memory, which is executed
immediately after the function returns. Hacker might get a root shell by adding execution path to such code.
● Or place the code we are trying to execute in the buffer's overflowing area
7. Buffer Overflow Countermeasures
● The solutions proposed for buffer overflow problems mainly
target the prevention of large-scale system attacks through
the loopholes described above.
● None of the methods described above can claim to prevent
all possible attacks.
● Write secure code:
C library functions such as strcpy (), strcat (), sprintf () and
vsprintf () operate on null terminated strings and perform no
bounds checking.