02d1f3
From 47b3ceae397d21bf822bc2ac73052a4b1daf8e1c Mon Sep 17 00:00:00 2001
02d1f3
From: Mark Adler <madler@alumni.caltech.edu>
02d1f3
Date: Tue, 11 Jun 2019 22:01:18 -0700
02d1f3
Subject: [PATCH] Detect and reject a zip bomb using overlapped entries.
02d1f3
02d1f3
This detects an invalid zip file that has at least one entry that
02d1f3
overlaps with another entry or with the central directory to the
02d1f3
end of the file. A Fifield zip bomb uses overlapped local entries
02d1f3
to vastly increase the potential inflation ratio. Such an invalid
02d1f3
zip file is rejected.
02d1f3
02d1f3
See https://www.bamsoftware.com/hacks/zipbomb/ for David Fifield's
02d1f3
analysis, construction, and examples of such zip bombs.
02d1f3
02d1f3
The detection maintains a list of covered spans of the zip files
02d1f3
so far, where the central directory to the end of the file and any
02d1f3
bytes preceding the first entry at zip file offset zero are
02d1f3
considered covered initially. Then as each entry is decompressed
02d1f3
or tested, it is considered covered. When a new entry is about to
02d1f3
be processed, its initial offset is checked to see if it is
02d1f3
contained by a covered span. If so, the zip file is rejected as
02d1f3
invalid.
02d1f3
02d1f3
This commit depends on a preceding commit: "Fix bug in
02d1f3
undefer_input() that misplaced the input state."
02d1f3
---
02d1f3
 extract.c | 190 +++++++++++++++++++++++++++++++++++++++++++++++++++++-
02d1f3
 globals.c |   1 +
02d1f3
 globals.h |   3 +
02d1f3
 process.c |  11 ++++
02d1f3
 unzip.h   |   1 +
02d1f3
 5 files changed, 205 insertions(+), 1 deletion(-)
02d1f3
02d1f3
diff --git a/extract.c b/extract.c
02d1f3
index 1acd769..0973a33 100644
02d1f3
--- a/extract.c
02d1f3
+++ b/extract.c
02d1f3
@@ -319,6 +319,125 @@ static ZCONST char Far UnsupportedExtraField[] =
02d1f3
   "\nerror:  unsupported extra-field compression type (%u)--skipping\n";
02d1f3
 static ZCONST char Far BadExtraFieldCRC[] =
02d1f3
   "error [%s]:  bad extra-field CRC %08lx (should be %08lx)\n";
