开发者

how to rewrite the following function so that it is no longer vulnerable to stack buffer overflow?

I need to rewrite the function so that it is no longer vulnerable to stack buffer overflow.

void hello (char *tag)
{
   char inp [16];

   开发者_如何学Pythonprintf("enter value for %s:", tag);
   gets(inp);
   printf("hello your %s is %s\n", tag, inp);
}

Also, how do I rewrite the following other code to avoid buffer overflow:

int main (int argc, char *argv[ ]) {
    int valid=FALSE;
    char str1[8];
    char str2[8];

    next_tag(str1);
    gets(str2);
    if (strncmp(str1,str2,8)==0)
        valid=TRUE;
    printf("buffer: str1(%s),str2(%s),valid(%d) \n", str1, str2, valid);
}


Simply use fgets() instead of gets(). It allows you to limit the number of characters stored in the buffer.


I'm not going to post code as this looks like homework.

Buffer Overflow happens when you try to access a location of the buffer beyond its size.

for example, in your hello(...) function this would be trying to access an element of the array inp larger than 15.

You ask for the user to provide an index into the array and then gives back the value of that location of the array.

Inorder to prevent an overflow you invariably need to make sure that the range of the index user specified is below the size of that array.

I can't comment on the second code fragment because it's incomplete.


void hello (char *tag)
{
   char inp [16];

   printf("enter value for %s:", tag);
   fgets(inp, 16, stdin);
   printf("hello your %s is %s\n", tag, inp);
}

And similar for the other one.


Use fgets instead of gets. Keep the size at the length of the buffer and you won't overflow it.


You can create a test case after receiving the strings to check its length. If you accept the input then proceed otherwise terminate or panic!
Do Tests before this line:

if (strncmp(str1,str2,8)==0)
    valid=TRUE;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