Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to exploit a vulnerable function if its input is safe?

Assume that I have a code having buffer overflow vulnerability as following

int func(const char *str){
    char buffer[100];
    unsigned short len = strlen(str);

    if(len >= 100){
        return -1;
    }
    strncpy(buffer,str,strlen(str));
    return 0; 
}

(taken from this question)

Is there a way to exploit this vulnerability if its getting input from another function (not user input) and the length of str is always less than 100?

For example

int main() {
    int user_input;
    if (cin >> user_input) {
        if(user_input == 1)
          func("aaaa");
        else 
          func("bbbb");
    }
}

Assume there is no other vulnerability in the code.

Just a hypothetical question, any ideas?

like image 363
smttsp Avatar asked Apr 30 '15 07:04

smttsp


1 Answers

In short, there is no vulnerability. Every input sanitized = no vulnerability.

But that doesn't mean you should leave it unfixed. While there is no physical vulnerability, there is a lot of potential for a vulnerability. Now you don't pass anything longer than 100 characters. But what about a few months from now on? Will you remember that you can only pass input shorter than 100 characters? I don't think so.

You can fix it by:

  1. choosing to hold strlen in size_t (but this won't circumvent buffer overflow if variable is longer than 4GB)
  2. using a dynamically allocated buffer and checking if you managed to malloc it successfully
  3. using strnlen together with sizeof(buffer) rather than strlen
  4. passing len as a second parameter (probably annoying)

Using strncpy(a, b, strlen(b)) is the same as using strcpy(a,b). This is prevented to some extent with the check in the if instruction, but the choice unsigned short for its storage makes it worthless anyway. It's also better to use strncpy(a, b, len) to make it obvious that len does need to be there, in case the check gets refactored away.

like image 69
rr- Avatar answered Oct 16 '22 01:10

rr-