Linux – code injected inside PHP file with 777 permission

hackinglinuxPHPSecurity

I woke up to find that all the folders in my shared-web-host with 777 permission had two new php file. The code inside the file could not be read – here is the decoded version: http://pastie.org/779226 (what the…?)
That code was injected even inside some PHP files.

I am at a loss as to HOW someone would do this? I know having 777 permission is not the smartest thing, but how did they get into my folder system in the first place.

I'm just a client side programmer, would be great if I had some advice on how to keep this from happening in the future.

Cheers.

Best Answer

Here is the de-obfuscated version of the script: http://pastie.org/private/iobgt7aetg8mezoepucsg

The code seems to include external PHP code from another website and collects information about your visitors while doing so.

One way this could of occurred is that you are allowing file uploads on a directory accessible from the outside. Doing so without proper validation is dangerous as a malicious user can upload a PHP file (using your image upload) with malicious code. If the web-server is not configured properly, the code will run when requested.

In order to avoid such problems, make sure that:

  • PHP processes are run by a limited user.
  • Files which do not need to be edited are set to be writable only by the owner (0644 or 0744 depending if you require the execute bit or not).
  • Only set the upload directory to writable.
  • Try to use an upload directory that is outside your webroot. Then use readfile() to serve the file.
  • Validate the files. If you want your form only to allow images, validate the magic bits and make sure that the image is valid. This is a hugely overlooked step. Same applies to any other format. Do not rely on the file extension or the mimetype sent by the client. Check the actual file content.