Backport of:

From bd2abee5f0a9b5cbe3a1ab1f338c4fb8f6ca797b Mon Sep 17 00:00:00 2001
From: Richard Hughes <richard@hughsie.com>
Date: Mon, 18 Dec 2017 10:57:23 +0000
Subject: Do not crash when ncbytes is larger than the buffer size

This fixes CVE-2018-5345
---
 libgcab/cabinet.c               |  28 ++++++++++++++++++++++++----
 tests/test-ncbytes-overflow.cab | Bin 0 -> 95066 bytes
 2 files changed, 24 insertions(+), 4 deletions(-)
 create mode 100644 tests/test-ncbytes-overflow.cab

Index: gcab-0.7/libgcab/cabinet.c
===================================================================
--- gcab-0.7.orig/libgcab/cabinet.c	2018-01-24 07:45:58.211034829 -0500
+++ gcab-0.7/libgcab/cabinet.c	2018-01-24 07:46:32.570999055 -0500
@@ -459,18 +459,38 @@ cdata_read (cdata_t *cd, u1 res_data, gi
     gboolean success = FALSE;
     int ret, zret = Z_OK;
     gint compression = comptype & GCAB_COMPRESSION_MASK;
-    guint8 *buf = compression == GCAB_COMPRESSION_NONE ? cd->out : cd->in;
+    gsize buf_sz;
+    guint8 *buf = NULL;
     CHECKSUM datacsum;
 
-    if (compression > GCAB_COMPRESSION_MSZIP &&
-        compression != GCAB_COMPRESSION_LZX) {
+    /* decompress directly into ->out for no decompression */
+    switch (compression) {
+    case GCAB_COMPRESSION_NONE:
+        buf = cd->out;
+        buf_sz = sizeof(cd->out);
+        break;
+    case GCAB_COMPRESSION_MSZIP:
+    case GCAB_COMPRESSION_LZX:
+        buf = cd->in;
+        buf_sz = sizeof(cd->in);
+        break;
+    default:
         g_set_error (error, GCAB_ERROR, GCAB_ERROR_FAILED,
                      _("unsupported compression method %d"), compression);
-        return FALSE;
+        break;
     }
+    if (buf == NULL)
+        return FALSE;
 
     R4 (cd->checksum);
     R2 (cd->ncbytes);
+    if (cd->ncbytes > buf_sz) {
+        g_set_error (error, GCAB_ERROR, GCAB_ERROR_FAILED,
+                     "tried to decompress %" G_GUINT16_FORMAT " bytes "
+                     "into buffer of size %" G_GSIZE_FORMAT,
+                     cd->ncbytes, buf_sz);
+        return FALSE;
+    }
     R2 (cd->nubytes);
     cd->reserved = g_malloc (res_data);
     RN (cd->reserved, res_data);
