git: 519395f62d29 - stable/13 - h_resolv: Fix a buffer overflow in load().

From: John Baldwin <jhb_at_FreeBSD.org>
Date: Wed, 06 Sep 2023 21:56:31 UTC
The branch stable/13 has been updated by jhb:

URL: https://cgit.FreeBSD.org/src/commit/?id=519395f62d2966faf83990d4162cc5b39af06c75

commit 519395f62d2966faf83990d4162cc5b39af06c75
Author:     John Baldwin <jhb@FreeBSD.org>
AuthorDate: 2022-12-28 17:39:18 +0000
Commit:     John Baldwin <jhb@FreeBSD.org>
CommitDate: 2023-09-06 21:56:09 +0000

    h_resolv: Fix a buffer overflow in load().
    
    fgetln() returns a pointer to an array of characters that is 'len'
    characters long, not 'len + 1'.  While here, overwriting the contents
    of the buffer returned by fgetln isn't really safe, so switch to using
    getline() instead.
    
    Note that these fixes are a subset of those applied to a
    near-identical copy of this function in libc's resolv_test.c in commit
    2afeaad315ac19450389b8f2befdbe7c91c37818.
    
    Reviewed by:    ngie
    Reported by:    CHERI (buffer overflow)
    Sponsored by:   DARPA
    Differential Revision:  https://reviews.freebsd.org/D37886
    
    (cherry picked from commit d131218534977f1b2ed590380e70d59a3b20b333)
---
 contrib/netbsd-tests/lib/libpthread/h_resolv.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/contrib/netbsd-tests/lib/libpthread/h_resolv.c b/contrib/netbsd-tests/lib/libpthread/h_resolv.c
index 9c5fedcc2e7f..d8756de96d23 100644
--- a/contrib/netbsd-tests/lib/libpthread/h_resolv.c
+++ b/contrib/netbsd-tests/lib/libpthread/h_resolv.c
@@ -73,18 +73,18 @@ static void
 load(const char *fname)
 {
 	FILE *fp;
-	size_t len;
+	size_t linecap;
 	char *line;
 
 	if ((fp = fopen(fname, "r")) == NULL)
 		err(1, "Cannot open `%s'", fname);
-	while ((line = fgetln(fp, &len)) != NULL) {
-		char c = line[len];
+	line = NULL;
+	linecap = 0;
+	while (getline(&line, &linecap, fp) >= 0) {
 		char *ptr;
-		line[len] = '\0';
+
 		for (ptr = strtok(line, WS); ptr; ptr = strtok(NULL, WS))
 			sl_add(hosts, strdup(ptr));
-		line[len] = c;
 	}
 
 	(void)fclose(fp);