From 772a02d9d434495078bc7339809999beb3a60f15 Mon Sep 17 00:00:00 2001
From: Stefan Hajnoczi <stefanha@redhat.com>
Date: Tue, 25 Mar 2014 11:45:36 +0100
Subject: [PATCH 18/48] block/cloop: prevent offsets_size integer overflow (CVE-2014-0143)

RH-Author: Kevin Wolf <kwolf@redhat.com>
Message-id: <1395744364-16049-18-git-send-email-kwolf@redhat.com>
Patchwork-id: n/a
O-Subject: [virt-devel] [EMBARGOED RHEL-6.6/6.5.z qemu-kvm PATCH v2 17/45]
           block/cloop: prevent offsets_size integer overflow (CVE-2014-0143)
Bugzilla: 1079319
RH-Acked-by: Max Reitz <mreitz@redhat.com>
RH-Acked-by: Stefan Hajnoczi <stefanha@redhat.com>
RH-Acked-by: Jeff Cody <jcody@redhat.com>

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

The following integer overflow in offsets_size can lead to out-of-bounds
memory stores when n_blocks has a huge value:

    uint32_t n_blocks, offsets_size;
    [...]
    ret = bdrv_pread(bs->file, 128 + 4, &s->n_blocks, 4);
    [...]
    s->n_blocks = be32_to_cpu(s->n_blocks);

    /* read offsets */
    offsets_size = s->n_blocks * sizeof(uint64_t);
    s->offsets = g_malloc(offsets_size);

    [...]

    for(i=0;i<s->n_blocks;i++) {
        s->offsets[i] = be64_to_cpu(s->offsets[i]);

offsets_size can be smaller than n_blocks due to integer overflow.
Therefore s->offsets[] is too small when the for loop byteswaps offsets.

This patch refuses to open files if offsets_size would overflow.

Note that changing the type of offsets_size is not a fix since 32-bit
hosts still only have 32-bit size_t.

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

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

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

diff --git a/block/cloop.c b/block/cloop.c
index 9caf7f0..ff1587c 100644
--- a/block/cloop.c
+++ b/block/cloop.c
@@ -91,6 +91,11 @@ static int cloop_open(BlockDriverState *bs, int flags)
     s->n_blocks = be32_to_cpu(s->n_blocks);
 
     /* read offsets */
+    if (s->n_blocks > UINT32_MAX / sizeof(uint64_t)) {
+        /* Prevent integer overflow */
+        qerror_report(QERR_GENERIC_ERROR, "n_blocks too large");
+        return -EINVAL;
+    }
     offsets_size = s->n_blocks * sizeof(uint64_t);
     s->offsets = g_malloc(offsets_size);
     if (bdrv_pread(bs->file, 128 + 4 + 4, s->offsets, offsets_size) <
-- 
1.7.1

