[hackers] [sbase] [PATCH 02/11] od: Fix buffer overflow if -N flag is larger than BUFSIZ

From: Michael Forney <mforney_AT_mforney.org>
Date: Tue, 6 Dec 2016 02:16:54 -0800

Previously, if max was specified, od will call read with that size,
potentially overflowing buf with data read from the file.
---
 od.c | 18 ++++++++++--------
 1 file changed, 10 insertions(+), 8 deletions(-)
diff --git a/od.c b/od.c
index 9b83501..27a7104 100644
--- a/od.c
+++ b/od.c
_AT_@ -129,23 +129,25 @@ od(FILE *fp, char *fname, int last)
 {
 	static unsigned char *line;
 	static size_t lineoff;
-	size_t i;
-	unsigned char buf[BUFSIZ];
 	static off_t addr;
-	size_t buflen;
+	unsigned char buf[BUFSIZ];
+	size_t i, n, size = sizeof(buf);
 
 	while (skip - addr > 0) {
-		buflen = fread(buf, 1, MIN(skip - addr, BUFSIZ), fp);
-		addr += buflen;
+		n = fread(buf, 1, MIN(skip - addr, sizeof(buf)), fp);
+		addr += n;
 		if (feof(fp) || ferror(fp))
 			return;
 	}
 	if (!line)
 		line = emalloc(linelen);
 
-	while ((buflen = fread(buf, 1, max >= 0 ?
-	                       max - (addr - skip) : BUFSIZ, fp))) {
-		for (i = 0; i < buflen; i++, addr++) {
+	for (;;) {
+		if (max >= 0)
+			size = MIN(max - (addr - skip), size);
+		if (!(n = fread(buf, 1, size, fp)))
+			break;
+		for (i = 0; i < n; i++, addr++) {
 			line[lineoff++] = buf[i];
 			if (lineoff == linelen) {
 				printline(line, lineoff, addr - lineoff + 1);
-- 
2.10.2
Received on Tue Dec 06 2016 - 11:16:54 CET

This archive was generated by hypermail 2.3.0 : Tue Dec 06 2016 - 11:24:25 CET