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?
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:
strlen
in size_t
(but this won't circumvent buffer overflow if variable is longer than 4GB)malloc
it successfullystrnlen
together with sizeof(buffer)
rather than strlen
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With