Search code examples
cif-statementbuffer-overflow

Code vulnerability to buffer overflow attack


#include <stdio.h>

int main(void){
  int len;
  char input[40]="";

  printf("input length : \n");
  scanf("%d", &len);
  if(len > 40){
    return 0;
  }
  
  read(0, input, len);
  printf("%s", input);
  return 0;
}

This code is vulnerable to a buffer overflow attack, and I am trying to figure out why. I tried a lot, but every attack code is failed to bypass 'if' statements.

How do I exploit this code?


Solution

  • Apart from the exact number 40 leading to a non-null terminated string, this program also accepts -1 etc as input.

    read in turn has a parameter of unsigned size_t, so if I enter -1 then len will get converted to 0xFFFF... - a very large number.

    The biggest mistake is to declare the buffer size as a signed integer. Buffers cannot have negative size. It should have been declared as size_t and input should have been taken with %zu or better yet as a string through fgets and similar, which is then parsed and sanitized.