Nginx PHP code execution via FastCGI
Description
Nginx servers running PHP through FastCGI are vulnerable to arbitrary PHP code execution when the PHP configuration option 'cgi.fix_pathinfo' is enabled. This option causes PHP to rewrite the SCRIPT_FILENAME and PATH_INFO parameters, allowing attackers to append PHP code to requests for non-PHP files (such as images or text files). When Nginx passes these manipulated requests to PHP-FPM, the appended code gets executed on the server. This vulnerability affects default PHP configurations where cgi.fix_pathinfo is set to 1.
Remediation
Apply one of the following mitigations to prevent this vulnerability:
Option 1: Disable cgi.fix_pathinfo (Recommended)
Edit your php.ini file and set:
cgi.fix_pathinfo = 0After making this change, restart PHP-FPM for the setting to take effect.
Option 2: Configure Nginx to Block Malicious Requests
Add the following security check to your Nginx server block configuration before the FastCGI pass directive:
location ~ \.php$ {
# Prevent path traversal attacks
if ($fastcgi_script_name ~ \..*\/.*php) {
return 403;
}
# Your existing FastCGI configuration
fastcgi_pass unix:/var/run/php-fpm.sock;
include fastcgi_params;
}After updating the Nginx configuration, test it with nginx -t and reload Nginx with nginx -s reload.Additional Best Practice: Ensure that only legitimate PHP files in designated directories can be executed by using strict location blocks and avoiding regex patterns that might match unintended files.