Module Name:    src
Committed By:   rillig
Date:           Tue Feb 20 19:49:10 UTC 2024

Modified Files:
        src/tests/lib/libutil: t_snprintb.c

Log Message:
tests/snprintb: fix out-of-bounds memory read (since 2024-02-16)

Before t_snprintb.c 1.20, the buffer size was required to be greater
than zero. Allowing the buffer size to be zero led to buf[-1] being
checked. On amd64, that byte happened to be 0, on i386 it didn't.

Fixes PR lib/57951.


To generate a diff of this commit:
cvs rdiff -u -r1.22 -r1.23 src/tests/lib/libutil/t_snprintb.c

Please note that diffs are not public domain; they are subject to the
copyright notices on the relevant files.

Modified files:

Index: src/tests/lib/libutil/t_snprintb.c
diff -u src/tests/lib/libutil/t_snprintb.c:1.22 src/tests/lib/libutil/t_snprintb.c:1.23
--- src/tests/lib/libutil/t_snprintb.c:1.22	Mon Feb 19 23:30:56 2024
+++ src/tests/lib/libutil/t_snprintb.c	Tue Feb 20 19:49:10 2024
@@ -1,4 +1,4 @@
-/* $NetBSD: t_snprintb.c,v 1.22 2024/02/19 23:30:56 rillig Exp $ */
+/* $NetBSD: t_snprintb.c,v 1.23 2024/02/20 19:49:10 rillig Exp $ */
 
 /*
  * Copyright (c) 2002, 2004, 2008, 2010, 2024 The NetBSD Foundation, Inc.
@@ -32,7 +32,7 @@
 #include <sys/cdefs.h>
 __COPYRIGHT("@(#) Copyright (c) 2008, 2010, 2024\
  The NetBSD Foundation, inc. All rights reserved.");
-__RCSID("$NetBSD: t_snprintb.c,v 1.22 2024/02/19 23:30:56 rillig Exp $");
+__RCSID("$NetBSD: t_snprintb.c,v 1.23 2024/02/20 19:49:10 rillig Exp $");
 
 #include <stdio.h>
 #include <string.h>
@@ -48,9 +48,11 @@ vis_arr(const char *arr, size_t arrsize)
 	static size_t i;
 
 	i = (i + 1) % (sizeof(buf) / sizeof(buf[0]));
-	int rv = strnvisx(buf[i], sizeof(buf[i]), arr, arrsize,
+	buf[i][0] = '"';
+	int rv = strnvisx(buf[i] + 1, sizeof(buf[i]) - 2, arr, arrsize,
 	    VIS_WHITE | VIS_OCTAL);
 	ATF_REQUIRE_MSG(rv >= 0, "strnvisx failed for size %zu", arrsize);
+	strcpy(buf[i] + 1 + rv, "\"");
 	return buf[i];
 }
 
@@ -95,7 +97,8 @@ h_snprintb_loc(const char *file, size_t 
 	ATF_CHECK_MSG(
 	    rv == want_rv
 	    && memcmp(buf, want_buf, want_bufsize) == 0
-	    && buf[rlen < bufsize ? rlen : bufsize - 1] == '\0',
+	    && (bufsize < 1
+		|| buf[rlen < bufsize ? rlen : bufsize - 1] == '\0'),
 	    "failed:\n"
 	    "\ttest case: %s:%zu\n"
 	    "\tformat: %s\n"
@@ -1110,7 +1113,12 @@ h_snprintb_m_loc(const char *file, size_
 
 	size_t total = rv;
 	ATF_CHECK_MSG(
-	    total == want_rv && memcmp(buf, want_buf, want_bufsize) == 0,
+	    total == want_rv
+	    && memcmp(buf, want_buf, want_bufsize) == 0
+	    && (bufsize < 1
+		|| buf[total < bufsize ? total : bufsize - 1] == '\0')
+	    && (bufsize < 2
+		|| buf[total < bufsize ? total - 1 : bufsize - 2] == '\0'),
 	    "failed:\n"
 	    "\ttest case: %s:%zu\n"
 	    "\tformat: %s\n"

Reply via email to