From fcb42570519f8cf924b0302b09062a60aa565fbe Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Dan=20=C4=8Cerm=C3=A1k?= <dan.cermak@cgc-instruments.com>
Date: Tue, 9 Jan 2018 21:18:36 +0100
Subject: [PATCH 1/2] Add check for DataBuf.size_ in Jp2Image::readMetadata()

When parsing a subBox that is a ColorHeader, a length is extracted
from the input file and fed directly into DataBuf() (which calls
malloc). A crafted input file can provide arbitrarily (up to
max(uint32_t)-8) large values and result in excessive memory
allocation.

This commit adds a check for the new size of DataBuf so that it is not
larger than the remaining size of the file.

This fixes #202 aka CVE-2018-4868
---
 src/jp2image.cpp | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/src/jp2image.cpp b/src/jp2image.cpp
index 20727844d..8dd6c9c1b 100644
--- a/src/jp2image.cpp
+++ b/src/jp2image.cpp
@@ -268,7 +268,12 @@ namespace Exiv2
 #endif
 
                             const long pad = 3 ; // 3 padding bytes 2 0 0
-                            DataBuf data(Safe::add(subBox.length, static_cast<uint32_t>(8)));
+			    const size_t data_length = Safe::add(subBox.length, static_cast<uint32_t>(8));
+			    // data_length makes no sense if it is larger than the rest of the file
+			    if (data_length > io_->size() - io_->tell()) {
+				throw Error(58);
+			    }
+                            DataBuf data(data_length);
                             io_->read(data.pData_,data.size_);
                             const long    iccLength = getULong(data.pData_+pad, bigEndian);
                             // subtracting pad from data.size_ is safe:

From 72de0f96f35d05ba68b28f4fa82f51a1df2778ca Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Dan=20=C4=8Cerm=C3=A1k?= <dan.cermak@cgc-instruments.com>
Date: Tue, 9 Jan 2018 21:27:20 +0100
Subject: [PATCH 2/2] Added reproducer for CVE-2018-4868 to the test suite

---
 tests/bugfixes/github/test_CVE_2018_4868.py |  18 ++++++++++++++++++
 1 files changed, 18 insertions(+)
 create mode 100644 tests/bugfixes/github/test_CVE_2018_4868.py

diff --git a/tests/bugfixes/github/test_CVE_2018_4868.py b/tests/bugfixes/github/test_CVE_2018_4868.py
new file mode 100644
index 000000000..434eec6b4
--- /dev/null
+++ b/tests/bugfixes/github/test_CVE_2018_4868.py
@@ -0,0 +1,18 @@
+# -*- coding: utf-8 -*-
+
+import system_tests
+
+
+class TestCvePoC(system_tests.Case):
+
+    url = "https://github.com/Exiv2/exiv2/issues/202"
+    cve_url = "http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-4868"
+    found_by = ["afl", "topsecLab", "xcainiao"]
+
+    filename = "{data_path}/exiv2-memorymmap-error"
+    commands = ["{exiv2} " + filename]
+    stdout = [""]
+    stderr = ["""{exiv2_exception_msg} """ + filename + """:
+{error_58_message}
+"""]
+    retval = [1]
