Buffer Overflow explained through C code
Buffer overflow is a well known vulnerability . It is one of the most frequent attack types.
It uses input to a poorly implemented, but (in intention) completely harmless application, typically with root / administrator privileges. It results from input that is longer than the implementer intended. To understand its inner workings, we need to talk a little bit about how computers use memory.
Buffer Overflow through C language .
Lets take an example C program that has a this vulnerability . The vulnerability doesnt exist in the C language or the compiler but it exists in the strcpy function . This function is vulnerable to buffer overflow as it doesn’t check for the memory bounds of the data it copies .
Let study some real program examples that show the danger of such situations based on the C. In the examples,I have not implement any malicious code injection but just to show that the buffer can be overflow. Modern compilers normally provide overflow checking option during the compile/link time but during the run time it is quite difficult to check this problem without any extra protection mechanism such as using exception handling.
C code to Show Buffer overflow
#include <stdio.h> #include <string.h> #include <stdlib.h> //Author : Vanshit Malhotra //Demonstrate Buffer Overflow via Segmantation Fault int main(int argc, char *argv[]) { char mybuffer[5]; if (argc < 2) { printf("strcpy() NOT executed....\n"); printf("Syntax: %s <characters>\n", argv[0]); exit(0); } strcpy(mybuffer, argv[1]); printf("mybuffer content= %s\n", mybuffer); return 0; }
Here are the screenshots from the execution of the code .
Observe the SEGMENTATION FAULT that occurs when data more than the buffer limit is provided as an input to the program .
You might like using strcpy_s() instaed of strcpy() function to avoid buffer overflow in your C code .
The vulnerability exists because the mybuffer could be overflowed if the user input (argv[1]) bigger than 8 bytes. Why 8 bytes? For 32 bit (4 bytes) system, we must fill up a double word (32 bits) memory. Character (char) size is 1 byte, so if we request buffer with 5 bytes, the system will allocate 2 double words (8 bytes). That is why when you input more than 8 bytes; the mybuffer will be over flowed .
Similar standard functions that are technically less vulnerable, such as strncpy(), strncat(), and memcpy(), do exist. But the problem with these functions is that it is the programmer responsibility to assert the size of the buffer, not the compiler.
Lokesh Singh says
Very Good Vanshit :) Keep it up bro.
Vanshit Malhotra says
:)