Preventing inadvertent code execution – Nginx

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 the 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 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 used try_files to ensure that the file actually exists before passing the request on to the FastCGI server for PHP processing.

Tip

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 expression.

Related Articles

How to add swap space on Ubuntu 21.04 Operating System

How to add swap space on Ubuntu 21.04 Operating System

The swap space is a unique space on the disk that is used by the system when Physical RAM is full. When a Linux machine runout the RAM it use swap space to move inactive pages from RAM. Swap space can be created into Linux system in two ways, one we can create a...

read more

Lorem ipsum dolor sit amet consectetur

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

18 − 4 =