ImageMagick remote code execution
Description
ImageMagick, a widely-used image processing library, contains multiple critical vulnerabilities that allow remote code execution when processing maliciously crafted image files. This affects web applications that accept user-uploaded images and process them using ImageMagick directly or through popular wrapper libraries such as PHP's imagick, Ruby's rmagick and paperclip, or Node.js's imagemagick. Attackers can exploit these vulnerabilities by uploading specially crafted image files that contain embedded commands, which ImageMagick will execute during processing.
Remediation
Implement the following security measures to protect against ImageMagick RCE vulnerabilities:
1. Update ImageMagick: Upgrade to the latest patched version of ImageMagick (6.9.3-10 or later for version 6.x, or 7.0.1-1 or later for version 7.x).
2. Validate File Headers: Verify that uploaded files begin with the correct magic bytes for expected image formats before processing. Example validation in PHP:
$allowedTypes = [
'image/jpeg' => "\xFF\xD8\xFF",
'image/png' => "\x89\x50\x4E\x47",
'image/gif' => "GIF89a"
];
$fileHeader = file_get_contents($uploadedFile, false, null, 0, 10);
$isValid = false;
foreach ($allowedTypes as $mime => $magic) {
if (strpos($fileHeader, $magic) === 0) {
$isValid = true;
break;
}
}
if (!$isValid) {
// Reject the file
}3. Configure ImageMagick Policy: Edit the ImageMagick policy.xml file (typically located at /etc/ImageMagick-6/policy.xml) to disable vulnerable coders:
<policy domain="coder" rights="none" pattern="EPHEMERAL" /> <policy domain="coder" rights="none" pattern="URL" /> <policy domain="coder" rights="none" pattern="HTTPS" /> <policy domain="coder" rights="none" pattern="MVG" /> <policy domain="coder" rights="none" pattern="MSL" /> <policy domain="path" rights="none" pattern="@*" />
4. Sanitize Filenames: Strip any special characters from uploaded filenames and do not pass user-controlled data to ImageMagick command-line parameters.
5. Consider Alternatives: Evaluate using alternative image processing libraries that are not affected by these vulnerabilities, or implement sandboxing to isolate ImageMagick processes.