S
S
Snorway2016-08-08 17:19:54
Yii
Snorway, 2016-08-08 17:19:54

How to secure the upload of images to the site?

Is there a best practice to protect the site from hacking by filling the shell in the image? From known to me - image resize. Is it reliable?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vamp, 2016-08-08
@Snorway

The essence of the vulnerability is that an arbitrary php code is inserted into the image metadata. Further, using the site's vulnerabilities, the attacker forces the server to execute this picture as a php script.
To get rid of shells embedded in this way, a resize is used, during which all metadata is lost. An additional bonus is the validity check - imagecreatefromstring() and other similar functions will return an error if the user has uploaded a broken/unsupported format or no image at all.
In principle, this is a good way if you do not need the original of the uploaded image. Use it without fear.
If the original is still needed, then the metadata should be removed during upload. Here it will be more difficult, since each format has its own characteristics in this regard. For example, jpeg has COM and APP1 (EXIF) sections. png has tEXt, iTXt and zTXt. Other formats have some other features of their own. That is, you need to understand image formats and use libraries that allow you to work with the format at such a low level. Moreover, it is necessary to delete all metadata that is not directly related to the image, since php code can be put into a non-standard chunk - the browser will ignore it and display the image correctly, but the php code will still be present there.
You can also try to search for the substring <? in the raw content of the file. If the substring is found, then perhaps there is some php code there. The method is so-so and not recommended for use - there will be many false positives.
And never again save an image in the file system under the name with which the user uploaded it. Generate your filenames. If you need a custom file name, save it separately in the database.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question