2017-03-07 29 views
1

我有一個html表單,要求用戶輸入一個域名,這是張貼到下面的php7.0頁面處理一個shell腳本,然後通過輸出通過aha寫入到一個HTML頁面,然後顯示。如何在php7中使用shell_exec時停止命令注入?

我的問題是我怎麼能防止用戶注入命令,如:

domain.com | rm * -rf

我認爲這可以通過使用safe_mode並限制命令可以運行的目錄來完成,但現在看起來這個功能已經被棄用了。

$domain_arg = escapeshellarg($_POST['domain']); 
$today = date("Y-m-d-H:i:s"); 
$cmd = "/home/ubuntu/dtest/dtest.sh $domain_arg | aha -b -t 'Domain test of $domain_arg' > /var/www/website/results/$domain_arg.$today.html"; 
$output = shell_exec($cmd); 
header("Location: http://the.web.com/results/$result.$today.html"); 
+1

非常危險,允許用戶輸入注入'執行'命令。在做這件事之前,你最好有一些非常好的驗證。我相信你可以寫一個驗證器,確保輸入是一個有效的域名。 – Pitchinnate

+0

使用'escapeshellarg'就是你需要做的,而你正在做。 – miken32

+0

雖然你應該使用別的東西作爲文件名組件。 – miken32

回答

0

您在運行參數前使用escapeshellarg,結果是單引號字符串,如'domain.com | rm *'。你的問題是,你不能用此作爲外殼的說法,但作爲一個shell參數的部分

aha -b -t 'Domain test of $domain_arg' 

這絕對導致您所描述的問題。嘗試這樣的代替:

<?php 
$domain_arg = escapeshellarg($_POST["domain"]); 
$log_msg = escapeshellarg("Domain test of $_POST[domain]"); 
$today = date("Y-m-d-H:i:s"); 
$log_file = preg_replace(
    "/[^\w:\\/.-]/i", 
    "_", 
    "/var/www/website/results/$_POST[domain].$today.html" 
); 

$cmd = "/home/ubuntu/dtest/dtest.sh $domain_arg | aha -b -t $log_msg > $log_file"; 
$output = shell_exec($cmd); 
$result = rawurlencode($output); // just guessing that's where it comes from 
$today = rawurlencode($today); 
header("Location: http://the.web.com/results/$result.$today.html"); 
+0

我不得不添加$ filename =''。 preg_replace('/ [^ a-z0-9]/i','_',$ _POST ['domain'])。今天$。 '的.html';並設置標題爲$文件名,我不得不添加一個。之前的HTML,但除此之外,這完美的作品,我不能再刪除文件,謝謝! – user2001109

+0

我剛剛注意到你的編輯,也會嘗試這個版本。 – user2001109

+0

這很容易解決。我希望你在生產中使用它之前瞭解所有這些代碼! ;) – miken32