Monday, March 21, 2011

Buffer Overflow attack

Description: Buffer overflow errors are characterized by the overwriting of memory fragments of the process, which should have never been modified intentionally or unintentionally. Overwriting values of the IP (Instruction Pointer), BP (Base Pointer) and other registers causes exceptions, segmentation faults, and other errors to occur. Usually these errors end execution of the application in an unexpected way. Buffer overflow errors occur when we operate on buffers of char type.

How to use buffer overflow errors in a different way?
Generally, exploitation of these errors may lead to:
  • application DoS
  • reordering execution of functions
  • code execution (if we are able to inject the shellcode, described in the separate document)
How are buffer overflow errors are made?
These kinds of errors are very easy to make. For years they were a programmer's nightmare. The problem lies in native C functions, which don't care about doing appropriate buffer length checks. Below is the list of such functions and, if they exist, their safe equivalents:
  • gets() -> fgets() - read characters
  • strcpy() -> strncpy() - copy content of the buffer
  • strcat() -> strncat() - buffer concatenation
  • sprintf() -> snprintf() - fill buffer with data of different types
  • (f)scanf() - read from STDIN
  • getwd() - return working directory
  • realpath() - return absolute (full) path
Use safe equivalent functions, which check the buffers length, whenever it's possible. Namely:
  1. gets() -> fgets()
  2. strcpy() -> strncpy()
  3. strcat() -> strncat()
  4. sprintf() -> snprintf()
Those functions which don't have safe equivalents should be rewritten with safe checks implemented. Time spent on that will benefit in the future. Remember that you have to do it only once.
Use compilers, which are able to identify unsafe functions, logic errors and check if the memory is overwritten when and where it shouldn't be.