Project: imagemagick (imagemagick/imagemagick), language: c++
Vulnerability instance: imagemagick.cve-2017-10995
Sanitizer: address

================= Bug Report (1/1) ==================
## Source: GitHub Issue
## URL: https://github.com/ImageMagick/ImageMagick/issues/538
## Description:
Issue: ImageMagick/ImageMagick#538
Title: imagemagick identify&convert heap-buffer-overflow 
State: closed
Created by: zyy89
Created at: 2017-07-04 16:32:12+00:00
Labels: bug

Issue Body:
ImageMagick-7.0.6-0
```
  ~$identify $FILE or convert $FILE
```
build instructions:
```
  ~$ sudo apt-get install imagemagick libmagick++-dev
  ~$ CC="gcc" CFLAGS="-fsanitize=address" ./configure 
  ~$ make
  ~$ make install
```
when identify or convert MNG file, imagemagick will cause a heap buffer overflow
> =================================================================
==6483==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000008c5a at pc 0x7fee316dfb7d bp 0x7ffeba5682b0 sp 0x7ffeba5682a0
READ of size 1 at 0x602000008c5a thread T0
    #0 0x7fee316dfb7c in mng_get_long coders/png.c:1636
    #1 0x7fee316f08ad in ReadOneMNGImage coders/png.c:5741
    #2 0x7fee316fae29 in ReadMNGImage coders/png.c:7497
    #3 0x7fee31272c4f in ReadImage MagickCore/constitute.c:497
    #4 0x7fee314bee06 in ReadStream MagickCore/stream.c:1045
    #5 0x7fee3127217c in PingImage MagickCore/constitute.c:226
    #6 0x7fee312725a9 in PingImages MagickCore/constitute.c:327
    #7 0x7fee30c32a2a in IdentifyImageCommand MagickWand/identify.c:319
    #8 0x7fee30c89c7a in MagickCommandGenesis MagickWand/mogrify.c:183
    #9 0x40169a in MagickMain utilities/magick.c:149
    #10 0x4017be in main utilities/magick.c:180
    #11 0x7fee3050282f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
    #12 0x4012c8 in _start (/home/sf/ImageMagick-7.0.6-0/build-gcc/bin/magick+0x4012c8)


The vulnerability is caused when identify MNG image, which happens  in function mng_get_long (coders/png.c:1636) which is called by line 5741 at coders/png.c.  
Here is the critical code of mng_get_long and its call code:
```
static long mng_get_long(unsigned char *p)
{
  return((long) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]));
}
```
```
5728	                        if (change_delay == 2)
5729	                          default_frame_delay=frame_delay;
5730	
5731	                        p+=4;
5732	
5733	                        if (logging != MagickFalse)
5734	                          (void) LogMagickEvent(CoderEvent,GetMagickModule(),
(gdb) 
5735	                            "    Framing_delay=%.20g",(double) frame_delay);
5736	                      }
5737	
5738	                    if (change_timeout)
5739	                      {
5740	                        frame_timeout=1UL*image->ticks_per_second*
5741	                          mng_get_long(p);
5742	
5743	                        if (mng_info->ticks_per_second != 0)
```
 It is caused by heap buffer overflow, which is caused by a read operation without overflow check.
The p buffer is pointer to chunk, its buffer data and  length are read from input file,
```
        p=NULL;
        chunk=(unsigned char *) NULL;

        if (length != 0)
          {
            chunk=(unsigned char *) AcquireQuantumMemory(length,
             sizeof(*chunk));

            if (chunk == (unsigned char *) NULL)
              ThrowReaderException(ResourceLimitError,
                "MemoryAllocationFailed");

            for (i=0; i < (ssize_t) length; i++)
              chunk[i]=(unsigned char) ReadBlobByte(image);

            p=chunk;
          }
``` 
When setting proper length and repeat value, it is possible to disclosing some critical data, such as heap chunk data and even other applications’ private data. 

Testcase: https://github.com/zyy89/pocs/blob/master/imagemagick-heap-buffer-overflow-1


Comments:
Comment by mikayla-grace on 2017-07-06 16:20:33+00:00:
Thanks for the problem report.  We can reproduce it and will have a patch to fix it in GIT master branch @ https://github.com/ImageMagick/ImageMagick later today.  The patch will be available in the beta releases of ImageMagick @ http://www.imagemagick.org/download/beta/ by sometime tomorrow. 


---

Comment by bastien-roucaries on 2017-07-08 21:56:33+00:00:
Does it affect v6 ?

---

Comment by mikayla-grace on 2017-07-08 22:19:53+00:00:
Yes.

---

Comment by bastien-roucaries on 2017-07-09 14:06:23+00:00:
Did you jhave a commit for v6 ?

---

Comment by bastien-roucaries on 2017-07-15 09:43:34+00:00:
Ping ?

---

Comment by dlemstra on 2017-07-15 10:06:06+00:00:
280e592 is 7 and  7a9a910 is 6.




---

Comment by bastien-roucaries on 2017-07-15 10:08:07+00:00:
Will want to be ping for correct fix (glenn one). Thank you nevertheless

---

Comment by glennrp on 2017-07-15 14:34:49+00:00:
Final fix for IM7 is commit 6a4f9c1feb7153807f22435ac6853956a1648707


---

Comment by bastien-roucaries on 2017-07-19 22:36:03+00:00:
And for v6 ? Does we need to apply previous commit ?

---

