From 4c0d757d6de529e8dda6bb6ca08369d5f9bffdb3 Mon Sep 17 00:00:00 2001
From: Steve Lhomme <slhomme@matroska.org>
Date: Wed, 1 Nov 2023 09:02:36 +0100
Subject: [PATCH] MemIOCallback: fix buffer overflow when reading too much data

If the addition of 2 positive values is smaller than one of the values then we
have an overflowing addition.

In this case that means we are trying to read more data that is actually in
our buffer. So we can use the same mechanism as reading too much data.

(cherry picked from commit 4d577f5c3e267b2988d56dafebc82dedb4c45506)
Signed-off-by: Steve Lhomme <slhomme@matroska.org>
---
 src/MemIOCallback.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

--- libebml-1.4.4.orig/src/MemIOCallback.cpp
+++ libebml-1.4.4/src/MemIOCallback.cpp
@@ -68,7 +68,8 @@ uint32 MemIOCallback::read(void *Buffer,
   if (Buffer == nullptr || Size < 1)
     return 0;
   //If the size is larger than than the amount left in the buffer
-  if (Size + dataBufferPos > dataBufferTotalSize) {
+  if (Size + dataBufferPos < Size || // overflow, reading too much
+      Size + dataBufferPos > dataBufferTotalSize) {
     //We will only return the remaining data
     memcpy(Buffer, dataBuffer + dataBufferPos, dataBufferTotalSize - dataBufferPos);
     uint64 oldDataPos = dataBufferPos;
