3 ms·
In this case I'm skeptical. SIZE_MAX may trigger integer overflow, but smaller values are still potential buffer overflows. It would have to be a rather contriv
by dietrichepp 11y ago
In this case I'm skeptical. SIZE_MAX may trigger integer overflow, but smaller values are still potential buffer overflows. It would have to be a rather contrived or pathological case in order for the integer overflow to be exploitable.
That, and programs shouldn't be using strncpy or strncat anyway, at least 99% of the time.
- spoiler 11y agoI rarely work with cstrings directly, and even then I don't tend to use them (`strcat`/`strncat`) myself; I tend to use `memcpy`/`memmove` instead. However, I'm curious why do you say they shouldn't be used? Is there any other reason, other than the performance overhead?
- dietrichepp 11y agoBasically, strncpy and strncat shouldn't be used because they don't do what you want. You want a NUL terminated string without buffer overflow, but these functions instead work with fixed size strings. They're simply designed to perform a different task. In particular, they put 0…N NUL bytes at the end, but you usually want exactly one NUL byte, no more, no less.
- __david__ 11y ago> In particular, they put 0…N NUL bytes at the end, but you usually want exactly one NUL byte, no more, no less. strncpy() does that but strncat() does not. strncat(s1,s2,size) is usually wrong for a different reason: the size argument specifies how many bytes to copy from s2 to the end of s1 (not including the trailing NULL). This means to not buffer overflow your s1 you need to call it like this strncat(s1, s2, sizeof(s1) - strlen(s1) - 1); ...Which of course everyone forgets. strlcat() is a nice replacement because it does that calculation for you, so you can just do: strlcat(s1, s2, sizeof(s1)); and you won't buffer overflow your s1.
- jandrese 11y agoOf course strl... functions are still braindamaged because they still return the length of the original string, regardless of what parameter you specified in the third argument. So if the initial string has lost its null terminator the strl... functions will still core dump even if you specified an otherwise safe size. Also, if you're copying the first few bytes out of an enormous buffer (especially a file mmap) it can take a long time for the function to chew through the rest of the buffer calculating that return value that you don't even care about. That's why it's usually better to just use memcpy or memmove instead.
- dietrichepp 11y agoIn particular, most people end up using memcpy/memmove, snprintf, or a library like strbuf. The BSD devs are somewhat unusual for favoring strlcpy.