顯示具有 PHP 安全攻防 標籤的文章。 顯示所有文章
顯示具有 PHP 安全攻防 標籤的文章。 顯示所有文章

2016年9月12日 星期一

PHP 安全攻防 - Injection 系列(1):OS Command Injection

1.漏洞說明:

當使用存在此漏洞之相關函數,並可接受外部輸入時,可能導致惡意攻擊者執行任意指令。


2.漏洞範例:

(1)system:在瀏覽器上顯示指令執行後的結果,且會回傳指令成功與否。

<?php system('ls '.$_GET['vul']); ?>

(2)passthru:在瀏覽器上顯示指令執行後的結果,不會回傳指令成功與否。

<?php passthru('ls '.$_GET['vul']); ?>

(3)shell_exec:回傳指令執行後的結果,會顯示全部的資訊;exec() 則只會顯示一行。

<?php echo shell_exec('ls '.$_GET['vul']); ?>

(4)`` (backticks):等同 shell_exec

<?php $vul = $_GET['vul']; echo `ls $vul`; ?>

(5)popen:透過 pipe 讀寫檔案。另一危險參數 proc_open 等同 popen,但能控制程度更大,支援 stdin、stdout 等。

<?php $hd =  popen('ls '.$_GET['vul'] ,'r');
  while(!feof($hd)) {echo fgets($hd);}
  pclose($hd); ?>



3.防範方式:
  • 盡量不要執行外部指令。
  • 限制使用者的執行權限,尤其是在敏感的路徑(如 images、uploads 等資料夾)。
  • 若允許檔案上傳,應使用白名單方式限制檔案類型。
  • 驗證使用者的輸入時,最好使用白名單的方式,若須使用黑名單應至少過濾「&」、「|」、「;」、「`」、「%0A」、「%0a」等特殊字串。
  • 限制使用者不能寫入或執行任意外部可執行檔案。
  • 透過自定義的函數,或 Library 來取代外部指令的功能。
  • 若必須使用系統函數時,應限制使用者僅能輸入常數字串。
  • 最好在 php.ini 中的 disable_functions 設定如下函數:exec(), shell_exec(), passthru(), system(), show_source(), popen(), proc_open(), pcntl_exec(), eval(), assert(), call_user_func()、call_user_func_array、preg_replace() 等。
  • 使用 escapeshellcmd() 對使用者的輸入進行過濾(注意此函數在 PHP 版本 < 5.2.6 中具安全性漏洞)。
  • 使用 escapeshellarg() 對使用者的輸入進行過濾(注意此函數在 PHP 版本 < 5.4.42;5.5.x<5.5.26;5.6.x<5.6.10 中具安全性漏洞)。


4.測試方法:
  • <command>
  • `<command>
  • `<command>`
  • ; <command>
  • ; <command> ;
  • | <command>
  • | <command> |
  • || <command>
  • & <command> &
  • && <command>
  • $(<command>)
  • %0a <command> %0a
  • > ~/<file>
  • < ~/<file>


5.Payload:


6.相關工具:


7.推薦學習資料:


8.參考資料:

(1)MITRE - CWE-77
(2)Wiki -  Code Injection
(3)RogueWave - SV.CODE_INJECTION.SHELL_EXEC
(4)nixCraft - PHP.INI settings
(5)Security Off - 利用pcntl_exec突破disable_functions
(6)SecurityInnovation - Preventing Command Injection in PHP with a Few Simple Techniques
(7)stackoverflow - PHP - exec() vs system() vs passthru()
(8)nfuxml - 4種執行系統外部程式函式
(9)Rise and Hack! - OS Command Injection, Path Traversal & Local File Inclusion Vulnerability - Notes
(10)瑞星 - Web攻防系列教程之浅析PHP命令注入攻击
(11)Acunetix - Web-shells 101 using PHP – Introduction to Web Shells – Part 2
(12)Acunetix - Detection and Prevention – An Introduction to Web-Shells – Final Part
(13)xiaoLBlog - preg_replace修饰符e导致的安全问题与利用方式
(14)CVE - CVE-2015-4642
(15)CVE - CVE-2008-2051
(16)開發者俱樂部 - PHP 安全及相關
(17)Pentester Academy - 024 command injection filters
(18)Osanda Malith - Dynamic Function Injection in PHP