From 515837c7319a1e225191962c5e521fc4fc2c2508 Mon Sep 17 00:00:00 2001
From: Kevin Wolf <kwolf@redhat.com>
Date: Tue, 3 Jun 2014 10:01:32 +0200
Subject: [PATCH 13/26] qcow1: Validate L2 table size (CVE-2014-0222)

RH-Author: Kevin Wolf <kwolf@redhat.com>
Message-id: <1401789694-14289-5-git-send-email-kwolf@redhat.com>
Patchwork-id: 59110
O-Subject: [RHEL-6.6/6.5.z qemu-kvm PATCH 4/6] qcow1: Validate L2 table size (CVE-2014-0222)
Bugzilla: 1097228
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=1097228

Too large L2 table sizes cause unbounded allocations. Images actually
created by qemu-img only have 512 byte or 4k L2 tables.

To keep things consistent with cluster sizes, allow ranges between 512
bytes and 64k (in fact, down to 1 entry = 8 bytes is technically
working, but L2 table sizes smaller than a cluster don't make a lot of
sense).

This also means that the number of bytes on the virtual disk that are
described by the same L2 table is limited to at most 8k * 64k or 2^29,
preventively avoiding any integer overflows.

Cc: qemu-stable@nongnu.org
Signed-off-by: Kevin Wolf <kwolf@redhat.com>
Reviewed-by: Benoit Canet <benoit@irqsave.net>
(cherry picked from commit 42eb58179b3b215bb507da3262b682b8a2ec10b5)

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

Replaced error_setg() by qerror_report() for RHEL 6.

Signed-off-by: Kevin Wolf <kwolf@redhat.com>
---
 block/qcow.c | 9 +++++++++
 1 file changed, 9 insertions(+)

Signed-off-by: Miroslav Rezanina <mrezanin@redhat.com>
---
 block/qcow.c |    9 +++++++++
 1 files changed, 9 insertions(+), 0 deletions(-)

diff --git a/block/qcow.c b/block/qcow.c
index 5a2101e..9c372ff 100644
--- a/block/qcow.c
+++ b/block/qcow.c
@@ -136,6 +136,15 @@ static int qcow_open(BlockDriverState *bs, int flags)
         goto fail;
     }
 
+    /* l2_bits specifies number of entries; storing a uint64_t in each entry,
+     * so bytes = num_entries << 3. */
+    if (header.l2_bits < 9 - 3 || header.l2_bits > 16 - 3) {
+        qerror_report(QERR_GENERIC_ERROR,
+                      "L2 table size must be between 512 and 64k");
+        ret = -EINVAL;
+        goto fail;
+    }
+
     if (header.crypt_method > QCOW_CRYPT_AES) {
         ret = -EINVAL;
         goto fail;
-- 
1.7.1

