Buffer Overflows, C/C++

Prevent buffer overflows

A buffer overflow is a form of software security vulnerability. Occurs when a program tries to store more data in a fixed length buffer. The extra data corrupts-overwrites data in memory addresses adjacent to the allocated buffer. This will often cause the program to crash or operate incorrectly.

Stack buffer overflow

Stack buffer overflow occurs when a program tries to store more data to a fixed length buffer located on the stack segment.

Heap overflow

A heap overflow occurs in the heap segment. Memory on the heap is dynamically allocated at runtime by using functions such as malloc, realloc and calloc.

Examples

1
2
3
4
5
6
7
8
9
#include <string.h>
#include <stdio.h>
 
int main (int argc, char **argv)
{
    char  c[100];
    strcpy(c, argv[1]);
}
<span style="text-decoration: underline;">

In this example if the user provides an argument larger or equal to 100 characters will result in corruption of the stack. To store 100 characters we need a buffer which has a 101 characters length. Don’t forget the zero byte character!

1
2
3
4
5
6
7
8
#include <string.h>
#include <stdio.h>
 
int main (int argc, char **argv)
{
    char *arr = (char *)malloc(strlen(argv[1]));
    strcpy(arr, argv[1]);
}

In this example whatever argument the user provides, it will often result in corruption of the heap. Sometimes the code above will work because the heap allocates more space than you request.

Prevention

> Validate input.

> Use higher-level programming languages.

> Avoid using functions such as printf(), strcpy(), strcat(), sprintf(), vsprintf() and gets ().

> Specify a width for the %s format when you use function scanf().

> Use products such as libsafe, StackShield, SecureStack and StackGuard.

> Use systems which offer non-executable stacks.

> Use safer versions of functions such as strncpy(), strncat(),
snprintf(), vsnprintf() instead.