PHP-CGI远程代码执行漏洞分析与防范

2019-05-01 15:29:23于海丽

探究一下原理, RFC3875 中规定,当querystring中不包含没有解码的 = 号的情况下,要将querystring作为cgi的参数传入。所以,Apache服务器按要求实现了这个功能。

但PHP并没有注意到RFC的这一个规则,也许是曾经注意并处理了,处理方法就是web上下文中不允许传入参数。但在2004年的时候某个开发者发表过这么一段言论:

From: Rasmus Lerdorf <rasmus <at> lerdorf.com>
Subject: [PHP-DEV] php-cgi command line switch memory check
Newsgroups: gmane.comp.php.devel
Date: 2004-02-04 23:26:41 GMT (7 years, 49 weeks, 3 days, 20 hours and 39 minutes ago)

In our SAPI cgi we have a check along these lines:

 if (getenv("SERVER_SOFTWARE")
  || getenv("SERVER_NAME")
  || getenv("GATEWAY_INTERFACE")
  || getenv("REQUEST_METHOD")) {
  cgi = 1;
 }

 if(!cgi) getopt(...)

As in, we do not parse command line args for the cgi binary if we are 
running in a web context. At the same time our regression testing system 
tries to use the cgi binary and it sets these variables in order to 
properly test GET/POST requests. From the regression testing system we 
use -d extensively to override ini settings to make sure our test 
environment is sane. Of course these two ideas conflict, so currently our 
regression testing is somewhat broken. We haven't noticed because we 
don't have many tests that have GET/POST data and we rarely build the cgi 
binary.

The point of the question here is if anybody remembers why we decided not 
to parse command line args for the cgi version? I could easily see it 
being useful to be able to write a cgi script like:

 #!/usr/local/bin/php-cgi -d include_path=/path
 <?php
  ...
 ?>

and have it work both from the command line and from a web context.

As far as I can tell this wouldn't conflict with anything, but somebody at 
some point must have had a reason for disallowing this.

-Rasmus

显然,这位开发者是为了方便使用类似 #!/usr/local/bin/php-cgi -d include_path=/path 的写法来进行测试,认为不应该限制php-cgi接受命令行参数,而且这个功能不和其他代码有任何冲突。

于是, if(!cgi) getopt(...) 被删掉了。

但显然,根据RFC中对于command line的说明,命令行参数不光可以通过 #!/usr/local/bin/php-cgi -d include_path=/path 的方式传入php-cgi,更可以通过querystring的方式传入。

这就是本漏洞的历史成因。

那么,可控命令行参数,能做些什么事。

通过阅读源码,我发现cgi模式下有如下一些参数可用:

-c 指定php.ini文件的位置
-n 不要加载php.ini文件
-d 指定配置项
-b 启动fastcgi进程
-s 显示文件源码
-T 执行指定次该文件
-h-? 显示帮助

相关文章 大家在看