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