-1

I'm trying to learn more about ways to exploit/prevent buffer overflow in my programs. I know that the following code is vulnerable if the size is constant, but what if the size is random every time? Is there still a way to grab it from the stack and somehow alter the amount of overflow characters dynamically?

void vulnFunc(int size){
    char buffer[size];
    gets(buffer);
    // Arbitrary code
}
Riptyde4
  • 5,134
  • 8
  • 30
  • 57
  • if you allocate dynamically also , you can use `sizeof` operator to get size ,and accordingly alter the contents . – ameyCU Nov 10 '15 at 04:45
  • It is probably difficult to control where/what the overflow overwrites, but it is still possible to screw up the memory after the buffer by providing a bigger input than the random number that was passed to the function. You still [can't use `gets()` safely](http://stackoverflow.com/questions/1694036/why-is-the-gets-function-dangerous-why-should-it-not-be-used). – Jonathan Leffler Nov 10 '15 at 05:19

2 Answers2

0

Consider fgets(buf, sizeof(buf)-1, stdin);

with stdin and a size that matches your buffer. It will be safe. There are other possibilities, such as a loop with getc(stdin): when the data becomes larger than your buffer you can realloc().

Redwood
  • 1
  • 1
0

It depends on the variable that is used to represent the array, if its of type char[] or char *. let me explain why:

  1. for char[], the variable name represents an array and the sizeof operator returns the size of the array in the memory (number of cell * sizeof(type)), so basicly you can get the number of cells using the following call:

    sizeof(array)/sizeof(array[0])

  2. for char*, the variable is a pointer which holds the value of the first cell of the array, sizeof(array) in this case will return the size of pointer in memory that is 8Byte for 64bit architecture, it has nothing with the array so you cant get the information from this kind of variable. Maybe you could store the size of the allocated buffer in memory but I don't know if it suits your needs.

antonpuz
  • 3,256
  • 4
  • 25
  • 48