67d8e9
From 5c44459c3b28a9bd3283aaceab7c615f8020c531 Mon Sep 17 00:00:00 2001
67d8e9
From: Mark Adler <madler@alumni.caltech.edu>
67d8e9
Date: Tue, 17 Apr 2018 22:09:22 -0700
67d8e9
Subject: [PATCH] Fix a bug that can crash deflate on some input when using
67d8e9
 Z_FIXED.
67d8e9
67d8e9
This bug was reported by Danilo Ramos of Eideticom, Inc. It has
67d8e9
lain in wait 13 years before being found! The bug was introduced
67d8e9
in zlib 1.2.2.2, with the addition of the Z_FIXED option. That
67d8e9
option forces the use of fixed Huffman codes. For rare inputs with
67d8e9
a large number of distant matches, the pending buffer into which
67d8e9
the compressed data is written can overwrite the distance symbol
67d8e9
table which it overlays. That results in corrupted output due to
67d8e9
invalid distances, and can result in out-of-bound accesses,
67d8e9
crashing the application.
67d8e9
67d8e9
The fix here combines the distance buffer and literal/length
67d8e9
buffers into a single symbol buffer. Now three bytes of pending
67d8e9
buffer space are opened up for each literal or length/distance
67d8e9
pair consumed, instead of the previous two bytes. This assures
67d8e9
that the pending buffer cannot overwrite the symbol table, since
67d8e9
the maximum fixed code compressed length/distance is 31 bits, and
67d8e9
since there are four bytes of pending space for every three bytes
67d8e9
of symbol space.
67d8e9
---
67d8e9
 deflate.c | 74 ++++++++++++++++++++++++++++++++++++++++---------------
67d8e9
 deflate.h | 25 +++++++++----------
67d8e9
 trees.c   | 50 +++++++++++--------------------------
67d8e9
 3 files changed, 79 insertions(+), 70 deletions(-)
67d8e9
67d8e9
diff --git a/deflate.c b/deflate.c
67d8e9
index 425babc..19cba87 100644
67d8e9
--- a/deflate.c
67d8e9
+++ b/deflate.c
67d8e9
@@ -255,11 +255,6 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
67d8e9
     int wrap = 1;
67d8e9
     static const char my_version[] = ZLIB_VERSION;
67d8e9
 
