The memcpy() function has been recommended to be banned and will most likely enter Microsoft's SDL Banned list later this year. memcpy() joins the ranks of other popular functions like strcpy, strncpy, strcat, strncat which were banned due to their security vulnerability through buffer overruns.
Part of the root cause, is usage of "unsafe" functions, including C++ staples such as memcpy, strcpy, strncpy, and more. These functions are considered unsafe since they directly handle unconstrained buffers, and without intensive, careful bounds checkings will typically directly overflow any target buffers.
memcpy() doesn't support overlapping memory. This allows for optimizations that won't work if the buffers do overlap.
memcpy_s copies count bytes from src to dest ; wmemcpy_s copies count wide characters (two bytes). If the source and destination overlap, the behavior of memcpy_s is undefined. Use memmove_s to handle overlapping regions. These functions validate their parameters.
As some of you may know, Microsoft banned memcpy()
from their Security Development Lifecycle, replacing it with memcpy_s()
.
void *memcpy(void *dest, const void *src, size_t n);
/* simplified signature */
errno_t memcpy_s(void *dst, size_t dstsize, const void *src, size_t n);
So if your code used to be:
if (in_len > dst_len) {
/* error */
}
memcpy(dst, src, in_len);
it becomes:
if (memcpy_s(dst, dst_len, src, src_len)) {
/* error */
}
Or, with truncation,
memcpy(dst, src, min(in_len, dst_len));
vs
(void)memcpy_s(dst, dst_len, src, src_len);
The question: how does an extra length parameter make code any more secure? To use memcpy()
, I should already have all four parameters known and pass appropriate length as a third argument. What's stopping me from making the same mistake of miscalculating destination buffer size and passing the wrong valus of dst_size
? I can't see why it's any different from memcpy()
and why it's being deprecated. Is there any common use case that I can't see? What am I missing here?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With