Artisan Développeur

Qualité, amélioration continue, agilité.

[php] How to manage uploaded images in secure way

I dev lately on an open source project, GRR (, it’s an old resources management script.

Writen a looooong time ago, « old school » code, but functional and pretty complete.

A security researcher , « kmkz » (Bourbon Jean-marie) – twitter: @kmkz_security, has discovered a security flaw which permit to upload a shell using the upload logo functionality.
Just need to rename the image like EvilShell.php.jpg …
The old code, never check if the submitted file have more than one extension, or if it’s an actual image… Just check if the final extension is jpg, gif or png.

After lot of reading about mime type, EXIF code injection, magic bytes, and million of stackoverflow questions, my little function :

This is a small, not POO, simple function to check :

  • multiple extension (logo.php.png)
  • extension allowed (jpg, png or gif)
  • good mime type with php finfo_file method
  • if image is valid and remove EXIF with one of the imagecreateFORMAT function from GD
  • if target directory is writable
  • if move_uploaded_file pass without error

The idea is to start test with the obvious attempts, remove the EXIF data to be sure and rename the file to avoid long and wired names.

I think I cover all attack vectors with an image, but if you want test it, break it, improve or comment, do it !

[pastacode lang= »php » user= »nicolas-san » repos= »upload » path_id= »upload.php » revision= »master » highlight= » » lines= » » provider= »github »/]


Comment ( 1 )

  1. / Replykmkz
    Yop, Here my public advisory : Thx a lot for the credit!! @++

Leave a reply

Your email address will not be published.

Ce site utilise Akismet pour réduire les indésirables. En savoir plus sur comment les données de vos commentaires sont utilisées.