67d8e9
-    ushf *overlay;
67d8e9
-    /* We overlay pending_buf and d_buf+l_buf. This works since the average
67d8e9
-     * output size for (length,distance) codes is <= 24 bits.
67d8e9
-     */
67d8e9
-
67d8e9
     if (version == Z_NULL || version[0] != my_version[0] ||
67d8e9
         stream_size != sizeof(z_stream)) {
67d8e9
         return Z_VERSION_ERROR;
67d8e9
@@ -329,9 +324,47 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
67d8e9
 
67d8e9
     s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
67d8e9
 
67d8e9
-    overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
67d8e9
-    s->pending_buf = (uchf *) overlay;
67d8e9
-    s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
67d8e9
+    /* We overlay pending_buf and sym_buf. This works since the average size
67d8e9
+     * for length/distance pairs over any compressed block is assured to be 31
67d8e9
+     * bits or less.
67d8e9
+     *
67d8e9
+     * Analysis: The longest fixed codes are a length code of 8 bits plus 5
67d8e9
+     * extra bits, for lengths 131 to 257. The longest fixed distance codes are
67d8e9
+     * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest
67d8e9
+     * possible fixed-codes length/distance pair is then 31 bits total.
67d8e9
+     *
67d8e9
+     * sym_buf starts one-fourth of the way into pending_buf. So there are
67d8e9
+     * three bytes in sym_buf for every four bytes in pending_buf. Each symbol
67d8e9
+     * in sym_buf is three bytes -- two for the distance and one for the
67d8e9
+     * literal/length. As each symbol is consumed, the pointer to the next
67d8e9
+     * sym_buf value to read moves forward three bytes. From that symbol, up to
67d8e9
+     * 31 bits are written to pending_buf. The closest the written pending_buf
67d8e9
+     * bits gets to the next sym_buf symbol to read is just before the last
67d8e9
+     * code is written. At that time, 31*(n-2) bits have been written, just
67d8e9
+     * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at
67d8e9
+     * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1
67d8e9
+     * symbols are written.) The closest the writing gets to what is unread is
67d8e9
+     * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and
67d8e9
+     * can range from 128 to 32768.
67d8e9
+     *
67d8e9
+     * Therefore, at a minimum, there are 142 bits of space between what is
67d8e9
+     * written and what is read in the overlain buffers, so the symbols cannot
67d8e9
+     * be overwritten by the compressed data. That space is actually 139 bits,
67d8e9
+     * due to the three-bit fixed-code block header.
67d8e9
+     *
67d8e9
+     * That covers the case where either Z_FIXED is specified, forcing fixed
67d8e9
+     * codes, or when the use of fixed codes is chosen, because that choice
67d8e9
+     * results in a smaller compressed block than dynamic codes. That latter
67d8e9
+     * condition then assures that the above analysis also covers all dynamic
67d8e9
+     * blocks. A dynamic-code block will only be chosen to be emitted if it has
67d8e9
+     * fewer bits than a fixed-code block would for the same set of symbols.
67d8e9
+     * Therefore its average symbol length is assured to be less than 31. So
67d8e9
+     * the compressed data for a dynamic block also cannot overwrite the
67d8e9
+     * symbols from which it is being constructed.
67d8e9
+     */
67d8e9
+
67d8e9
+    s->pending_buf = (uchf *) ZALLOC(strm, s->lit_bufsize, 4);
67d8e9
+    s->pending_buf_size = (ulg)s->lit_bufsize * 4;
67d8e9
 
67d8e9
     if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
67d8e9
         s->pending_buf == Z_NULL) {
67d8e9
@@ -340,8 +373,12 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
67d8e9
         deflateEnd (strm);
67d8e9
         return Z_MEM_ERROR;
67d8e9
     }
67d8e9
-    s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
67d8e9
-    s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
67d8e9
+    s->sym_buf = s->pending_buf + s->lit_bufsize;
67d8e9
+    s->sym_end = (s->lit_bufsize - 1) * 3;
67d8e9
+    /* We avoid equality with lit_bufsize*3 because of wraparound at 64K
67d8e9
+     * on 16 bit machines and because stored blocks are restricted to
67d8e9
+     * 64K-1 bytes.
67d8e9
+     */
67d8e9
 
67d8e9
     s->level = level;
67d8e9
     s->strategy = strategy;
67d8e9
@@ -552,7 +589,7 @@ int ZEXPORT deflatePrime (strm, bits, value)
67d8e9
 
67d8e9
     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
67d8e9
     s = strm->state;
67d8e9
-    if ((Bytef *)(s->d_buf) < s->pending_out + ((Buf_size + 7) >> 3))
67d8e9
+    if (s->sym_buf < s->pending_out + ((Buf_size + 7) >> 3))
67d8e9
         return Z_BUF_ERROR;
