Advisory

GHSA-qh3h-j545-h8c9

Details, part 2 of 2. The advisory

Details

The constant 4 was likely chosen based on the character count of typical format specifiers like %03d (total of 4 characters: %, 0, 3, d). However, in reality, there are formats with only 2 characters like %d, and formats with longer width specifications (e.g., %010d), so this uniform constant-based correction is inconsistent with actual template structures.

As a result, when the correction value becomes excessive, offset exceeds the relative position p - format within the template, generating a negative index. This static and template-independent design of the correction processing is the root cause of this vulnerability.

This causes vsnprintf() to write outside the stack buffer range, which is detected by AddressSanitizer as a stack-buffer-overflow.

Proposed Fix

In MagickCore/image.c, within the InterpretImageFilename() function:

MagickExport size_t InterpretImageFilename(const ImageInfo *image_info,
  Image *image,const char *format,int value,char *filename,
  ExceptionInfo *exception)
{
...
  /*--------Changed--------*/
  ssize_t
    field_width,
    offset,
    written; // Added
  /*--------Changed--------*/
...
  for (p=strchr(format,'%'); p != (char *) NULL; p=strchr(p+1,'%'))
  {
    q=(char *) p+1;
    if (*q == '%')
      {
        p=q+1;
        continue;
      }
    field_width=0;
    if (*q == '0')
      field_width=(ssize_t) strtol(q,&q,10);
    switch (*q)
    {
      case 'd':
      case 'o':
      case 'x':
      {
        q++;
        c=(*q);
        *q='\0';
        written = FormatLocaleString(filename+(p-format-offset),(size_t)
          (MagickPathExtent-(p-format-offset)),p,value);
        /*--------Changed--------*/
        if (written <= 0 || written > (MagickPathExtent - (p - format - offset)))
          return 0;
        offset += (ssize_t)((q - p) - written);
        /*--------Changed--------*/
        *q=c;
        (void) ConcatenateMagickString(filename,q,MagickPathExtent);
        canonical=MagickTrue;
        if (*(q-1) != '%')
          break;
        p++;
        break;
      }
      case '[':
      {
        ...
      }
      default:
        break;
    }
  }
  • By updating offset based on the difference between template description length (q - p) and the number of output bytes written, buffer position consistency is maintained.
  • Correction is performed according to the actual template structure, ensuring stable behavior regardless of format length without relying on static constants.
  • Range checking of written allows detection of vsnprintf failures and excessive writes.

Commits
Fixed in https://github.com/ImageMagick/ImageMagick/commit/66dc8f51c11b0ae1f1cdeacd381c3e9a4de69774 and https://github.com/ImageMagick/ImageMagick6/commit/643deeb60803488373cd4799b24d5786af90972e

Sources & licences