
TL;DR (Exec Brief)
Recent rounds of bug fixes in ImageMagick uncovered memory-corruption and integer-overflow flaws across multiple decoders/“coders” (e.g., JPEG2000/JP2, TIFF, PSD, BMP/PCX/PNM, DCM/medical formats, RLE families, etc.). In common web stacks where user-supplied images are processed automatically (PHP imagick, Python wand, Ruby rmagick, Node gm/sharp bridges), a crafted image can trigger heap/stack out-of-bounds writes, leading to crashes (DoS) and, in some cases, code execution under the service account.
Risk: Pre-auth RCE/DoS via file upload, URL-fetch (server-side import), or background thumbnailers.
Who’s affected: Any workload using ImageMagick 6/7 without current patches and without strict policy.xml hardening and resource limits.
Why these bugs keep happening
ImageMagick supports dozens of complex, legacy formats with exotic compression and metadata. Typical root causes:
- Integer overflows during dimension/stride calculations → undersized allocations → heap overflows.
- Bounds-check mistakes when parsing chunks/tiles/scanlines → out-of-bounds read/write.
- Untrusted metadata (profiles/EXIF/ICC/IPTC) parsed into fixed buffers.
- Delegate chains (e.g., Ghostscript for PS/PDF/XPS, coders invoking external tools) expanding the attack surface.
Result: A single malformed image can destabilize your web worker or, with grooming, pivot to RCE.
Threat model (real world)
- User uploads an image to your site (profile picture, product photo).
- Your backend auto-resizes/thumbnails via ImageMagick (CLI
magick/convertor libMagick). - Crafted payload triggers overflow in a specific coder (e.g., JP2 tile, DCM tag, TIFF strip).
- Outcome ranges from SIGSEGV (DoS) to arbitrary write enabling RCE in the web worker/container.
- Attacker laterally moves using the app’s cloud creds, storage keys, or DB access.
Immediate Actions (Do this now)
- Patch/Upgrade
- Move to the latest stable ImageMagick 7.x (or the newest LTS for 6.x if you’re pinned).
- Rebuild images/containers; verify at runtime:
magick -version convert -list configure | grep -i delegates convert -list policy
- Enforce
policy.xmlhardening (deny risky coders & delegates)- Disable rarely used/legacy formats and all PostScript/Ghostscript-backed paths by default.
- Minimal starter (merge into
/etc/ImageMagick-7/policy.xmlor equivalent):<policymap> <!-- Block external helpers & dangerous coders --> <policy domain="coder" rights="none" pattern="PS,PS2,PS3,EPS,PDF,XPS,EPDF,EPT,EPSF,EPSI,PSB"/> <policy domain="coder" rights="none" pattern="DCM,PCL,MSL,MVG,PLT,FIG,ART,PCD"/> <!-- Constrain everything else --> <policy domain="resource" name="memory" value="256MiB"/> <policy domain="resource" name="map" value="512MiB"/> <policy domain="resource" name="width" value="8000"/> <policy domain="resource" name="height" value="8000"/> <policy domain="resource" name="area" value="256MP"/> <policy domain="system" name="precision" value="6"/> <policy domain="path" rights="none" pattern="@*"/> <!-- no indirect files --> </policymap> - Tailor to your business formats (keep only
PNG, JPEG, WEBP, AVIFetc.).
- Run as least privilege + sandbox
- Never run ImageMagick as root.
- Contain with seccomp/AppArmor/SELinux or a restricted container runtime; mount noexec on
/tmpif feasible.
- Kill URL-fetching and external delegates
- Disallow
http(s):///ftp://sources and@filenameindirection in user code paths. - Set environment:
MAGICK_CODER_MODULE_PATHto a curated directory; remove unwanted modules.
- Disallow
- Add size/format pre-filters before ImageMagick
- Reject images with huge dimensions or mismatched MIME vs extension.
- Prefer a transcode-to-safe pipeline: decode with a minimal, audited lib (e.g., libvips for validation), then re-encode to PNG/JPEG with conservative settings.
Detection & Threat Hunting
Signals to watch
- Frequent segfaults of
magick/convert/php-fpm/gunicornaround image uploads. - OOM kills or CPU spikes when processing uncommon formats (JP2, DCM, PICT, PCX).
- Creation of unexpected temp files in
/tmpor cache dirs during processing.
Splunk (web upload → crash correlation)
(index=web sourcetype=nginx OR sourcetype=apache)
| stats count as uploads by src, uri, http_content_type, file_ext, bin(_time, 5m)
| join type=left _time
[ search index=os (process_name="magick" OR process_name="convert" OR process_name="php-fpm")
(EventCode=11 OR EventCode=1000 OR message="segfault" OR message="killed")
| stats count as crashes by host, bin(_time, 5m) ]
| where crashes > 0
| table _time, src, uri, http_content_type, file_ext, uploads, crashes
Elastic KQL (uncommon formats through upload endpoints)
url.path : ("/upload*" or "/image*")
and http.request.body.content_type : *
and file.extension : ("jp2","j2k","jpc","dcm","pcx","pict","pfm","sgi","xwd")
EDR / Sysmon (process spawn anomalies)
w3wp.exe,php-fpm,gunicorn,nodespawningmagick/convertwith unusually large geometry or rare coders in args.
Secure Configuration Checklist (Dev & Prod)
- ✅ Pin formats you truly need; block everything else in
policy.xml. - ✅ Resource limits (memory/map/area/time) tuned to your workload.
- ✅ No internet fetching of images during processing (download via your app and serve as a file).
- ✅ Temporary directories separated and cleaned; apply noexec,nodev,nosuid where possible.
- ✅ CI/CD guardrails: a) unit tests that process a corpus of nasty images, b)
magick -list policycheck to assert hardening, c) SCA to alert on vulnerable ImageMagick versions. - ✅ Observability: crash metrics + alert on rate of failures per minute in image workers.
Incident Response (if you suspect exploitation)
- Isolate the image worker pool/pod/VM; preserve memory/core dumps.
- Quarantine the triggering files; do not open them outside a sandbox.
- Collect worker logs,
/tmpartifacts, and web request logs for the time window. - Rotate app secrets/credentials accessible to the worker (cloud keys, DB creds).
- Rebuild workers from a known-good base; redeploy with patched ImageMagick and stricter policies.
- Backfill checks: re-scan recent uploads for suspicious formats/headers.
Developer Tips (safer image pipeline)
- Prefer libvips (via
sharpin Node,pyvipsin Python) for initial sniffing and basic transforms; call ImageMagick only for specific transforms you cannot avoid. - Normalize: decode → sanitize → re-encode to PNG/JPEG; strip metadata (
-strip). - For thumbnails:
-define jpeg:size=... -thumbnail WxHto limit decode cost.
CyberDudeBivash Verdict
ImageMagick’s power is also its danger: a huge surface of complex parsers. Treat it like a remote-code execution boundary. Patch fast, lock down policy.xml, sandbox aggressively, and enforce a minimal-formats strategy. If your business doesn’t need a format, turn it off.
#CyberDudeBivash #ImageMagick #MemoryCorruption #IntegerOverflow #RCE #AppSec #SupplyChain #ZeroTrust #BlueTeam #IncidentResponse #ThreatIntel
Leave a comment