67d8e9
     do {
67d8e9
         put = Buf_size - s->bi_valid;
67d8e9
@@ -1113,7 +1150,6 @@ int ZEXPORT deflateCopy (dest, source)
67d8e9
 #else
67d8e9
     deflate_state *ds;
67d8e9
     deflate_state *ss;
67d8e9
-    ushf *overlay;
67d8e9
 
67d8e9
 
67d8e9
     if (deflateStateCheck(source) || dest == Z_NULL) {
67d8e9
@@ -1133,8 +1169,7 @@ int ZEXPORT deflateCopy (dest, source)
67d8e9
     ds->window = (Bytef *) ZALLOC_WINDOW(dest, ds->w_size, 2*sizeof(Byte));
67d8e9
     ds->prev   = (Posf *)  ZALLOC(dest, ds->w_size, sizeof(Pos));
67d8e9
     ds->head   = (Posf *)  ZALLOC(dest, ds->hash_size, sizeof(Pos));
67d8e9
-    overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
67d8e9
-    ds->pending_buf = (uchf *) overlay;
67d8e9
+    ds->pending_buf = (uchf *) ZALLOC(dest, ds->lit_bufsize, 4);
67d8e9
 
67d8e9
     if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
67d8e9
         ds->pending_buf == Z_NULL) {
67d8e9
@@ -1148,8 +1183,7 @@ int ZEXPORT deflateCopy (dest, source)
67d8e9
     zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
67d8e9
 
67d8e9
     ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
67d8e9
-    ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
67d8e9
-    ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
67d8e9
+    ds->sym_buf = ds->pending_buf + ds->lit_bufsize;
67d8e9
 
67d8e9
     ds->l_desc.dyn_tree = ds->dyn_ltree;
67d8e9
     ds->d_desc.dyn_tree = ds->dyn_dtree;
67d8e9
@@ -1925,7 +1959,7 @@ local block_state deflate_fast(s, flush)
67d8e9
         FLUSH_BLOCK(s, 1);
67d8e9
         return finish_done;
67d8e9
     }
67d8e9
-    if (s->last_lit)
67d8e9
+    if (s->sym_next)
67d8e9
         FLUSH_BLOCK(s, 0);
67d8e9
     return block_done;
67d8e9
 }
67d8e9
@@ -2056,7 +2090,7 @@ local block_state deflate_slow(s, flush)
67d8e9
         FLUSH_BLOCK(s, 1);
67d8e9
         return finish_done;
67d8e9
     }
67d8e9
-    if (s->last_lit)
67d8e9
+    if (s->sym_next)
67d8e9
         FLUSH_BLOCK(s, 0);
67d8e9
     return block_done;
67d8e9
 }
67d8e9
@@ -2131,7 +2165,7 @@ local block_state deflate_rle(s, flush)
67d8e9
         FLUSH_BLOCK(s, 1);
67d8e9
         return finish_done;
67d8e9
     }
67d8e9
-    if (s->last_lit)
67d8e9
+    if (s->sym_next)
67d8e9
         FLUSH_BLOCK(s, 0);
67d8e9
     return block_done;
67d8e9
 }
67d8e9
@@ -2170,7 +2204,7 @@ local block_state deflate_huff(s, flush)
67d8e9
         FLUSH_BLOCK(s, 1);
67d8e9
         return finish_done;
67d8e9
     }
67d8e9
-    if (s->last_lit)
67d8e9
+    if (s->sym_next)
67d8e9
         FLUSH_BLOCK(s, 0);
67d8e9
     return block_done;
67d8e9
 }
