PHP安全編程:shell命令注入

來源:互聯網
上載者:User

標籤: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命令注入

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.