Browse Source

Prevent double free on huge files with 32 bit.

The function compat_getdelim_ is used for tor_getline if tor is compiled
on a system that lacks getline and getdelim. These systems should be
very rare, considering that getdelim is POSIX.

If this system is further a 32 bit architecture, it is possible to
trigger a double free with huge files.

If bufsiz has been already increased to 2 GB, the next chunk would
be 4 GB in size, which wraps around to 0 due to 32 bit limitations.

A realloc(*buf, 0) could be imagined as "free(*buf); return malloc(0);"
which therefore could return NULL. The code in question considers
that an error, but will keep the value of *buf pointing to already
freed memory.

The caller of tor_getline() would free the pointer again, therefore
leading to a double free.

This code can only be triggered in dirserv_read_measured_bandwidths
with a huge measured bandwith list file on a system that actually
allows to reach 2 GB of space through realloc.

It is not possible to trigger this on Linux with glibc or other major
*BSD systems even on unit tests, because these systems cannot reach
so much memory due to memory fragmentation.

This patch is effectively based on the penetration test report of
cure53 for curl available at https://cure53.de/pentest-report_curl.pdf
and explained under section "CRL-01-007 Double-free in aprintf() via
unsafe size_t multiplication (Medium)".
Tobias Stoeckmann 5 years ago
parent
commit
9ce0bdd226
1 changed files with 2 additions and 1 deletions
  1. 2 1
      src/ext/getdelim.c

+ 2 - 1
src/ext/getdelim.c

@@ -67,7 +67,8 @@ compat_getdelim_(char **buf, size_t *bufsiz, int delimiter, FILE *fp)
 			char *nbuf;
 			size_t nbufsiz = *bufsiz * 2;
 			ssize_t d = ptr - *buf;
-			if ((nbuf = raw_realloc(*buf, nbufsiz)) == NULL)
+			if (nbufsiz < *bufsiz ||
+			    (nbuf = raw_realloc(*buf, nbufsiz)) == NULL)
 				return -1;
 			*buf = nbuf;
 			*bufsiz = nbufsiz;