From 447e05bbd5a4867abea6e4a91f1f0b2ca20fdbb2 Mon Sep 17 00:00:00 2001
From: Kevin Wolf <kwolf@redhat.com>
Date: Tue, 25 Mar 2014 11:45:46 +0100
Subject: [PATCH 28/48] bochs: Check catalog_size header field (CVE-2014-0143)

RH-Author: Kevin Wolf <kwolf@redhat.com>
Message-id: <1395744364-16049-28-git-send-email-kwolf@redhat.com>
Patchwork-id: n/a
O-Subject: [EMBARGOED RHEL-6.6/6.5.z qemu-kvm PATCH v2 27/45]
           bochs: Check catalog_size header field (CVE-2014-0143)
Bugzilla: 1079319
RH-Acked-by: Max Reitz <mreitz@redhat.com>
RH-Acked-by: Stefan Hajnoczi <stefanha@redhat.com>
RH-Acked-by: Laszlo Ersek <lersek@redhat.com>

Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=1079319
Upstream status: Embargoed

It should neither become negative nor allow unbounded memory
allocations. This fixes aborts in g_malloc() and an s->catalog_bitmap
buffer overflow on big endian hosts.

Signed-off-by: Kevin Wolf <kwolf@redhat.com>
Reviewed-by: Stefan Hajnoczi <stefanha@redhat.com>

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

Signed-off-by: Kevin Wolf <kwolf@redhat.com>
---
 block/bochs.c |   14 ++++++++++++++
 1 files changed, 14 insertions(+), 0 deletions(-)

diff --git a/block/bochs.c b/block/bochs.c
index c6f2cd6..36d9c47 100644
--- a/block/bochs.c
+++ b/block/bochs.c
@@ -121,7 +121,14 @@ static int bochs_open(BlockDriverState *bs, int flags)
         bs->total_sectors = le64_to_cpu(bochs.extra.redolog.disk) / 512;
     }
 
+    /* Limit to 1M entries to avoid unbounded allocation. This is what is
+     * needed for the largest image that bximage can create (~8 TB). */
     s->catalog_size = le32_to_cpu(bochs.catalog);
+    if (s->catalog_size > 0x100000) {
+        qerror_report(QERR_GENERIC_ERROR, "Catalog size is too large");
+        return -EFBIG;
+    }
+
     s->catalog_bitmap = g_malloc(s->catalog_size * 4);
 
     ret = bdrv_pread(bs->file, le32_to_cpu(bochs.header), s->catalog_bitmap,
@@ -140,6 +147,13 @@ static int bochs_open(BlockDriverState *bs, int flags)
 
     s->extent_size = le32_to_cpu(bochs.extent);
 
+    if (s->catalog_size < bs->total_sectors / s->extent_size) {
+        qerror_report(QERR_GENERIC_ERROR,
+                      "Catalog size is too small for this disk size");
+        ret = -EINVAL;
+        goto fail;
+    }
+
     qemu_co_mutex_init(&s->lock);
     return 0;
 
-- 
1.7.1