02d1f3
+static ZCONST char Far NotEnoughMemCover[] =
02d1f3
+  "error: not enough memory for bomb detection\n";
02d1f3
+static ZCONST char Far OverlappedComponents[] =
02d1f3
+  "error: invalid zip file with overlapped components (possible zip bomb)\n";
02d1f3
+
02d1f3
+
02d1f3
+
02d1f3
+
02d1f3
+
02d1f3
+/* A growable list of spans. */
02d1f3
+typedef zoff_t bound_t;
02d1f3
+typedef struct {
02d1f3
+    bound_t beg;        /* start of the span */
02d1f3
+    bound_t end;        /* one past the end of the span */
02d1f3
+} span_t;
02d1f3
+typedef struct {
02d1f3
+    span_t *span;       /* allocated, distinct, and sorted list of spans */
02d1f3
+    size_t num;         /* number of spans in the list */
02d1f3
+    size_t max;         /* allocated number of spans (num <= max) */
02d1f3
+} cover_t;
02d1f3
+
02d1f3
+/*
02d1f3
+ * Return the index of the first span in cover whose beg is greater than val.
02d1f3
+ * If there is no such span, then cover->num is returned.
02d1f3
+ */
02d1f3
+static size_t cover_find(cover, val)
02d1f3
+    cover_t *cover;
02d1f3
+    bound_t val;
02d1f3
+{
02d1f3
+    size_t lo = 0, hi = cover->num;
02d1f3
+    while (lo < hi) {
02d1f3
+        size_t mid = (lo + hi) >> 1;
02d1f3
+        if (val < cover->span[mid].beg)
02d1f3
+            hi = mid;
02d1f3
+        else
02d1f3
+            lo = mid + 1;
02d1f3
+    }
02d1f3
+    return hi;
02d1f3
+}
02d1f3
+
02d1f3
+/* Return true if val lies within any one of the spans in cover. */
02d1f3
+static int cover_within(cover, val)
02d1f3
+    cover_t *cover;
02d1f3
+    bound_t val;
02d1f3
+{
02d1f3
+    size_t pos = cover_find(cover, val);
02d1f3
+    return pos > 0 && val < cover->span[pos - 1].end;
02d1f3
+}
02d1f3
+
02d1f3
+/*
02d1f3
+ * Add a new span to the list, but only if the new span does not overlap any
02d1f3
+ * spans already in the list. The new span covers the values beg..end-1. beg
02d1f3
+ * must be less than end.
02d1f3
+ *
02d1f3
+ * Keep the list sorted and merge adjacent spans. Grow the allocated space for
02d1f3
+ * the list as needed. On success, 0 is returned. If the new span overlaps any
02d1f3
+ * existing spans, then 1 is returned and the new span is not added to the
02d1f3
+ * list. If the new span is invalid because beg is greater than or equal to
02d1f3
+ * end, then -1 is returned. If the list needs to be grown but the memory
02d1f3
+ * allocation fails, then -2 is returned.
02d1f3
+ */
02d1f3
+static int cover_add(cover, beg, end)
02d1f3
+    cover_t *cover;
02d1f3
+    bound_t beg;
02d1f3
+    bound_t end;
02d1f3
+{
02d1f3
+    size_t pos;
02d1f3
+    int prec, foll;
02d1f3
+
02d1f3
+    if (beg >= end)
02d1f3
+    /* The new span is invalid. */
02d1f3
+        return -1;
02d1f3
+
02d1f3
+    /* Find where the new span should go, and make sure that it does not
02d1f3
+       overlap with any existing spans. */
02d1f3
+    pos = cover_find(cover, beg);
02d1f3
+    if ((pos > 0 && beg < cover->span[pos - 1].end) ||
02d1f3
+        (pos < cover->num && end > cover->span[pos].beg))
02d1f3
+        return 1;
02d1f3
+
02d1f3
+    /* Check for adjacencies. */
02d1f3
+    prec = pos > 0 && beg == cover->span[pos - 1].end;
02d1f3
+    foll = pos < cover->num && end == cover->span[pos].beg;
02d1f3
+    if (prec && foll) {
02d1f3
+        /* The new span connects the preceding and following spans. Merge the
02d1f3
+           following span into the preceding span, and delete the following
02d1f3
+           span. */
02d1f3
+        cover->span[pos - 1].end = cover->span[pos].end;
02d1f3
+        cover->num--;
02d1f3
+        memmove(cover->span + pos, cover->span + pos + 1,
02d1f3
+                (cover->num - pos) * sizeof(span_t));
02d1f3
+    }
02d1f3
+    else if (prec)
02d1f3
+        /* The new span is adjacent only to the preceding span. Extend the end
02d1f3
+           of the preceding span. */
02d1f3
+        cover->span[pos - 1].end = end;
02d1f3
+    else if (foll)
02d1f3
+        /* The new span is adjacent only to the following span. Extend the
02d1f3
+           beginning of the following span. */
02d1f3
+        cover->span[pos].beg = beg;
02d1f3
+    else {
02d1f3
+        /* The new span has gaps between both the preceding and the following
02d1f3
+           spans. Assure that there is room and insert the span.  */
02d1f3
+        if (cover->num == cover->max) {
02d1f3
+            size_t max = cover->max == 0 ? 16 : cover->max << 1;
02d1f3
+            span_t *span = realloc(cover->span, max * sizeof(span_t));
02d1f3
+            if (span == NULL)
02d1f3
+                return -2;
02d1f3
+            cover->span = span;
02d1f3
+            cover->max = max;
02d1f3
+        }
02d1f3
+        memmove(cover->span + pos + 1, cover->span + pos,
02d1f3
+                (cover->num - pos) * sizeof(span_t));
02d1f3
+        cover->num++;
02d1f3
+        cover->span[pos].beg = beg;
02d1f3
+        cover->span[pos].end = end;
02d1f3
+    }
02d1f3
+    return 0;
02d1f3
+}
02d1f3
 
02d1f3
 
02d1f3
 
02d1f3
@@ -374,6 +493,29 @@ int extract_or_test_files(__G)    /* return PK-type error code */
02d1f3
     }
02d1f3
 #endif /* !SFX || SFX_EXDIR */
02d1f3
 
02d1f3
+    /* One more: initialize cover structure for bomb detection. Start with a
02d1f3
+       span that covers the central directory though the end of the file. */
02d1f3
+    if (G.cover == NULL) {
02d1f3
+        G.cover = malloc(sizeof(cover_t));
02d1f3
+        if (G.cover == NULL) {
02d1f3
+            Info(slide, 0x401, ((char *)slide,
02d1f3
+              LoadFarString(NotEnoughMemCover)));
02d1f3
+            return PK_MEM;
02d1f3
+        }
02d1f3
+        ((cover_t *)G.cover)->span = NULL;
02d1f3
+        ((cover_t *)G.cover)->max = 0;
02d1f3
+    }
02d1f3
+    ((cover_t *)G.cover)->num = 0;
02d1f3
+    if ((G.extra_bytes != 0 &&
02d1f3
+         cover_add((cover_t *)G.cover, 0, G.extra_bytes) != 0) ||
02d1f3
+        cover_add((cover_t *)G.cover,
02d1f3
+                  G.extra_bytes + G.ecrec.offset_start_central_directory,
02d1f3
+                  G.ziplen) != 0) {
02d1f3
+        Info(slide, 0x401, ((char *)slide,
02d1f3
+          LoadFarString(NotEnoughMemCover)));
02d1f3
+        return PK_MEM;
02d1f3
+    }
02d1f3
+
02d1f3
 /*---------------------------------------------------------------------------
02d1f3
     The basic idea of this function is as follows.  Since the central di-
02d1f3
     rectory lies at the end of the zipfile and the member files lie at the
02d1f3
@@ -591,7 +733,8 @@ int extract_or_test_files(__G)    /* return PK-type error code */
02d1f3
             if (error > error_in_archive)
