From: Stefan Hajnoczi <stefanha@redhat.com>
Date: Wed, 26 Mar 2014 13:05:58 +0100
Subject: dmg: sanitize chunk length and sectorcount (CVE-2014-0145)

Chunk length and sectorcount are used for decompression buffers as well
as the bdrv_pread() count argument.  Ensure that they have reasonable
values so neither memory allocation nor conversion from uint64_t to int
will cause problems.

Signed-off-by: Stefan Hajnoczi <stefanha@redhat.com>
Signed-off-by: Kevin Wolf <kwolf@redhat.com>
Reviewed-by: Max Reitz <mreitz@redhat.com>
Signed-off-by: Stefan Hajnoczi <stefanha@redhat.com>
(cherry picked from commit c165f7758009a4f793c1fc19ebb69cf55313450b)

Conflicts:
	block/dmg.c

diff --git a/block/dmg.c b/block/dmg.c
index 37902a4..463d149 100644
--- a/block/dmg.c
+++ b/block/dmg.c
@@ -27,6 +27,14 @@
 #include "module.h"
 #include <zlib.h>
 
+enum {
+    /* Limit chunk sizes to prevent unreasonable amounts of memory being used
+     * or truncating when converting to 32-bit types
+     */
+    DMG_LENGTHS_MAX = 64 * 1024 * 1024, /* 64 MB */
+    DMG_SECTORCOUNTS_MAX = DMG_LENGTHS_MAX / 512,
+};
+
 typedef struct BDRVDMGState {
     CoMutex lock;
     /* each chunk contains a certain number of sectors,
@@ -155,12 +163,26 @@ static int dmg_open(BlockDriverState *bs, int flags)
 		s->sectorcounts[i] = read_off(bs, offset);
 		offset += 8;
 
+                if (s->sectorcounts[i] > DMG_SECTORCOUNTS_MAX) {
+                    error_report("sector count %" PRIu64 " for chunk %u is "
+                                 "larger than max (%u)",
+                                 s->sectorcounts[i], i, DMG_SECTORCOUNTS_MAX);
+                    goto fail;
+                }
+
 		s->offsets[i] = last_in_offset+read_off(bs, offset);
 		offset += 8;
 
 		s->lengths[i] = read_off(bs, offset);
 		offset += 8;
 
+                if (s->lengths[i] > DMG_LENGTHS_MAX) {
+                    error_report("length %" PRIu64 " for chunk %u is larger "
+                                 "than max (%u)",
+                                 s->lengths[i], i, DMG_LENGTHS_MAX);
+                    goto fail;
+                }
+
 		if(s->lengths[i]>max_compressed_size)
 		    max_compressed_size = s->lengths[i];
 		if(s->sectorcounts[i]>max_sectors_per_chunk)
-- 
1.7.10.4

