diff options
author | Xiang Wang <merle@hardenedlinux.org> | 2021-01-20 17:31:19 +0800 |
---|---|---|
committer | Felix Singer <felixsinger@posteo.net> | 2022-09-29 17:05:38 +0000 |
commit | 5feb8cdb6ff497e45cda73839dacafc240bf83bb (patch) | |
tree | fd3c99ccf093d56e957068e763d9c83d774ca2c7 | |
parent | b822ce85aaed8c6dfa8f5e1e2354db5c9db50509 (diff) | |
download | flashrom-5feb8cdb6ff497e45cda73839dacafc240bf83bb.tar.gz flashrom-5feb8cdb6ff497e45cda73839dacafc240bf83bb.tar.bz2 flashrom-5feb8cdb6ff497e45cda73839dacafc240bf83bb.zip |
helpers.c: Fix undefined behavior in strndup()
Using strlen() or strdup() inside strndup() is problematic: if the
input string is not null-terminated, these functions can read past the
end of the buffer, which triggers undefined behavior. Rewrite the
function to never read past the provided `maxlen` bound.
Change-Id: Id34127024085879228626fbad59af03268ec5255
Signed-off-by: Xiang Wang <merle@hardenedliux.org>
Reviewed-on: https://review.coreboot.org/c/flashrom/+/49741
Reviewed-by: Angel Pons <th3fanbus@gmail.com>
Reviewed-by: Edward O'Callaghan <quasisec@chromium.org>
Tested-by: build bot (Jenkins) <no-reply@coreboot.org>
Reviewed-on: https://review.coreboot.org/c/flashrom/+/67870
Reviewed-by: Felix Singer <felixsinger@posteo.net>
-rw-r--r-- | helpers.c | 17 |
1 files changed, 9 insertions, 8 deletions
@@ -106,15 +106,16 @@ char* strtok_r(char *str, const char *delim, char **nextp) /* strndup is a POSIX function not present in MinGW */ char *strndup(const char *src, size_t maxlen) { - if (strlen(src) > maxlen) { - char *retbuf; - if ((retbuf = malloc(1 + maxlen)) != NULL) { - memcpy(retbuf, src, maxlen); - retbuf[maxlen] = '\0'; - } - return retbuf; + char *retbuf; + size_t len; + for (len = 0; len < maxlen; len++) + if (src[len] == '\0') + break; + if ((retbuf = malloc(1 + len)) != NULL) { + memcpy(retbuf, src, len); + retbuf[len] = '\0'; } - return strdup(src); + return retbuf; } #endif |