Comment by glennrp on 2017-07-19 22:47:50+00:00:
I believe v6 was not vulnerable to this particular problem.  It was fixed in V6 around version 6.9.5-3.

---

Comment by bastien-roucaries on 2017-07-21 15:09:18+00:00:
glenn instead of if (change_clipping && ((p-chunk) < (ssize_t) (length-16))) v6 has if (change_clipping && ((p-chunk) < (ssize_t) (length-17)))

is it normal ?

---

Comment by glennrp on 2017-07-21 16:06:32+00:00:
It should be 16.

---

Comment by glennrp on 2017-07-21 16:31:04+00:00:
I fixed the 17 -> 16 thing.  It wasn't a security problem but could have caused certain FRAM chunks to be rejected incorrectly.  See commit 1fdc09d

---

Comment by carnil on 2017-07-29 03:14:06+00:00:
@glennrp: could you help identify the commit in v6, around 6.9.5-3 which fixes this issue?

---

Comment by glennrp on 2017-07-29 06:43:45+00:00:
 IM6 commits 24430226caf7eb468b4180f2883b2563e8cc1b23 and  1fdc09dc8f9522f07f5f501fe8453765ad82556c

---

Comment by carnil on 2017-07-29 16:22:48+00:00:
@glennrp: thank you!

Commit References:
6a4f9c1feb7153807f22435ac6853956a1648707
1fdc09dc8f9522f07f5f501fe8453765ad82556c
24430226caf7eb468b4180f2883b2563e8cc1b23

Build script:
#!/bin/bash -eu
# Minimized build script with only core build commands
set -eu
./configure --prefix="$WORK" --disable-shared --disable-docs
make "-j$(nproc)"
make install -j$(nproc)

Dockerfile:
FROM hwiwonlee/secb.base:latest
RUN apt-get update && apt-get install -y make autoconf automake libtool
RUN git clone https://github.com/imagemagick/imagemagick imagemagick
RUN git -C imagemagick checkout 9caa8b0c4269163def2ce0fa6ff1754ec0c234d2
WORKDIR $SRC/imagemagick
COPY build.sh $SRC/

Additional files:
filename: crop_fuzzer.cc
content: #include <cstdint>

#include <Magick++/Blob.h>
#include <Magick++/Image.h>

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  uint16_t Width;
  uint16_t Height;
  if (Size < (sizeof(Width) + sizeof(Height))) {
    return 0;
  }
  Width = *reinterpret_cast<const uint16_t *>(Data);
  Height = *reinterpret_cast<const uint16_t *>(Data + sizeof(Width));
  const Magick::Blob blob(Data + sizeof(Width) + sizeof(Height),
                          Size - (sizeof(Width) + sizeof(Height)));
  Magick::Image image;
  try {
    image.read(blob);
  } catch (Magick::Exception &e) {
    return 0;
  }
  image.crop(Magick::Geometry(Width, Height));
  return 0;
}

filename: encoder_fuzzer.cc
content: #include <cstdint>

#include <Magick++/Blob.h>
#include <Magick++/Image.h>

#define FUZZ_ENCODER_STRING_LITERAL(name) #name
#define FUZZ_ENCODER FUZZ_ENCODER_STRING_LITERAL(FUZZ_IMAGEMAGICK_ENCODER)

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  const Magick::Blob blob(Data, Size);
  Magick::Image image;
  try {
    image.read(blob);
  } catch (Magick::Exception &e) {
    return 0;
  }

  Magick::Blob outBlob;
  try {
    image.write(&outBlob, FUZZ_ENCODER);
  } catch (Magick::Exception &e) {
  }
  return 0;
}

filename: encoder_list.cc
content: #include <iostream>

#include <Magick++/Blob.h>
#include <Magick++/Image.h>

extern "C" int main() {
  size_t nFormats;
  Magick::ExceptionInfo ex;
  const Magick::MagickInfo **formats = GetMagickInfoList("*", &nFormats, &ex);

  for (size_t i = 0; i < nFormats; i++) {
    const Magick::MagickInfo *format = formats[i];
    if (format->encoder && format->name) {
      std::cout << format->name << std::endl;
    }
  }
}

filename: enhance_fuzzer.cc
content: #include <cstdint>

#include <Magick++/Blob.h>
#include <Magick++/Image.h>

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  const Magick::Blob blob(Data, Size);
  Magick::Image image;
  try {
    image.read(blob);
    image.enhance();
  } catch (Magick::Exception &e) {
    return 0;
  }
  return 0;
}

filename: huffman_decode_fuzzer.cc
content: #include <cstdint>

#include <Magick++/Blob.h>
#include <Magick++/Image.h>

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  const Magick::Blob blob(Data, Size);
  Magick::Image image;
  try {
    image.read(blob);
  } catch (Magick::Exception &e) {
    return 0;
  }
  Magick::ExceptionInfo ex;
  auto res = HuffmanDecodeImage(image.image(), &ex);
  return 0;
}

filename: rotate_fuzzer.cc
content: #include <cstdint>

#include <Magick++/Blob.h>
#include <Magick++/Image.h>

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  if (Size < sizeof(double)) {
    return 0;
  }
  double Degrees = *reinterpret_cast<const double *>(Data);
  if (!isfinite(Degrees)) {
    return 0;
  }
  const Magick::Blob blob(Data + sizeof(Degrees), Size - sizeof(Degrees));
  Magick::Image image;
  try {
    image.read(blob);
  } catch (Magick::Exception &e) {
    return 0;
  }
  image.rotate(Degrees);
  return 0;
}