Wednesday, July 13, 2011

Integer Overflow (Bugs) in C

Integers is a fundamental data type in a C program, They are used to represent a finite subset of mathematical integers, C Provides us with a suite of functions, and quite a lot of modifiers for manipulating these integers , but if these functions and modifiers are not used properly and carefully they can lead top disastrous results like failing of a Program Logic , Security breach , A break in authentication applications etc.


Integer Overflow



Integer data types in C have a fixed size and limits and which cannot be changed dynamically, This drawback have resulted in a bug commonly known as ‘Integer Overflow bugs’. These bugs are one of the difficult bugs to track down and fix. It happens When an arithmetic operation attempts to create a numeric value that is larger than can be represented within available storage space.

Basically what happens is , As we add 1 to the maximum value than can be represented within a storage space , The integer overflows and resets to the minimum value it can hold .

To make it simple let’s take an example of a odometer (non-digital) an odometer is used to measure distances and it consists of different rings! When odometer reaches its maximum value i.e some 9999’s after that it rolls over to its lowest value i.e 0.

Demonstration



Bug.c
Code:
  #include
   
  int main()
  {
      int i=0;
   
      scanf("%d",&i);
   
      printf("Value %d" , i);
      
      return(0);
  }
Compiling :-
Code:
  gcc Bug.c –o Bug
Input : 1

Ouput :-
Code:
  1
  Value 1
Input : 2147483648
Code:
  2147483648
  Value -2147483648
Boom! See what just happened we have carried a successful Integer overflow attack o our application.

How it happened

I am currently using a 32 bit GCC compiler , with MAXIMUM integer limit set to 2147483647 , So as we add one more to it resets back to its minimum value i.e -2147483648.

This was just an example of how these bugs can be demonstrated , and believe me if you pick up 10 normal C applications and test them for these bugs I guarantee you’ll find at least one of them which is vulnerable.

A Challenge



In the following challenge, You have to force the application to print the success message.

Code:
  #include
   
  void printInt(unsigned int i)
  {
      if(i > 100)
      {
          printf("Success ! You did it!\nValue of Int : %u",i);
          return(0);
      }
  }
   
  int main()
  {
      int i=0;
   
      scanf("%d",&i);
   
      if(i > 100)
      {
          return(-1);
      }
      printInt(i);
      return(0);
  }
It may seem impossible at first, Read the article once more check if you are missing something , Read the Code carefully and you’ll get your solution.


Solution (don’t check it , at least before trying) :-


Give the input as ‘-1’
Code:
  -1
  Success ! You did it!
  Value of Int : 4294967295

Courtesy : Go4Expert (copied and pasted for my personal reference)

No comments:
Write comments