02d1f3
                 error_in_archive = error;
02d1f3
             /* ...and keep going (unless disk full or user break) */
02d1f3
-            if (G.disk_full > 1 || error_in_archive == IZ_CTRLC) {
02d1f3
+            if (G.disk_full > 1 || error_in_archive == IZ_CTRLC ||
02d1f3
+                error == PK_BOMB) {
02d1f3
                 /* clear reached_end to signal premature stop ... */
02d1f3
                 reached_end = FALSE;
02d1f3
                 /* ... and cancel scanning the central directory */
02d1f3
@@ -1060,6 +1203,11 @@ static int extract_or_test_entrylist(__G__ numchunk,
02d1f3
 
02d1f3
         /* seek_zipf(__G__ pInfo->offset);  */
02d1f3
         request = G.pInfo->offset + G.extra_bytes;
02d1f3
+        if (cover_within((cover_t *)G.cover, request)) {
02d1f3
+            Info(slide, 0x401, ((char *)slide,
02d1f3
+              LoadFarString(OverlappedComponents)));
02d1f3
+            return PK_BOMB;
02d1f3
+        }
02d1f3
         inbuf_offset = request % INBUFSIZ;
02d1f3
         bufstart = request - inbuf_offset;
02d1f3
 
02d1f3
@@ -1591,6 +1739,18 @@ static int extract_or_test_entrylist(__G__ numchunk,
02d1f3
             return IZ_CTRLC;        /* cancel operation by user request */
02d1f3
         }
02d1f3
 #endif
02d1f3
+        error = cover_add((cover_t *)G.cover, request,
02d1f3
+                          G.cur_zipfile_bufstart + (G.inptr - G.inbuf));
02d1f3
+        if (error < 0) {
02d1f3
+            Info(slide, 0x401, ((char *)slide,
02d1f3
+              LoadFarString(NotEnoughMemCover)));
02d1f3
+            return PK_MEM;
02d1f3
+        }
02d1f3
+        if (error != 0) {
02d1f3
+            Info(slide, 0x401, ((char *)slide,
02d1f3
+              LoadFarString(OverlappedComponents)));
02d1f3
+            return PK_BOMB;
02d1f3
+        }
02d1f3
 #ifdef MACOS  /* MacOS is no preemptive OS, thus call event-handling by hand */
02d1f3
         UserStop();
02d1f3
 #endif
02d1f3
@@ -1992,6 +2152,34 @@ static int extract_or_test_member(__G)    /* return PK-type error code */
02d1f3
     }
02d1f3
 
02d1f3
     undefer_input(__G);
02d1f3
+
02d1f3
+    if ((G.lrec.general_purpose_bit_flag & 8) != 0) {
02d1f3
+        /* skip over data descriptor (harder than it sounds, due to signature
02d1f3
+         * ambiguity)
02d1f3
+         */
02d1f3
+#       define SIG 0x08074b50
02d1f3
+#       define LOW 0xffffffff
02d1f3
+        uch buf[12];
02d1f3
+        unsigned shy = 12 - readbuf((char *)buf, 12);
02d1f3
+        ulg crc = shy ? 0 : makelong(buf);
02d1f3
+        ulg clen = shy ? 0 : makelong(buf + 4);
02d1f3
+        ulg ulen = shy ? 0 : makelong(buf + 8); /* or high clen if ZIP64 */
02d1f3
+        if (crc == SIG &&                       /* if not SIG, no signature */
02d1f3
+            (G.lrec.crc32 != SIG ||             /* if not SIG, have signature */
02d1f3
+             (clen == SIG &&                    /* if not SIG, no signature */
02d1f3
+              ((G.lrec.csize & LOW) != SIG ||   /* if not SIG, have signature */
02d1f3
+               (ulen == SIG &&                  /* if not SIG, no signature */
02d1f3
+                (G.zip64 ? G.lrec.csize >> 32 : G.lrec.ucsize) != SIG
02d1f3
+                                                /* if not SIG, have signature */
02d1f3
+                )))))
02d1f3
+                   /* skip four more bytes to account for signature */
02d1f3
+                   shy += 4 - readbuf((char *)buf, 4);
02d1f3
+        if (G.zip64)
02d1f3
+            shy += 8 - readbuf((char *)buf, 8); /* skip eight more for ZIP64 */
02d1f3
+        if (shy)
02d1f3
+            error = PK_ERR;
02d1f3
+    }
02d1f3
+
02d1f3
     return error;
02d1f3
 
02d1f3
 } /* end function extract_or_test_member() */
02d1f3
diff --git a/globals.c b/globals.c
02d1f3
index fa8cca5..1e0f608 100644
02d1f3
--- a/globals.c
02d1f3
+++ b/globals.c
02d1f3
@@ -181,6 +181,7 @@ Uz_Globs *globalsCtor()
02d1f3
 # if (!defined(NO_TIMESTAMPS))
02d1f3
     uO.D_flag=1;    /* default to '-D', no restoration of dir timestamps */
02d1f3
 # endif
02d1f3
+    G.cover = NULL;     /* not allocated yet */
02d1f3
 #endif
02d1f3
 
02d1f3
     uO.lflag=(-1);
02d1f3
diff --git a/globals.h b/globals.h
02d1f3
index 11b7215..2bdcdeb 100644
02d1f3
--- a/globals.h
02d1f3
+++ b/globals.h
02d1f3
@@ -260,12 +260,15 @@ typedef struct Globals {
02d1f3
     ecdir_rec       ecrec;         /* used in unzip.c, extract.c */
02d1f3
     z_stat   statbuf;              /* used by main, mapname, check_for_newer */
02d1f3
 
02d1f3
+    int zip64;                     /* true if Zip64 info in extra field */
02d1f3
+
02d1f3
     int      mem_mode;
02d1f3
     uch      *outbufptr;           /* extract.c static */
02d1f3
     ulg      outsize;              /* extract.c static */
02d1f3
     int      reported_backslash;   /* extract.c static */
02d1f3
     int      disk_full;
02d1f3
     int      newfile;
02d1f3
+    void     **cover;              /* used in extract.c for bomb detection */
02d1f3
 
02d1f3
     int      didCRlast;            /* fileio static */
02d1f3
     ulg      numlines;             /* fileio static: number of lines printed */
02d1f3
diff --git a/process.c b/process.c
02d1f3
index 1e9a1e1..d2e4dc3 100644
02d1f3
--- a/process.c
02d1f3
+++ b/process.c
02d1f3
@@ -637,6 +637,13 @@ void free_G_buffers(__G)     /* releases all memory allocated in global vars */
02d1f3
     }
02d1f3
 #endif
02d1f3
 
02d1f3
+    /* Free the cover span list and the cover structure. */
02d1f3
+    if (G.cover != NULL) {
02d1f3
+        free(*(G.cover));
02d1f3
+        free(G.cover);
02d1f3
+        G.cover = NULL;
02d1f3
+    }
02d1f3
+
02d1f3
 } /* end function free_G_buffers() */
