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
2afeaad315.

Reviewed by:	ngie
Reported by:	CHERI (buffer overflow)
Sponsored by:	DARPA
Differential Revision:	https://reviews.freebsd.org/D37886
This commit is contained in:
John Baldwin 2022-12-28 09:39:18 -08:00
parent 058ac3e806
commit d131218534

View file

@ -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);