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