Nginx + PHP 爲什麼要在php.ini設置cgi.fix_pathinfo=0

現在普遍的Nginx + PHP cgi的做法是在配置文件中, 通過正則匹配(Nginx(PHP/fastcgi)的PATH_INFO問題)設置SCRIPT_FILENAME, 發現了一個這種方式的安全漏洞.

比如, 有http://www.laruence.com/fake.jpg, 那麼通過構造如下的URL, 就可以看到fake.jpg的二進制內容:

  1.  
  2. http://www.laruence.com/fake.jpg/foo.php

爲什麼會這樣呢?

比如, 如下的nginx conf:

  1. location ~ \.php($|/) {
  2.      fastcgi_pass 127.0.0.1:9000;
  3.      fastcgi_index index.php;
  4.  
  5.      set $script $uri;
  6.      set $path_info "";
  7.      if ($uri ~ "^(.+\.php)(/.*)") {
  8.           set $script $1;
  9.           set $path_info $2;
  10.      }
  11.  
  12.      include fastcgi_params;
  13.      fastcgi_param SCRIPT_FILENAME $document_root$script;
  14.      fastcgi_param SCRIPT_NAME $script;
  15.      fastcgi_param PATH_INFO $path_info;
  16. }

通過正則匹配以後, SCRIPT_NAME會被設置爲”fake.jpg/foo.php”, 繼而構造成SCRIPT_FILENAME傳遞個PHP CGI, 但是PHP又爲什麼會接受這樣的參數, 並且把a.jpg解析呢?

這就要說到PHP的cgi SAPI中的參數, fix_pathinfo了:

  1. ; cgi.fix_pathinfo provides *real* PATH_INFO/PATH_TRANSLATED support for CGI. PHP's
  2. ; previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok
  3. ; what PATH_INFO is. For more information on PATH_INFO, see the cgi specs. Setting
  4. ; this to 1 will cause PHP CGI to fix it's paths to conform to the spec. A setting
  5. ; of zero causes PHP to behave as before. Default is 1. You should fix your scripts
  6. ; to use SCRIPT_FILENAME rather than PATH_TRANSLATED.
  7. cgi.fix_pathinfo=1

如果開啓了這個選項, 那麼就會觸發在PHP中的如下邏輯:

  1. /*
  2. * if the file doesn't exist, try to extract PATH_INFO out
  3. * of it by stat'ing back through the '/'
  4. * this fixes url's like /info.php/test
  5. */
  6. if (script_path_translated &&
  7.      (script_path_translated_len = strlen(script_path_translated)) > 0 &&
  8.      (script_path_translated[script_path_translated_len-1] == '/' ||
  9. ....//以下省略.

到這裏, PHP會認爲SCRIPT_FILENAME是fake.jpg, 而foo.php是PATH_INFO, 然後PHP就把fake.jpg當作一個PHP文件來解釋執行… So…

這個隱患的危害用小頓的話來說, 是巨大的.

對於一些論壇來說, 如果上傳一個圖片(實際上是惡意的PHP腳本), 繼而構造這樣的訪問請求…

所以, 大家如果有用這種服務器搭配的, 請排查, 如果有隱患, 請關閉fix_pathinfo(默認是開啓的).


本文地址: http://www.laruence.com/2010/05/20/1495.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章