標籤:http 使用 ar 資料 c ef .net php 編程
使用系統命令是一項危險的操作,尤其在你試圖使用遠端資料來構造要執行的命令時更是如此。如果使用了被汙染資料,命令注入漏洞就產生了。
exec()是用於執行shell命令的函數。它返回執行並返回命令輸出的PowerBet最後一行,但你可以指定一個數組作為第二個參數,這樣輸出的每一行都會作為一個元素存入數組。使用方式如下:
<?php$last = exec(‘ls‘, $output, $return);print_r($output);echo "Return [$return]";?>
假設ls命令在shell中手工運行時會產生如下輸出:
$ lstotal 0-rw-rw-r-- 1 chris chris 0 May 21 12:34 php-security-rw-rw-r-- 1 chris chris 0 May 21 12:34 chris-shiflett
當通過上例的方法在exec()中運行時,輸出結果如下:
Array( [0] => total 0 [1] => -rw-rw-r-- 1 chris chris 0 May 21 12:34 php-security [2] => -rw-rw-r-- 1 chris chris 0 May 21 12:34 chris-shiflett)Return [0]
這種運行shell命令的方法方便而有用,但這種方便為你帶來了重大的風險。如果使用了被汙染資料構造命令串的話,攻擊者就能執行任意的命令。
我建議你有可能的話,要避免使用shell命令,如果實在要用的話,就要確保對構造命令串的資料進行過濾,同時必須要對輸出進行轉義:
<?php$clean = array();$shell = array();/* Filter Input ($command, $argument) */$shell[‘command‘] = escapeshellcmd($clean[‘command‘]);$shell[‘argument‘] = escapeshellarg($clean[‘argument‘]);$last = exec("{$shell[‘command‘]} {$shell[‘argument‘]}", $output, $return);?>
儘管有多種方法可以執行shell命令,但必須要堅持一點,在構造被啟動並執行字串時只允許使用已過濾和轉義資料。其他需要注意的同類函數有passthru( ), popen( ), shell_exec( ),以及system( )。我再次重申,如果有可能的話,建議避免所有shell命令的使用。
PHP安全編程:shell命令注入