nginx php 错误配置导致安全漏洞

后知后觉发现了此文 Setting up PHP-FastCGI and nginx? Don’t trust the tutorials: check your configuration! 基本上是说,网上的大部分 nginx + php 配置教程中有一个错误,导致 php 会试图执行非 php 文件,甚至是用户上传的图片。

事实上看到此漏洞的描述我已经立刻想到问题之所在了,的确,之前我写的那篇配置笔记也是有此问题的。基本原理就是 nginx 配置中有这么一段

location ~ .*.php5?$ {
        include fastcgi_params;
        root /var/host/phpMyAdmin;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass unix:/var/run/php_fcgi.sock;
        fastcgi_index index.php;
    }

凡是以 .php 或者 .php5 结尾的 uri 都会被交给 php 处理,于是类似于 user.jpg/aaa.php 也会交给 php 处理,于是 user.jpg 就被当成 php 代码给执行了。

解决此问题的方法有好几种,codex.wordpress.com 上面提供的一种方式是如下修改 nginx 中有关 php 的配置。不过如果 nginx 和 php 不运行在同一台机器上时,此方法无效。

location ~ \.php$ {
	# Zero-day exploit defense.
	# http://forum.nginx.org/read.php?2,88845,page=3
	# Won't work properly (404 error) if the file is not stored on this server, which is entirely possible with php-fpm/php-fcgi.
	# Comment the 'try_files' line out if you set up php-fpm/php-fcgi on another machine.  And then cross your fingers that you won't get hacked.
	try_files $uri =404;

	fastcgi_split_path_info ^(.+\.php)(/.+)$;
	include fastcgi_params;
	fastcgi_index index.php;
	fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
#	fastcgi_intercept_errors on;
	fastcgi_pass php;
}

Leave a Reply

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