libkern: Avoid a one-byte OOB access in strndup()

If the length of the string is maxlen, we would end up copying maxlen+1
bytes, which violates the contract of the function.  The result is the
same since that extra byte is overwritten.

Reported by:	Kevin Day <kevin@your.org>
Reviewed by:	imp, kib
MFC after:	1 week
Differential Revision:	https://reviews.freebsd.org/D54093
This commit is contained in:
Mark Johnston
2025-12-08 14:08:22 +00:00
parent 792221630b
commit 73586fcea6
+3 -3
View File
@@ -40,9 +40,9 @@ strndup(const char *string, size_t maxlen, struct malloc_type *type)
size_t len;
char *copy;
len = strnlen(string, maxlen) + 1;
copy = malloc(len, type, M_WAITOK);
len = strnlen(string, maxlen);
copy = malloc(len + 1, type, M_WAITOK);
memcpy(copy, string, len);
copy[len - 1] = '\0';
copy[len] = '\0';
return (copy);
}