e0b30b
From 9d2ec74b76d220f5343e548fcb7058d723293a22 Mon Sep 17 00:00:00 2001
e0b30b
From: Qualys Security Advisory <qsa@qualys.com>
e0b30b
Date: Thu, 1 Jan 1970 00:00:00 +0000
e0b30b
Subject: [PATCH 1/3] proc/alloc.*: Use size_t, not unsigned int.
e0b30b
e0b30b
Otherwise this can truncate sizes on 64-bit platforms, and is one of the
e0b30b
reasons the integer overflows in file2strvec() are exploitable at all.
e0b30b
Also: catch potential integer overflow in xstrdup() (should never
e0b30b
happen, but better safe than sorry), and use memcpy() instead of
e0b30b
strcpy() (faster).
e0b30b
e0b30b
Warnings:
e0b30b
e0b30b
- in glibc, realloc(ptr, 0) is equivalent to free(ptr), but not here,
e0b30b
  because of the ++size;
e0b30b
e0b30b
- here, xstrdup() can return NULL (if str is NULL), which goes against
e0b30b
  the idea of the xalloc wrappers.
e0b30b
e0b30b
We were tempted to call exit() or xerrx() in those cases, but decided
e0b30b
against it, because it might break things in unexpected places; TODO?
e0b30b
---
e0b30b
 proc/alloc.c | 20 ++++++++++++--------
e0b30b
 proc/alloc.h |  4 ++--
e0b30b
 2 files changed, 14 insertions(+), 10 deletions(-)
