From f9308839198aca5e68a65194f151a1de92398f54 Mon Sep 17 00:00:00 2001
From: Kevin Backhouse <kevinbackhouse@github.com>
Date: Tue, 20 Apr 2021 12:04:13 +0100
Subject: [PATCH] Better bounds checking in Jp2Image::encodeJp2Header()

---
 src/jp2image.cpp | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/src/jp2image.cpp b/src/jp2image.cpp
index 0825d99..f9be021 100644
--- a/src/jp2image.cpp
+++ b/src/jp2image.cpp
@@ -650,6 +650,7 @@ namespace Exiv2
 #ifdef DEBUG
                 std::cout << "Jp2Image::encodeJp2Header subbox: "<< toAscii(subBox.type) << " length = " << subBox.length << std::endl;
 #endif
+		enforce(subBox.length <= length - count, Exiv2::kerCorruptedMetadata);
                 count        += subBox.length;
                 newBox.type   = subBox.type;
             } else {
@@ -658,12 +659,13 @@ namespace Exiv2
                 count = length;
             }
 
-            int32_t newlen = subBox.length;
+            uint32_t newlen = subBox.length;
             if ( newBox.type == kJp2BoxTypeColorHeader ) {
                 bWroteColor = true ;
                 if ( ! iccProfileDefined() ) {
                     const char* pad   = "\x01\x00\x00\x00\x00\x00\x10\x00\x00\x05\x1cuuid";
                     uint32_t    psize = 15;
+		    enforce(newlen <= output.size_ - outlen, Exiv2::kerCorruptedMetadata);
                     ul2Data((byte*)&newBox.length,psize      ,bigEndian);
                     ul2Data((byte*)&newBox.type  ,newBox.type,bigEndian);
                     ::memcpy(output.pData_+outlen                     ,&newBox            ,sizeof(newBox));
@@ -672,6 +674,7 @@ namespace Exiv2
                 } else {
                     const char* pad   = "\0x02\x00\x00";
                     uint32_t    psize = 3;
+		    enforce(newlen <= output.size_ - outlen, Exiv2::kerCorruptedMetadata);
                     ul2Data((byte*)&newBox.length,psize+iccProfile_.size_,bigEndian);
                     ul2Data((byte*)&newBox.type,newBox.type,bigEndian);
                     ::memcpy(output.pData_+outlen                     ,&newBox            ,sizeof(newBox)  );
@@ -680,6 +683,7 @@ namespace Exiv2
                     newlen = psize + iccProfile_.size_;
                 }
             } else {
+		enforce(newlen <= output.size_ - outlen, Exiv2::kerCorruptedMetadata);
                 ::memcpy(output.pData_+outlen,boxBuf.pData_+inlen,subBox.length);
             }
 
-- 
2.23.0

