[PATCH AUTOSEL 6.5 16/16] selftests/nolibc: prevent out of bounds access in expect_vfprintf

From: Sasha Levin
Date: Fri Sep 08 2023 - 14:02:28 EST


From: Thomas Weißschuh <linux@xxxxxxxxxxxxxx>

[ Upstream commit 9c5e490093e83e165022e0311bd7df5aa06cc860 ]

If read() fails and returns -1 (or returns garbage for some other
reason) buf would be accessed out of bounds.
Only use the return value of read() after it has been validated.

Signed-off-by: Thomas Weißschuh <linux@xxxxxxxxxxxxxx>
Signed-off-by: Willy Tarreau <w@xxxxxx>
Signed-off-by: Sasha Levin <sashal@xxxxxxxxxx>
---
tools/testing/selftests/nolibc/nolibc-test.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/tools/testing/selftests/nolibc/nolibc-test.c b/tools/testing/selftests/nolibc/nolibc-test.c
index 55628a25df0a3..8e7750e2eb97c 100644
--- a/tools/testing/selftests/nolibc/nolibc-test.c
+++ b/tools/testing/selftests/nolibc/nolibc-test.c
@@ -769,7 +769,6 @@ static int expect_vfprintf(int llen, size_t c, const char *expected, const char
lseek(fd, 0, SEEK_SET);

r = read(fd, buf, sizeof(buf) - 1);
- buf[r] = '\0';

fclose(memfile);

@@ -779,6 +778,7 @@ static int expect_vfprintf(int llen, size_t c, const char *expected, const char
return 1;
}

+ buf[r] = '\0';
llen += printf(" \"%s\" = \"%s\"", expected, buf);
ret = strncmp(expected, buf, c);

--
2.40.1