buffer overflow

Rob Wehrli plug-devel@lists.PLUG.phoenix.az.us
Wed Aug 22 12:01:08 2001


Lucas Vogel wrote:
> 
> It seems as though every time I look at my favorite distribution's website
> (SuSE, in case you were curious) for software updates, there are a number of
> different security updates due to some kind of buffer overflow situation in
> one piece of software or another. Would someone care to go over buffer
> overflows, how they are exploited and good preventative programming
> practices?

Buffer overflows are situations where a program tries to write past the
end of an array's memory boundries.

For Example:

#include <stdio.h>

int main( int argc, char * argv[] )
{
  char a = 'a';
  char cName[5];
  int  i = 0;

  /* BAD CODE ...writes past end of array */

  do
  {
    cName[i] = a++;
    printf( "%c", cName[i++] );
  }   
  while( i < 7 );

  return 0;
}


This code compiles succesfully and runs.  However, the memory beyond the
end of the array is modified by this program and it is possible that
that memory is being used by another thread of the (a real) application
or elsewhere by the same thread.  If the code above corrupts the memory,
it is possible that a function call or other user of the memory can
raise a signal and cause the program to crash.  Hackers gain access to
the shell that started the application in this manner.  This is another
reason why "public" applications such as those ran from CGI are
typically ran as user "nobody" or some other user without greater system
privs.  Certainly, publicly accessible applications running as user root
would be a bad thing, especially if they wrote past the ends of arrays
:)  If you'd like to see if you can crash your application, simply make
the "7" above a really large number such as (replace with) while ( i <
0xFFFFFFFF ) ...and wait for it to hose!  (Also, try putting a:

char *szPhrase = "This is the end of the world as we know it...!";
(just after the cName declaration, and then put a printf call inside the
do/while loop after the printf/char, but reduce the loop count to a sane
number so you don't spend forever in printf)

Code written to protect these situations are an important programming
practice for security and just for good reasons such as not writing to
memory you don't "own."

Putting restrictions on the above program such as:

#include <stdio.h>

int main( int argc, char * argv[] )
{
  char a = 'a';
  char cName[5];
  int  i = 0;

  /* Now written to protect against array overflow */

  do
  {
    cName[i] = a++;
    printf( "%c", cName[i++] );
  }   
  while( i < ( sizeof( cName ) / sizeof( char ) ) );

  printf( "\n" );

  return 0;
}


> 
> Thanks
> 

No problemo...

Take Care.

Rob!