From: Stefan Hajnoczi <stefanha@redhat.com>
Date: Wed, 26 Mar 2014 13:05:28 +0100
Subject: block/cloop: refuse images with bogus offsets (CVE-2014-0144)

The offsets[] array allows efficient seeking and tells us the maximum
compressed data size.  If the offsets are bogus the maximum compressed
data size will be unrealistic.

This could cause g_malloc() to abort and bogus offsets mean the image is
broken anyway.  Therefore we should refuse such images.

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 f56b9bc3ae20fc93815b34aa022be919941406ce)

Conflicts:
	tests/qemu-iotests/075
	tests/qemu-iotests/075.out

diff --git a/block/cloop.c b/block/cloop.c
index 10f06b9..49e65e4 100644
--- a/block/cloop.c
+++ b/block/cloop.c
@@ -118,12 +118,34 @@ static int cloop_open(BlockDriverState *bs, int flags)
         goto cloop_close;
     }
     for(i=0;i<s->n_blocks;i++) {
+        uint64_t size;
+
         s->offsets[i] = be64_to_cpu(s->offsets[i]);
-        if (i > 0) {
-            uint32_t size = s->offsets[i] - s->offsets[i - 1];
-            if (size > max_compressed_block_size) {
-                max_compressed_block_size = size;
-            }
+        if (i == 0) {
+            continue;
+        }
+
+        if (s->offsets[i] < s->offsets[i - 1]) {
+            fprintf(stderr, "offsets not monotonically increasing at "
+                       "index %u, image file is corrupt\n", i);
+            goto cloop_close;
+        }
+
+        size = s->offsets[i] - s->offsets[i - 1];
+
+        /* Compressed blocks should be smaller than the uncompressed block size
+         * but maybe compression performed poorly so the compressed block is
+         * actually bigger.  Clamp down on unrealistic values to prevent
+         * ridiculous s->compressed_block allocation.
+         */
+        if (size > 2 * MAX_BLOCK_SIZE) {
+            fprintf(stderr, "invalid compressed block size at index %u, "
+                       "image file is corrupt\n", i);
+            goto cloop_close;
+        }
+
+        if (size > max_compressed_block_size) {
+            max_compressed_block_size = size;
         }
     }
 
-- 
1.7.10.4

