Prevent underflow buffer read in trim_whitespace() in libutil/passwd.c

If a string is empty or contains only white characters, the algorithm of
removal of white characters at the end of the passed string will read
buffer at index -1 and keep iterating backward.

Detected with MKSANITIZER/ASan when executing passwd(1).
This commit is contained in:
kamil 2018-06-24 01:53:14 +00:00
parent ed22e03d7d
commit b2b644497e

View File

@ -1,4 +1,4 @@
/* $NetBSD: passwd.c,v 1.52 2012/06/25 22:32:47 abs Exp $ */ /* $NetBSD: passwd.c,v 1.53 2018/06/24 01:53:14 kamil Exp $ */
/* /*
* Copyright (c) 1987, 1993, 1994, 1995 * Copyright (c) 1987, 1993, 1994, 1995
@ -31,7 +31,7 @@
#include <sys/cdefs.h> #include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint) #if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: passwd.c,v 1.52 2012/06/25 22:32:47 abs Exp $"); __RCSID("$NetBSD: passwd.c,v 1.53 2018/06/24 01:53:14 kamil Exp $");
#endif /* LIBC_SCCS and not lint */ #endif /* LIBC_SCCS and not lint */
#include <sys/types.h> #include <sys/types.h>
@ -503,13 +503,21 @@ trim_whitespace(char *line)
_DIAGASSERT(line != NULL); _DIAGASSERT(line != NULL);
/* Handle empty string */
if (*line == '\0')
return;
/* Remove leading spaces */ /* Remove leading spaces */
p = line; p = line;
while (isspace((unsigned char) *p)) while (isspace((unsigned char) *p))
p++; p++;
memmove(line, p, strlen(p) + 1); memmove(line, p, strlen(p) + 1);
/* Remove trailing spaces */ /* Handle empty string after removal of whitespace characters */
if (*line == '\0')
return;
/* Remove trailing spaces, line must not be empty string here */
p = line + strlen(line) - 1; p = line + strlen(line) - 1;
while (isspace((unsigned char) *p)) while (isspace((unsigned char) *p))
p--; p--;