From 1061db7f80fdc9ef572ac60b55f408f7bab6e1b0 Mon Sep 17 00:00:00 2001
From: Cristy <urban-warrior@imagemagick.org>
Date: Mon, 15 May 2023 14:22:11 -0400
Subject: [PATCH] carefully crafted image files (TIM2, JPEG) no longer overflow
 buffer nor use heap after free (thanks to Juzhi Lu, Zhen Zhou, Likang Luo of
 NSFOCUS Security Team)

Origin: https://github.com/ImageMagick/ImageMagick/commit/1061db7f80fdc9ef572ac60b55f408f7bab6e1b0

---
 MagickCore/profile.c | 5 +++--
 coders/tim2.c        | 4 +++-
 2 files changed, 6 insertions(+), 3 deletions(-)

diff --git a/MagickCore/profile.c b/MagickCore/profile.c
index 57909092d2..382583a524 100644
--- a/MagickCore/profile.c
+++ b/MagickCore/profile.c
@@ -2458,11 +2458,12 @@ static void ReplaceXmpValue(StringInfo *profile,size_t start,size_t end,
   if (new_length > length)
     SetStringInfoLength(profile,new_length);
   datum=(char *) GetStringInfoDatum(profile);
-  memmove(datum+start+value_length,datum+end,length-end);
-  memcpy(datum+start,value,value_length);
+  (void) memmove(datum+start+value_length,datum+end,length-end);
+  (void) memcpy(datum+start,value,value_length);
   if (new_length < length)
     {
       SetStringInfoLength(profile,new_length);
+      datum=(char *) GetStringInfoDatum(profile);
       *(datum+new_length)='\0';
     }
 }
diff --git a/coders/tim2.c b/coders/tim2.c
index 0445985dcc..d30afaf05d 100644
--- a/coders/tim2.c
+++ b/coders/tim2.c
@@ -517,10 +517,12 @@ static MagickBooleanType ReadTIM2ImageData(const ImageInfo *image_info,
     /*
       * ### Read CLUT Data ###
       */
-    clut_data=(unsigned char *) AcquireQuantumMemory(1,header->clut_size);
+    clut_data=(unsigned char *) AcquireQuantumMemory(2,
+      MagickMax(header->clut_size,image->colors));
     if (clut_data == (unsigned char *) NULL)
       ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
         image_info->filename);
+    (void) memset(clut_data,0,2*MagickMax(header->clut_size,image->colors));
     count=ReadBlob(image,header->clut_size,clut_data);
     if (count != (ssize_t) (header->clut_size))
       {
