How do I verify a file uploaded with php doesn'

2019-03-14 09:04发布

问题:

Using a simple firefox addon, a hacker can change the mime type of any file they want to upload, bypassing your file type checker.

Hackers can then use a program like GIMP to embed a php script inside the binary data of an image, audio or any other file.

How can I check for this, and prevent it?

回答1:

You can use mime_content_type() to get the actual mime type of the file instead of the value transmitted by the client browser.

Then you can use a library such as php-ClamAV that allows to perform virus-scans in PHP.

You can discard any file extension except those you expect (eg .png, .jpg, etc if you're expecting images). In the specific case of images, you could also neutralize images by modifying them (eg slightly resize them, modify the compression rate, something that would modify the data and neutralize any executable).

Finally of course, take of not giving the execution right to the file. But contrary to what is said in the comments, this will not really protect you. If the hacker finds a way to run php file though an injection for instance, he'll be able to chmod the file and get the execution right (and even run it).

A good practice is also to always rename the file in an unpredictable way. If it is not meant to be accessed by clients after upload, send the files in a folder where directory browsing is disabled.



标签: php security