e0b30b
e0b30b
diff --git a/proc/alloc.c b/proc/alloc.c
e0b30b
index 94af47f..1768d73 100644
e0b30b
--- a/proc/alloc.c
e0b30b
+++ b/proc/alloc.c
e0b30b
@@ -37,14 +37,14 @@ static void xdefault_error(const char *restrict fmts, ...) {
e0b30b
 message_fn xalloc_err_handler = xdefault_error;
e0b30b
 
e0b30b
 
e0b30b
-void *xcalloc(unsigned int size) {
e0b30b
+void *xcalloc(size_t size) {
e0b30b
     void * p;
e0b30b
 
e0b30b
     if (size == 0)
e0b30b
         ++size;
e0b30b
     p = calloc(1, size);
e0b30b
     if (!p) {
e0b30b
-        xalloc_err_handler("%s failed to allocate %u bytes of memory", __func__, size);
e0b30b
+        xalloc_err_handler("%s failed to allocate %zu bytes of memory", __func__, size);
e0b30b
         exit(EXIT_FAILURE);
e0b30b
     }
e0b30b
     return p;
e0b30b
@@ -57,20 +57,20 @@ void *xmalloc(size_t size) {
e0b30b
         ++size;
e0b30b
     p = malloc(size);
e0b30b
     if (!p) {
e0b30b
-	xalloc_err_handler("%s failed to allocate %zu bytes of memory", __func__, size);
e0b30b
+        xalloc_err_handler("%s failed to allocate %zu bytes of memory", __func__, size);
e0b30b
         exit(EXIT_FAILURE);
e0b30b
     }
e0b30b
     return(p);
e0b30b
 }
e0b30b
 
e0b30b
-void *xrealloc(void *oldp, unsigned int size) {
e0b30b
+void *xrealloc(void *oldp, size_t size) {
e0b30b
     void *p;
e0b30b
 
e0b30b
     if (size == 0)
e0b30b
         ++size;
e0b30b
     p = realloc(oldp, size);
e0b30b
     if (!p) {
e0b30b
-        xalloc_err_handler("%s failed to allocate %u bytes of memory", __func__, size);
e0b30b
+        xalloc_err_handler("%s failed to allocate %zu bytes of memory", __func__, size);
e0b30b
         exit(EXIT_FAILURE);
e0b30b
     }
e0b30b
     return(p);
e0b30b
@@ -80,13 +80,17 @@ char *xstrdup(const char *str) {
e0b30b
     char *p = NULL;
e0b30b
 
e0b30b
     if (str) {
e0b30b
-        unsigned int size = strlen(str) + 1;
e0b30b
+        size_t size = strlen(str) + 1;
e0b30b
+        if (size < 1) {
e0b30b
+            xalloc_err_handler("%s refused to allocate %zu bytes of memory", __func__, size);
e0b30b
+            exit(EXIT_FAILURE);
e0b30b
+        }
e0b30b
         p = malloc(size);
e0b30b
         if (!p) {
e0b30b
-            xalloc_err_handler("%s failed to allocate %u bytes of memory", __func__, size);
e0b30b
+            xalloc_err_handler("%s failed to allocate %zu bytes of memory", __func__, size);
e0b30b
             exit(EXIT_FAILURE);
e0b30b
         }
e0b30b
-        strcpy(p, str);
e0b30b
+        memcpy(p, str, size);
e0b30b
     }
e0b30b
     return(p);
e0b30b
 }
e0b30b
diff --git a/proc/alloc.h b/proc/alloc.h
e0b30b
index 19c91d7..6787a72 100644
e0b30b
--- a/proc/alloc.h
e0b30b
+++ b/proc/alloc.h
e0b30b
@@ -10,9 +10,9 @@ typedef void (*message_fn)(const char *__restrict, ...) __attribute__((format(pr
e0b30b
  /* change xalloc_err_handler to override the default fprintf(stderr... */
e0b30b
 extern message_fn xalloc_err_handler;
e0b30b
 
e0b30b
-extern void *xcalloc(unsigned int size) MALLOC;
e0b30b
+extern void *xcalloc(size_t size) MALLOC;
e0b30b
 extern void *xmalloc(size_t size) MALLOC;
e0b30b
-extern void *xrealloc(void *oldp, unsigned int size) MALLOC;
e0b30b
+extern void *xrealloc(void *oldp, size_t size) MALLOC;
e0b30b
 extern char *xstrdup(const char *str) MALLOC;
e0b30b
 
e0b30b
 EXTERN_C_END
e0b30b
-- 
e0b30b
2.14.3
e0b30b
e0b30b
e0b30b
From de660b14b80188d9b323c4999d1b91a9456ed687 Mon Sep 17 00:00:00 2001
e0b30b
From: Qualys Security Advisory <qsa@qualys.com>
e0b30b
Date: Thu, 1 Jan 1970 00:00:00 +0000
e0b30b
Subject: [PATCH 2/3] proc/readproc.c: Harden file2str().
e0b30b
e0b30b
1/ Replace sprintf() with snprintf() (and check for truncation).
e0b30b
e0b30b
2/ Prevent an integer overflow of ub->siz. The "tot_read--" is needed to
e0b30b
avoid an off-by-one overflow in "ub->buf[tot_read] = '\0'". It is safe
e0b30b
to decrement tot_read here, because we know that tot_read is equal to
e0b30b
ub->siz (and ub->siz is very large).
e0b30b
e0b30b
We believe that truncation is a better option than failure (implementing
e0b30b
failure instead should be as easy as replacing the "tot_read--" with
e0b30b
"tot_read = 0").
e0b30b
---
e0b30b
 proc/readproc.c | 10 ++++++++--
e0b30b
 1 file changed, 8 insertions(+), 2 deletions(-)
e0b30b
e0b30b
diff --git a/proc/readproc.c b/proc/readproc.c
e0b30b
index 9e3afc9..39235c7 100644
e0b30b
--- a/proc/readproc.c
e0b30b
+++ b/proc/readproc.c
e0b30b
@@ -35,6 +35,7 @@
e0b30b
 #include <signal.h>
e0b30b
 #include <fcntl.h>
e0b30b
 #include <dirent.h>
e0b30b
+#include <limits.h>
e0b30b
 #include <sys/types.h>
e0b30b
 #include <sys/stat.h>
e0b30b
 #ifdef WITH_SYSTEMD
e0b30b
@@ -635,7 +636,7 @@ static void statm2proc(const char* s, proc_t *restrict P) {
e0b30b
 static int file2str(const char *directory, const char *what, struct utlbuf_s *ub) {
e0b30b
  #define buffGRW 1024
e0b30b
     char path[PROCPATHLEN];
e0b30b
-    int fd, num, tot_read = 0;
e0b30b
+    int fd, num, tot_read = 0, len;
e0b30b
 
e0b30b
     /* on first use we preallocate a buffer of minimum size to emulate
e0b30b
        former 'local static' behavior -- even if this read fails, that
e0b30b
@@ -643,11 +644,16 @@ static int file2str(const char *directory, const char *what, struct utlbuf_s *ub
e0b30b
        ( besides, with this xcalloc we will never need to use memcpy ) */
e0b30b
     if (ub->buf) ub->buf[0] = '\0';
e0b30b
     else ub->buf = xcalloc((ub->siz = buffGRW));
e0b30b
-    sprintf(path, "%s/%s", directory, what);
e0b30b
+    len = snprintf(path, sizeof path, "%s/%s", directory, what);
e0b30b
+    if (len <= 0 || (size_t)len >= sizeof path) return -1;
e0b30b
     if (-1 == (fd = open(path, O_RDONLY, 0))) return -1;
e0b30b
     while (0 < (num = read(fd, ub->buf + tot_read, ub->siz - tot_read))) {
e0b30b
         tot_read += num;
e0b30b
         if (tot_read < ub->siz) break;
e0b30b
+        if (ub->siz >= INT_MAX - buffGRW) {
e0b30b
+            tot_read--;
e0b30b
+            break;
e0b30b
+        }
e0b30b
         ub->buf = xrealloc(ub->buf, (ub->siz += buffGRW));
e0b30b
     };
e0b30b
     ub->buf[tot_read] = '\0';
e0b30b
-- 
e0b30b
2.14.3
e0b30b
e0b30b
e0b30b
From 44a4b658f45bc3fbd7170662a52038a7b35c83de Mon Sep 17 00:00:00 2001
e0b30b
From: Qualys Security Advisory <qsa@qualys.com>
e0b30b
Date: Thu, 1 Jan 1970 00:00:00 +0000
e0b30b
Subject: [PATCH 3/3] proc/readproc.c: Fix bugs and overflows in file2strvec().
e0b30b
e0b30b
Note: this is by far the most important and complex patch of the whole
e0b30b
series, please review it carefully; thank you very much!
e0b30b
e0b30b
For this patch, we decided to keep the original function's design and
e0b30b
skeleton, to avoid regressions and behavior changes, while fixing the
e0b30b
various bugs and overflows. And like the "Harden file2str()" patch, this
e0b30b
patch does not fail when about to overflow, but truncates instead: there
e0b30b
is information available about this process, so return it to the caller;
e0b30b
also, we used INT_MAX as a limit, but a lower limit could be used.
e0b30b
e0b30b
The easy changes:
e0b30b
e0b30b
- Replace sprintf() with snprintf() (and check for truncation).
e0b30b
e0b30b
- Replace "if (n == 0 && rbuf == 0)" with "if (n <= 0 && tot <= 0)" and
e0b30b
  do break instead of return: it simplifies the code (only one place to
e0b30b
  handle errors), and also guarantees that in the while loop either n or
e0b30b
  tot is > 0 (or both), even if n is reset to 0 when about to overflow.
e0b30b
e0b30b
- Remove the "if (n < 0)" block in the while loop: it is (and was) dead
e0b30b
  code, since we enter the while loop only if n >= 0.
e0b30b
e0b30b
- Rewrite the missing-null-terminator detection: in the original
e0b30b
  function, if the size of the file is a multiple of 2047, a null-
e0b30b
  terminator is appended even if the file is already null-terminated.
e0b30b
e0b30b
- Replace "if (n <= 0 && !end_of_file)" with "if (n < 0 || tot <= 0)":
e0b30b
  originally, it was equivalent to "if (n < 0)", but we added "tot <= 0"
e0b30b
  to handle the first break of the while loop, and to guarantee that in
e0b30b
  the rest of the function tot is > 0.
e0b30b
e0b30b
- Double-force ("belt and suspenders") the null-termination of rbuf:
e0b30b
  this is (and was) essential to the correctness of the function.
e0b30b
e0b30b
- Replace the final "while" loop with a "for" loop that behaves just
e0b30b
  like the preceding "for" loop: in the original function, this would
e0b30b
  lead to unexpected results (for example, if rbuf is |\0|A|\0|, this
e0b30b
  would return the array {"",NULL} but should return {"","A",NULL}; and
e0b30b
  if rbuf is |A|\0|B| (should never happen because rbuf should be null-
e0b30b
  terminated), this would make room for two pointers in ret, but would
e0b30b
  write three pointers to ret).
e0b30b
e0b30b
The hard changes:
e0b30b
e0b30b
- Prevent the integer overflow of tot in the while loop, but unlike
e0b30b
  file2str(), file2strvec() cannot let tot grow until it almost reaches
e0b30b
  INT_MAX, because it needs more space for the pointers: this is why we
e0b30b
  introduced ARG_LEN, which also guarantees that we can add "align" and
e0b30b
  a few sizeof(char*)s to tot without overflowing.
e0b30b
e0b30b
- Prevent the integer overflow of "tot + c + align": when INT_MAX is
e0b30b
  (almost) reached, we write the maximal safe amount of pointers to ret
e0b30b
  (ARG_LEN guarantees that there is always space for *ret = rbuf and the
e0b30b
  NULL terminator).
e0b30b
---
e0b30b
 proc/readproc.c | 53 ++++++++++++++++++++++++++++++++---------------------
e0b30b
 1 file changed, 32 insertions(+), 21 deletions(-)
e0b30b
e0b30b
diff --git a/proc/readproc.c b/proc/readproc.c
e0b30b
index 39235c7..94ca4e9 100644
e0b30b
--- a/proc/readproc.c
e0b30b
+++ b/proc/readproc.c
e0b30b
@@ -665,11 +665,12 @@ static int file2str(const char *directory, const char *what, struct utlbuf_s *ub
e0b30b
 
e0b30b
 static char** file2strvec(const char* directory, const char* what) {
e0b30b
     char buf[2048];	/* read buf bytes at a time */
e0b30b
-    char *p, *rbuf = 0, *endbuf, **q, **ret;
e0b30b
+    char *p, *rbuf = 0, *endbuf, **q, **ret, *strp;
e0b30b
     int fd, tot = 0, n, c, end_of_file = 0;
e0b30b
     int align;
e0b30b
 
e0b30b
-    sprintf(buf, "%s/%s", directory, what);
e0b30b
+    const int len = snprintf(buf, sizeof buf, "%s/%s", directory, what);
e0b30b
+    if(len <= 0 || (size_t)len >= sizeof buf) return NULL;
e0b30b
     fd = open(buf, O_RDONLY, 0);
e0b30b
     if(fd==-1) return NULL;
e0b30b
 
e0b30b
@@ -677,18 +678,23 @@ static char** file2strvec(const char* directory, const char* what) {
e0b30b
     while ((n = read(fd, buf, sizeof buf - 1)) >= 0) {
e0b30b
 	if (n < (int)(sizeof buf - 1))
e0b30b
 	    end_of_file = 1;
e0b30b
-	if (n == 0 && rbuf == 0) {
e0b30b
-	    close(fd);
e0b30b
-	    return NULL;	/* process died between our open and read */
e0b30b
+	if (n <= 0 && tot <= 0) { /* nothing read now, nothing read before */
e0b30b
+	    break;		/* process died between our open and read */
e0b30b
 	}
e0b30b
-	if (n < 0) {
e0b30b
-	    if (rbuf)
e0b30b
-		free(rbuf);
e0b30b
-	    close(fd);
e0b30b
-	    return NULL;	/* read error */
e0b30b
+	/* ARG_LEN is our guesstimated median length of a command-line argument
e0b30b
+	   or environment variable (the minimum is 1, the maximum is 131072) */
e0b30b
+	#define ARG_LEN 64
e0b30b
+	if (tot >= INT_MAX / (ARG_LEN + (int)sizeof(char*)) * ARG_LEN - n) {
e0b30b
+	    end_of_file = 1; /* integer overflow: null-terminate and break */
e0b30b
+	    n = 0; /* but tot > 0 */
e0b30b
 	}
e0b30b
-	if (end_of_file && (n == 0 || buf[n-1]))/* last read char not null */
e0b30b
+	#undef ARG_LEN
e0b30b
+	if (end_of_file &&
e0b30b
+	    ((n > 0 && buf[n-1] != '\0') ||	/* last read char not null */
e0b30b
+	     (n <= 0 && rbuf[tot-1] != '\0')))	/* last read char not null */
e0b30b
 	    buf[n++] = '\0';			/* so append null-terminator */
e0b30b
+
e0b30b
+	if (n <= 0) break; /* unneeded (end_of_file = 1) but avoid realloc */
e0b30b
 	rbuf = xrealloc(rbuf, tot + n);		/* allocate more memory */
e0b30b
 	memcpy(rbuf + tot, buf, n);		/* copy buffer into it */
e0b30b
 	tot += n;				/* increment total byte ctr */
e0b30b
@@ -696,29 +702,34 @@ static char** file2strvec(const char* directory, const char* what) {
e0b30b
 	    break;
e0b30b
     }
e0b30b
     close(fd);
e0b30b
-    if (n <= 0 && !end_of_file) {
e0b30b
+    if (n < 0 || tot <= 0) {	/* error, or nothing read */
e0b30b
 	if (rbuf) free(rbuf);
e0b30b
 	return NULL;		/* read error */
e0b30b
     }
e0b30b
+    rbuf[tot-1] = '\0'; /* belt and suspenders (the while loop did it, too) */
e0b30b
     endbuf = rbuf + tot;			/* count space for pointers */
e0b30b
     align = (sizeof(char*)-1) - ((tot + sizeof(char*)-1) & (sizeof(char*)-1));
e0b30b
-    for (c = 0, p = rbuf; p < endbuf; p++) {
e0b30b
-	if (!*p || *p == '\n')
e0b30b
+    c = sizeof(char*);				/* one extra for NULL term */
e0b30b
+    for (p = rbuf; p < endbuf; p++) {
e0b30b
+	if (!*p || *p == '\n') {
e0b30b
+	    if (c >= INT_MAX - (tot + (int)sizeof(char*) + align)) break;
e0b30b
 	    c += sizeof(char*);
e0b30b
+	}
e0b30b
 	if (*p == '\n')
e0b30b
 	    *p = 0;
e0b30b
     }
e0b30b
-    c += sizeof(char*);				/* one extra for NULL term */
e0b30b
 
e0b30b
     rbuf = xrealloc(rbuf, tot + c + align);	/* make room for ptrs AT END */
e0b30b
     endbuf = rbuf + tot;			/* addr just past data buf */
e0b30b
     q = ret = (char**) (endbuf+align);		/* ==> free(*ret) to dealloc */
e0b30b
-    *q++ = p = rbuf;				/* point ptrs to the strings */
e0b30b
-    endbuf--;					/* do not traverse final NUL */
e0b30b
-    while (++p < endbuf)
e0b30b
-    	if (!*p)				/* NUL char implies that */
e0b30b
-	    *q++ = p+1;				/* next string -> next char */
e0b30b
-
e0b30b
+    for (strp = p = rbuf; p < endbuf; p++) {
e0b30b
+	if (!*p) {				/* NUL char implies that */
e0b30b
+	    if (c < 2 * (int)sizeof(char*)) break;
e0b30b
+	    c -= sizeof(char*);
e0b30b
+	    *q++ = strp;			/* point ptrs to the strings */
e0b30b
+	    strp = p+1;				/* next string -> next char */
e0b30b
+	}
e0b30b
+    }
e0b30b
     *q = 0;					/* null ptr list terminator */
e0b30b
     return ret;
e0b30b
 }
e0b30b
-- 
e0b30b
2.14.3
e0b30b