From 9df98a6e31bf3a2332759aa5770a414698d5e375 Mon Sep 17 00:00:00 2001 From: Matt Merhar Date: Fri, 13 Sep 2024 18:30:25 -0400 Subject: [PATCH] Avoid printing unterminated string in readline() When running with -v, readline() in io.c uses strncpy() to copy a string (*without* the terminating NULL) into an uninitialized buffer created by malloc(). When message() then prints this, it can lead to garbage data being emitted since it's potentially reading past the intended end of the string. In practice, this appears to only be an additional byte or 2 before a NULL is encountered. The issue was hit when readline() encountered "\r\n\r\n", not longer strings, but I imagine it's dependent on things like compiler / libc / the weather as to whether the end of the buffer returned by malloc() will be zeroed or not; I've seen similar issues pop up with "working" code running on newer distros. --- io.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/io.c b/io.c index e8df31a..56d516e 100644 --- a/io.c +++ b/io.c @@ -57,7 +57,7 @@ int readline(PTSTREAM *pts) { if( args_info.verbose_flag ) { /* Copy line of data into dstr without trailing newline */ - char *dstr = malloc(strlen(buf) + 1); + char *dstr = calloc(1, strlen(buf) + 1); strncpy( dstr, buf, strlen(buf)); if (strcmp(dstr, "")) message( " <- %s\n", dstr );