Why are strlcpy and strlcat considered insecure?

前端 未结 7 1027
一整个雨季
一整个雨季 2020-11-22 05:49

I understand that strlcpy and strlcat were designed as secure replacements for strncpy and strncat. However, some people

7条回答
  •  隐瞒了意图╮
    2020-11-22 06:37

    Ulrich's criticism is based on the idea that a string truncation that is not detected by the program can lead to security issues, through incorrect logic. Therefore, to be secure, you need to check for truncation. To do this for a string concatenation means that you are doing a check along the lines of this:

    if (destlen + sourcelen > dest_maxlen)
    {
        /* Bug out */
    }
    

    Now, strlcat does effectively do this check, if the programmer remembers to check the result - so you can use it safely:

    if (strlcat(dest, source, dest_bufferlen) >= dest_bufferlen)
    {
        /* Bug out */
    }
    

    Ulrich's point is that since you have to have destlen and sourcelen around (or recalculate them, which is what strlcat effectively does), you might as well just use the more efficient memcpy anyway:

    if (destlen + sourcelen > dest_maxlen)
    {
        goto error_out;
    }
    memcpy(dest + destlen, source, sourcelen + 1);
    destlen += sourcelen;
    

    (In the above code, dest_maxlen is the maximum length of the string that can be stored in dest - one less than the size of the dest buffer. dest_bufferlen is the full size of the dest buffer).

提交回复
热议问题