6.6. Dangers of Buffer overflowsΒΆ

Consider the following code:

int main( int argc, char *argv[] )
{
   char buff[50];

   if( argc > 1 ) {
      sprintf( buff, "First argument is %s\n", argv[1] );
   }
   ...
}
  • This code is dangerous because if a user enters a first argument which is very large, the sprintf() function could write beyond the end of the memory allocated for buff. This is called a buffer overflow.

  • Possible results of a buffer overflow are: core dump, system crash, or a security vulnerability, which is the worst of all.

  • Security problems can occur when a SUID root program executes code with a buffer overflow and later the program makes a system call such as execl or execv to execute another program. This is because the stack grows down.

    char program[50] = "/usr/bin/legit;"
    char overflowed[50];
    ...                            Stack:  |                |
                                           |  program[50]   |
    {                                      | overflowed[50] |
    codewith_overflow
    }
    ...
    execv( program, NULL );
    ...
    

    If our program is a SUID root program and the buffer overflow is carefully created such that program[50] ends up containing /bin/sh, then the hacker has achieved a root level compromise of the system.

  • Never write data supplied by a user to a string without first checking the size of the data.

  • Most common source of buffer overflows are: sprintf, strcat, strcpy, scanf, gets (never use gets).