Please explain why this code is vulnerable to buffer overflow

Asked 2 years ago, Updated 2 years ago, 89 views

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

   if(len >= 100)
   {
        return (-1);
   }

   strncpy(buffer,str,strlen(str));
   return 0;
}

It's a school assignment. They want us to write why this code is weak against buffer overflows But I can't figure it out no matter how much I think about it. Do I have to set it to int instead of short?

security c buffer-overflow

2022-09-22 22:18

1 Answers

In most compilers, the maximum value for unsinged short is 65535. Therefore, a buffer overflow occurs when a string over 65535 length is entered from this code. Also, the buffer size is 100 and the string over 100 in length should not come in.

When saving the return value of strlen(), you must use size_t instead of unsigned short You must memcpy when this length is greater than or equal to the buffer length.

char buffer[100];
size_t len = strlen(str);
if (len >= sizeof(buffer) / sizeof(buffer[0]))  return -1;
memcpy(buffer, str, len + 1);


2022-09-22 22:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.