67d8e9
diff --git a/deflate.h b/deflate.h
67d8e9
index 23ecdd3..d4cf1a9 100644
67d8e9
--- a/deflate.h
67d8e9
+++ b/deflate.h
67d8e9
@@ -217,7 +217,7 @@ typedef struct internal_state {
67d8e9
     /* Depth of each subtree used as tie breaker for trees of equal frequency
67d8e9
      */
67d8e9
 
67d8e9
-    uchf *l_buf;          /* buffer for literals or lengths */
67d8e9
+    uchf *sym_buf;        /* buffer for distances and literals/lengths */
67d8e9
 
67d8e9
     uInt  lit_bufsize;
67d8e9
     /* Size of match buffer for literals/lengths.  There are 4 reasons for
67d8e9
@@ -239,13 +239,8 @@ typedef struct internal_state {
67d8e9
      *   - I can't count above 4
67d8e9
      */
67d8e9
 
67d8e9
-    uInt last_lit;      /* running index in l_buf */
67d8e9
-
67d8e9
-    ushf *d_buf;
67d8e9
-    /* Buffer for distances. To simplify the code, d_buf and l_buf have
67d8e9
-     * the same number of elements. To use different lengths, an extra flag
67d8e9
-     * array would be necessary.
67d8e9
-     */
67d8e9
+    uInt sym_next;      /* running index in sym_buf */
67d8e9
+    uInt sym_end;       /* symbol table full when sym_next reaches this */
67d8e9
 
67d8e9
     ulg opt_len;        /* bit length of current block with optimal trees */
67d8e9
     ulg static_len;     /* bit length of current block with static trees */
67d8e9
@@ -325,20 +320,22 @@ void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf,
67d8e9
 
67d8e9
 # define _tr_tally_lit(s, c, flush) \
67d8e9
   { uch cc = (c); \
67d8e9
-    s->d_buf[s->last_lit] = 0; \
67d8e9
-    s->l_buf[s->last_lit++] = cc; \
67d8e9
+    s->sym_buf[s->sym_next++] = 0; \
67d8e9
+    s->sym_buf[s->sym_next++] = 0; \
67d8e9
+    s->sym_buf[s->sym_next++] = cc; \
67d8e9
     s->dyn_ltree[cc].Freq++; \
67d8e9
-    flush = (s->last_lit == s->lit_bufsize-1); \
67d8e9
+    flush = (s->sym_next == s->sym_end); \
67d8e9
    }
67d8e9
 # define _tr_tally_dist(s, distance, length, flush) \
67d8e9
   { uch len = (uch)(length); \
67d8e9
     ush dist = (ush)(distance); \
67d8e9
-    s->d_buf[s->last_lit] = dist; \
67d8e9
-    s->l_buf[s->last_lit++] = len; \
67d8e9
+    s->sym_buf[s->sym_next++] = dist; \
67d8e9
+    s->sym_buf[s->sym_next++] = dist >> 8; \
67d8e9
+    s->sym_buf[s->sym_next++] = len; \
67d8e9
     dist--; \
67d8e9
     s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
67d8e9
     s->dyn_dtree[d_code(dist)].Freq++; \
67d8e9
-    flush = (s->last_lit == s->lit_bufsize-1); \
67d8e9
+    flush = (s->sym_next == s->sym_end); \
67d8e9
   }
67d8e9
 #else
67d8e9
 # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
67d8e9
diff --git a/trees.c b/trees.c
67d8e9
index 4f4a650..decaeb7 100644
67d8e9
--- a/trees.c
67d8e9
+++ b/trees.c
67d8e9
@@ -416,7 +416,7 @@ local void init_block(s)
67d8e9
 
67d8e9
     s->dyn_ltree[END_BLOCK].Freq = 1;
67d8e9
     s->opt_len = s->static_len = 0L;
67d8e9
-    s->last_lit = s->matches = 0;
67d8e9
+    s->sym_next = s->matches = 0;
67d8e9
 }
67d8e9
 
67d8e9
 #define SMALLEST 1
67d8e9
@@ -948,7 +948,7 @@ void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)
67d8e9
 
67d8e9
         Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
67d8e9
                 opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
67d8e9
-                s->last_lit));
67d8e9
+                s->sym_next / 3));
67d8e9
 
67d8e9
         if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
67d8e9
 
67d8e9
@@ -1017,8 +1017,9 @@ int ZLIB_INTERNAL _tr_tally (s, dist, lc)
67d8e9
     unsigned dist;  /* distance of matched string */
67d8e9
     unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