02d1f3
 
02d1f3
 
02d1f3
@@ -1890,6 +1897,8 @@ int getZip64Data(__G__ ef_buf, ef_len)
02d1f3
 #define Z64FLGS 0xffff
02d1f3
 #define Z64FLGL 0xffffffff
02d1f3
 
02d1f3
+    G.zip64 = FALSE;
02d1f3
+
02d1f3
     if (ef_len == 0 || ef_buf == NULL)
02d1f3
         return PK_COOL;
02d1f3
 
02d1f3
@@ -1927,6 +1936,8 @@ int getZip64Data(__G__ ef_buf, ef_len)
02d1f3
 #if 0
02d1f3
           break;                /* Expect only one EF_PKSZ64 block. */
02d1f3
 #endif /* 0 */
02d1f3
+
02d1f3
+          G.zip64 = TRUE;
02d1f3
         }
02d1f3
02d1f3
         /* Skip this extra field block. */
02d1f3
diff --git a/unzip.h b/unzip.h
02d1f3
index 5b2a326..ed24a5b 100644
02d1f3
--- a/unzip.h
02d1f3
+++ b/unzip.h
02d1f3
@@ -645,6 +645,7 @@ typedef struct _Uzp_cdir_Rec {
02d1f3
 #define PK_NOZIP           9   /* zipfile not found */
02d1f3
 #define PK_PARAM          10   /* bad or illegal parameters specified */
02d1f3
 #define PK_FIND           11   /* no files found */
02d1f3
+#define PK_BOMB           12   /* likely zip bomb */
02d1f3
 #define PK_DISK           50   /* disk full */
02d1f3
 #define PK_EOF            51   /* unexpected EOF */
02d1f3