Format String Vulnerability and Prevention with Example in C



Format String − It is an ASCII string that is used for formatting strings. It is an ASCII string consisting of texts and formatting parameters.

For formatting, the program’s output, there are various format strings in C.

FORMAT STRING VULNERABILITIES

These are bugs that arise due to errors in programming that might be made easily by the programmer. If any such error-prone code blog is passed to output functions like printf, sprintf, etc. Then the write operation is performed to an arbitrary memory address.

Example

#include<stdio.h>
#include<string.h>

int main(){

   char buffer[100];
   strncpy(buffer, "Hii ", 5);
   printf(buffer);

   return 0;
}

PREVENTIONS

There are some measures that can be taken to prevent format string Vulnerabilities

  • Try to use format string as part of the program instead to input data. These can be easily solved using “%s” string format.

  • Use constant for creating format String and extract all variable strings as arguments of the function call instead of using them in constant string.

  • For cases where constant and variable string initialization norms cannot be followed format guards are used.


Advertisements