67d8e9
 {
67d8e9
-    s->d_buf[s->last_lit] = (ush)dist;
67d8e9
-    s->l_buf[s->last_lit++] = (uch)lc;
67d8e9
+    s->sym_buf[s->sym_next++] = dist;
67d8e9
+    s->sym_buf[s->sym_next++] = dist >> 8;
67d8e9
+    s->sym_buf[s->sym_next++] = lc;
67d8e9
     if (dist == 0) {
67d8e9
         /* lc is the unmatched char */
67d8e9
         s->dyn_ltree[lc].Freq++;
67d8e9
@@ -1033,30 +1034,7 @@ int ZLIB_INTERNAL _tr_tally (s, dist, lc)
67d8e9
         s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
67d8e9
         s->dyn_dtree[d_code(dist)].Freq++;
67d8e9
     }
67d8e9
-
67d8e9
-#ifdef TRUNCATE_BLOCK
67d8e9
-    /* Try to guess if it is profitable to stop the current block here */
67d8e9
-    if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
67d8e9
-        /* Compute an upper bound for the compressed length */
67d8e9
-        ulg out_length = (ulg)s->last_lit*8L;
67d8e9
-        ulg in_length = (ulg)((long)s->strstart - s->block_start);
67d8e9
-        int dcode;
67d8e9
-        for (dcode = 0; dcode < D_CODES; dcode++) {
67d8e9
-            out_length += (ulg)s->dyn_dtree[dcode].Freq *
67d8e9
-                (5L+extra_dbits[dcode]);
67d8e9
-        }
67d8e9
-        out_length >>= 3;
67d8e9
-        Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
67d8e9
-               s->last_lit, in_length, out_length,
67d8e9
-               100L - out_length*100L/in_length));
67d8e9
-        if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
67d8e9
-    }
67d8e9
-#endif
67d8e9
-    return (s->last_lit == s->lit_bufsize-1);
67d8e9
-    /* We avoid equality with lit_bufsize because of wraparound at 64K
67d8e9
-     * on 16 bit machines and because stored blocks are restricted to
67d8e9
-     * 64K-1 bytes.
67d8e9
-     */
67d8e9
+    return (s->sym_next == s->sym_end);
67d8e9
 }
67d8e9
 
67d8e9
 /* ===========================================================================
67d8e9
@@ -1069,13 +1047,14 @@ local void compress_block(s, ltree, dtree)
67d8e9
 {
67d8e9
     unsigned dist;      /* distance of matched string */
67d8e9
     int lc;             /* match length or unmatched char (if dist == 0) */
67d8e9
-    unsigned lx = 0;    /* running index in l_buf */
67d8e9
+    unsigned sx = 0;    /* running index in sym_buf */
67d8e9
     unsigned code;      /* the code to send */
67d8e9
     int extra;          /* number of extra bits to send */
67d8e9
 
67d8e9
-    if (s->last_lit != 0) do {
67d8e9
-        dist = s->d_buf[lx];
67d8e9
-        lc = s->l_buf[lx++];
67d8e9
+    if (s->sym_next != 0) do {
67d8e9
+        dist = s->sym_buf[sx++] & 0xff;
67d8e9
+        dist += (unsigned)(s->sym_buf[sx++] & 0xff) << 8;
67d8e9
+        lc = s->sym_buf[sx++];
67d8e9
         if (dist == 0) {
67d8e9
             send_code(s, lc, ltree); /* send a literal byte */
67d8e9
             Tracecv(isgraph(lc), (stderr," '%c' ", lc));
67d8e9
@@ -1100,11 +1079,10 @@ local void compress_block(s, ltree, dtree)
67d8e9
             }
67d8e9
         } /* literal or match pair ? */
67d8e9
 
67d8e9
-        /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
67d8e9
-        Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
67d8e9
-               "pendingBuf overflow");
67d8e9
+        /* Check that the overlay between pending_buf and sym_buf is ok: */
67d8e9
+        Assert(s->pending < s->lit_bufsize + sx, "pendingBuf overflow");
67d8e9
 
67d8e9
-    } while (lx < s->last_lit);
67d8e9
+    } while (sx < s->sym_next);
67d8e9
 
67d8e9
     send_code(s, END_BLOCK, ltree);
67d8e9
 }
67d8e9
-- 
67d8e9
2.34.1
67d8e9