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

Suppose I have code with a buffer overflow vulnerability as follows

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 it is received from another function (not user input) and str is always less than 100?

for instance

 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?

+6
source share
1 answer

In short, there is no vulnerability. Every entry disinfected = no vulnerability.

But this does not mean that you should leave it unsecured. Although there is no physical vulnerability, there are many opportunities for vulnerability. Now you do not miss more than 100 characters. But what about a few months? Will you remember that you can enter less than 100 characters? I do not think so.

You can fix this:

  • selecting strlen in size_t (but this will not bypass buffer overflows if the variable is larger than 4 GB)
  • using dynamically allocated buffer and checking malloc for success
  • using strnlen along with sizeof(buffer) , not strlen
  • passing len as a second parameter (possibly annoying)

Using strncpy(a, b, strlen(b)) same as using strcpy(a,b) . This is prevented to some extent by checking in the if , but choosing unsigned short to store it makes it useless anyway. It is also better to use strncpy(a, b, len) so that it is obvious that len should be there in case the check is deleted.

+2
source

Source: https://habr.com/ru/post/986275/


All Articles