Mastering Nginx

(Ron) #1
Chapter 7

[ 187 ]

Preventing inadvertent code execution


When trying to construct a configuration that does what you expect it to do, you


may inadvertently enable something that you did not expect. Take the following


configuration block, for example:


location ~* \.php {

include fastcgi_params;

fastcgi_pass 127.0.0.1:9000;

}

Here we seem to be passing all requests for PHP files to the FastCGI server responsible


for processing them. This would be OK if PHP only processed the file it was given,
but due to differences in how PHP is compiled and configured this may not always be


the case. This can become a problem if user uploads are made into the same directory
structure that PHP files are in.


Users may be prevented from uploading files with a .php extension, but are allowed
to upload .jpg, .png, and .gif files. A malicious user could upload an image file


with the embedded PHP code, and cause the FastCGI server to execute this code


by passing a URI with the uploaded filename in it.


To prevent this from happening, either set the PHP parameter cgi.fix_pathinfo
to 0 or use something similar to the following in your NGINX configuration:


location ~* \.php {

try_files $uri =404;

include fastcgi_params;

fastcgi_pass 127.0.0.1:9000;

}

We have used try_files to ensure that the file actually exists before passing the


request on to the FastCGI server for PHP processing.


Keep in mind that you should evaluate your configuration
to see if it matches your goals. If you have only a few files,
you would be better served by explicitly specifying which
PHP files may be executed instead of the regular expression
location and corresponding try_files.
Free download pdf