From 3875619331d2c7c74a80d34665cbc06e6ed4359a Mon Sep 17 00:00:00 2001
From: Dirk Lemstra <dirk@lemstra.org>
Date: Fri, 6 Mar 2026 13:14:19 +0100
Subject: [PATCH] Added extra check to prevent overflow that could result in a
 heap over-write
 (https://github.com/ImageMagick/ImageMagick/security/advisories/GHSA-qmw5-2p58-xvrc)

---
 coders/png.c | 11 +++++------
 1 file changed, 5 insertions(+), 6 deletions(-)

Index: ImageMagick-6.8.8-1/coders/png.c
===================================================================
--- ImageMagick-6.8.8-1.orig/coders/png.c
+++ ImageMagick-6.8.8-1/coders/png.c
@@ -7863,7 +7863,8 @@ ModuleExport void UnregisterPNGImage(voi
 static void
 Magick_png_write_raw_profile(const ImageInfo *image_info,png_struct *ping,
    png_info *ping_info, unsigned char *profile_type, unsigned char
-   *profile_description, unsigned char *profile_data, png_uint_32 length)
+   *profile_description, unsigned char *profile_data, png_uint_32 length,
+   ExceptionInfo *exception)
 {
    png_textp
      text;
@@ -7904,6 +7905,12 @@ Magick_png_write_raw_profile(const Image
    description_length=(png_uint_32) strlen((const char *) profile_description);
    allocated_length=(png_uint_32) (length*2 + (length >> 5) + 20
       + description_length);
+   if ((allocated_length < length) || (length >= (PNG_UINT_31_MAX / 2)))
+     {
+       (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
+         "maximum profile length exceeded","`%s'",image_info->filename);
+       return;
+     }
 #if PNG_LIBPNG_VER >= 10400
    text[0].text=(png_charp) png_malloc(ping,
       (png_alloc_size_t) allocated_length);
@@ -10788,7 +10795,8 @@ static MagickBooleanType WriteOnePNGImag
                   Magick_png_write_raw_profile(image_info,ping,ping_info,
                     (unsigned char *) name,(unsigned char *) name,
                     GetStringInfoDatum(profile),
-                    (png_uint_32) GetStringInfoLength(profile));
+                    (png_uint_32) GetStringInfoLength(profile),
+                    &image->exception);
                   ping_have_iCCP = MagickTrue;
                 }
           }
