From ef6298177a8390c01f5084ba89a808015a0b9473 Mon Sep 17 00:00:00 2001
From: Gerald Squelart <gsquelart@mozilla.com>
Date: Thu, 22 Oct 2015 10:00:12 +0200
Subject: [PATCH] Bug 1204580 - Check box ranges for overflow - r=rillian, a=al

---
 media/libstagefright/binding/Box.cpp | 21 +++++++++++++++++++--
 1 file changed, 19 insertions(+), 2 deletions(-)

diff --git a/media/libstagefright/binding/Box.cpp b/media/libstagefright/binding/Box.cpp
index 71c79ed..2558be0 100644
--- a/media/libstagefright/binding/Box.cpp
+++ b/media/libstagefright/binding/Box.cpp
@@ -40,6 +40,11 @@ Box::Box(BoxContext* aContext, uint64_t aOffset, const Box* aParent)
   : mContext(aContext), mParent(aParent)
 {
   uint8_t header[8];
+
+  if (aOffset > INT64_MAX - sizeof(header)) {
+    return;
+  }
+
   MediaByteRange headerRange(aOffset, aOffset + sizeof(header));
   if (mParent && !mParent->mRange.Contains(headerRange)) {
     return;
@@ -67,11 +72,14 @@ Box::Box(BoxContext* aContext, uint64_t aOffset, const Box* aParent)
   uint64_t size = BigEndian::readUint32(header);
   if (size == 1) {
     uint8_t bigLength[8];
+    if (aOffset > INT64_MAX - sizeof(header) - sizeof(bigLength)) {
+      return;
+    }
     MediaByteRange bigLengthRange(headerRange.mEnd,
                                   headerRange.mEnd + sizeof(bigLength));
     if ((mParent && !mParent->mRange.Contains(bigLengthRange)) ||
         !byteRange->Contains(bigLengthRange) ||
-        !mContext->mSource->CachedReadAt(aOffset, bigLength,
+        !mContext->mSource->CachedReadAt(aOffset + sizeof(header), bigLength,
                                          sizeof(bigLength), &bytes) ||
         bytes != sizeof(bigLength)) {
       return;
@@ -82,10 +90,19 @@ Box::Box(BoxContext* aContext, uint64_t aOffset, const Box* aParent)
     mBodyOffset = headerRange.mEnd;
   }
 
+  if (size > INT64_MAX) {
+    return;
+  }
+  int64_t end = static_cast<int64_t>(aOffset) + static_cast<int64_t>(size);
+  if (end < static_cast<int64_t>(aOffset)) {
+    // Overflowed.
+    return;
+  }
+
   mType = BigEndian::readUint32(&header[4]);
   mChildOffset = mBodyOffset + BoxOffset(mType);
 
-  MediaByteRange boxRange(aOffset, aOffset + size);
+  MediaByteRange boxRange(aOffset, end);
   if (mChildOffset > boxRange.mEnd ||
       (mParent && !mParent->mRange.Contains(boxRange)) ||
       !byteRange->Contains(boxRange)) {
-- 
2.5.0

