Why is this code vulnerable to buffer overflow attacks?

前端 未结 5 1057
鱼传尺愫
鱼传尺愫 2021-01-29 18:23
int func(char* str)
{
   char buffer[100];
   unsigned short len = strlen(str);

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

   strncpy(buffer,str,strlen(str));         


        
5条回答
  •  遥遥无期
    2021-01-29 18:48

    On most compilers the maximum value of an unsigned short is 65535.

    Any value above that gets wrapped around, so 65536 becomes 0, and 65600 becomes 65.

    This means that long strings of the right length (e.g. 65600) will pass the check, and overflow the buffer.


    Use size_t to store the result of strlen(), not unsigned short, and compare len to an expression that directly encodes the size of buffer. So for example:

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

提交回复
热议问题