1

On a website I give users option to upload files (and later download it).

I uploaded a hack.php file and was surprised that I was able to execute it by just typing in the url in the browser.

My permissions on the file a very strict. I don't want users to execute scripts that they upload. This is the relevant ls -la output:

-rwxr----- user apache hack.php

If I tighten permissions for the uploaded file to be:

-rwx------ user apache hack.php

Than the user can't download the file, because apache can't read it.

The whole situation seem bizarre to me. I have given hack.php no executable permissions, yet I can still execute without any troubles. What am I missing here?

In short, the main goal is to disable execution of any file of any sort that is uploaded to the server.

potato
  • 4,479
  • 7
  • 42
  • 99
  • Don't store it in a publicly accessible folder; that way a user can never execute it and you can serve it through php. – jeroen Jan 22 '19 at 12:17

3 Answers3

5

PHP file is not an executable by itself. Actually to execute it you need a PHP interpreter which will just read the file, parse it and execute. So from the OS point of view there is no need to have executable permissions on .php files. Only read permissions are needed.

Karol Samborski
  • 2,757
  • 1
  • 11
  • 18
  • So the executable permissions are just for `bash` scrips? – potato Jan 22 '19 at 12:05
  • Also, since the PHP interpreter is the only interpreter on my system, all I need to do is to check if the file has .php extension and discard it if it does? – potato Jan 22 '19 at 12:09
  • Well executable permissions are most useful for binaries. E.g. if you have some bash script with executable permissions it allows you to run it via `./your_script.sh` but only because of your shell. Notice that if you take off those permissions you can still execute you script using `bash your_script.sh` – Karol Samborski Jan 22 '19 at 12:25
  • If you want to prevent execution php files on your webserver you should make use of `.htaccess` file. – Karol Samborski Jan 22 '19 at 12:25
2

php files are executed by the webserver - this is not related to the executable flag of the file itself.

To prevent the issue you are having is to store uploaded files in a separate folder (ideally not to be reachable directly through the browser).

Now depending on the webserver you are using you can disable the execution of php files for this folder/path

For Apache you can create a .htaccess in your upload folder with the following:

php_flag engine off
wodka
  • 1,320
  • 10
  • 20
1

You don't need to store the file in a public folder, you can store the file in a retrict area, then, read the file and write the output dynamically without running it. You can also set a new file extension.

Something like that: php restrict access to files in directory