[PATCH 23/38] trace-cmd lib: prevent buffer overrun in read_string()

"Jerome Marchand" <[email protected]>
Newsgroups org.kernel.vger.linux-trace-devel
Message-ID <[email protected]>
In read_string() we try to write a null character at str(size), which
is out of range:

	if (str) {
		size += i + 1;
		str = realloc(str, size);
		if (!str)
			return NULL;
		memcpy(str + (size - i), buf, i);
		str[size] = 0;
	}

The character that should be zeroed is supposed to be at the size - 1
index, which is the size of str prior the reallocation plus i. We also
know that buf[i] == 0 so we can simply memcpy that too instead of
zeroing it by hand. That simplifies the code a little.

Fixes an OVERRUN error (CWE-119)

Signed-off-by: Jerome Marchand <[email protected]>
---
 lib/trace-cmd/trace-input.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)

diff --git a/lib/trace-cmd/trace-input.c b/lib/trace-cmd/trace-input.c
index 3284dbd4..c485acea 100644
--- a/lib/trace-cmd/trace-input.c
+++ b/lib/trace-cmd/trace-input.c
@@ -447,15 +447,13 @@ static char *read_string(struct tracecmd_input *handle)
 		str = realloc(str, size);
 		if (!str)
 			return NULL;
-		memcpy(str + (size - i), buf, i);
-		str[size] = 0;
+		memcpy(str + (size - i), buf, i + 1);
 	} else {
 		size = i + 1;
 		str = malloc(size);
 		if (!str)
 			return NULL;
-		memcpy(str, buf, i);
-		str[i] = 0;
+		memcpy(str, buf, i + 1);
 	}
 
 	return str;
-- 
2.44.0
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.