From 04964bec430d61e89251e15b4cbb8400e4ea4af9 Mon Sep 17 00:00:00 2001
From: Dale Curtis <dalecurtis@chromium.org>
Date: Fri, 2 Feb 2024 20:49:44 +0000
Subject: [PATCH] [mov] Avoid OOM for invalid STCO / CO64 constructions.

The `entries` value is read directly from the stream and used to
allocate memory. This change clamps `entries` to however many are
possible in the remaining atom or file size (whichever is smallest).

Fixes https://crbug.com/1429357

Signed-off-by: Dale Curtis <dalecurtis@chromium.org>
---
 libavformat/mov.c | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/libavformat/mov.c b/libavformat/mov.c
index af95e1f662..9f012b24ae 100644
--- a/libavformat/mov.c
+++ b/libavformat/mov.c
@@ -2237,6 +2237,13 @@ static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom)
         av_log(c->fc, AV_LOG_WARNING, "Ignoring duplicated STCO atom\n");
         return 0;
     }
+
+    // Clamp allocation size for `chunk_offsets` -- don't throw an error for an
+    // invalid count since the EOF path doesn't throw either.
+    entries =
+        FFMIN(entries, FFMIN(atom.size - 8, avio_size(pb) - avio_tell(pb)) /
+                           (atom.type == MKTAG('s', 't', 'c', 'o') ? 4 : 8));
+
     av_free(sc->chunk_offsets);
     sc->chunk_count = 0;
     sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets));
-- 
2.43.0.594.gd9cf4e227d-goog

