Why is this code vulnerable to buffer overflow attacks?

前端 未结 5 1058
鱼传尺愫
鱼传尺愫 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:55

    Even though you're using strncpy, the length of the cutoff is still dependent on the passed string pointer. You have no idea how long that string is (the location of the null terminator relative to the pointer, that is). So calling strlen alone opens you up to vulnerability. If you want to be more secure, use strnlen(str, 100).

    Full code corrected would be:

    int func(char *str) {
       char buffer[100];
       unsigned short len = strnlen(str, 100); // sizeof buffer
    
       if (len >= 100) {
         return -1;
       }
    
       strcpy(buffer, str); // this is safe since null terminator is less than 100th index
       return 0;
    }
    

提交回复
热议问题