Question

Alright, so I have seen a lot of discussions about how to secure image upload forms, however noone told me, what to do exactly to 100% prevent malicious code to be uploaded via my application.

I'm currently thinking about image re-creation, as I saw that it would be quite a secure method. Does it? What other options exists? Also which extensions are preferred with these methods?

Was it helpful?

Solution

I'm currently thinking about image re-creation, as I saw that it would be quite a secure method.

Unless library you use for re-creation is not vulnerable :P. But seriously, I think this is not a bad idea and in most cases it will rather improve security.

To improve security you can also detect content type using Fileinfo functions (mime_content_type() in previous versions of PHP).

An excerpt form PHP manual on older Mimetype extension, which is now replaced by Fileinfo:

The functions in this module try to guess the content type and encoding of a file by looking for certain magic byte sequences at specific positions within the file. While this is not a bullet proof approach the heuristics used do a very good job.


As for the question, which PHP extension suits best for secure image re-creation... I've checked CVE details website. I think the applicable trio are those extensions:

  1. GD (6 vulnerabilities)
  2. ImageMagick (44 vulnerabilities)
  3. Gmagick (12 vulnerabilities)

From the comparison I think GD suits best, because it has smallest number of security issues and they are quite old. Three of them are critical, but ImagMagick and Gmagick do not perform any better... ImageMagick seems to be very buggy (at least when it comes to security), so I choose Gmagick as the second option.

OTHER TIPS

As this document says, below is a sample snippet you need.

   $finfo = new finfo(FILEINFO_MIME_TYPE);
   $fileContents = file_get_contents($_FILES['some_name']['tmp_name']);
   $mimeType = $finfo->buffer($fileContents);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top