2012-03-13 30 views
2

我是相當新的PHP,並設法將這個簡單的下載腳本通過閱讀在這裏列出的一些問題在SO,並想問你那些更熟悉PHP的人看一看在下面的代碼中,看看我的實現是否有明顯的缺陷,或者是否應該改變。簡單的文件下載器

只是讓你知道,在我有限的測試過程中,一切似乎都做工精細,但正如我說我是相當新的PHP和希望確保我不是失去了一些東西,可能破壞了腳本以後的道路。

<?php 

//Settings 
$filesPath = './files'; 
$fileName = $_GET['file']; 
$allowedExts = array('jpg','png','gif'); 


//Functions 
//Returns the extension portion of a filename. 
function file_extension($fileName) 
{ 
    $path_info = pathinfo($fileName); 
    return strtolower($path_info['extension']); 
} 

//Validation and processing 
//Check that a file is actually being requested 
if (empty($fileName)) { 
    die('no file was requested'); 
} 

//Check that the file is allowed to be downloaded 
if (!in_array(file_extension($fileName), $allowedExts)) { 
    die('you cannot download this file'); 
} 

//Get the file 
if (file_exists($filesPath . DIRECTORY_SEPARATOR . $fileName)) { 
    header('Content-Description: File Transfer'); 
    header('Content-Type: application/octet-stream'); 
    header('Content-Disposition: attachment; filename=' . basename($fileName)); 
    header('Content-Transfer-Encoding: binary'); 
    header('Expires: 0'); 
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
    header('Pragma: public'); 
    header('Content-Length: ' . filesize($fileName)); 
    ob_clean(); 
    flush(); 
    readfile($fileName); 
    exit; 
} 
?> 

TIA, 戴夫

+0

不是安全相關的,但是你應該有'set_time_limit(0);'如果你不想讓你的下載在隨機中途中止.. http://php.net/manual/en/function.set-time-limit.php – Ben 2012-03-13 08:28:15

+0

謝謝,我補充說該設置,不知道我的主機會尊重它tho。 – 2012-03-13 09:01:08

+0

不是一個設置,只是在您的php代碼中,靠近頂部,添加'set_time_limit(0);' – Ben 2012-03-13 09:49:54

回答

3

您可以使用腳本很容易受到目錄遍歷。在你的情況下,我會在文件名上使用realpath(),並檢查它是否是.files/內的有效文件。

有人可能會遍歷目錄樹並竊取文件,如/etc/passwd等。

+0

謝謝我會研究,但擴展檢查不會阻止他們訪問任何文件,除了那些在allowedExt數組中? – 2012-03-13 08:28:50

+0

只是爲了更新我嘗試遍歷與像這樣download.php?file = ../../../../../etc/passwd這個url並且收到了一個403禁止的錯誤消息,所以我不知道如何測試此漏洞。 – 2012-03-13 09:04:13

+0

您的網絡服務器可能擁有自己的用戶帳戶,並且僅限於訪問特定目錄或運行SuPHP。但是,如果腳本在配置錯誤的服務器上執行,執行此類檢查仍然是一種好的做法。 – F21 2012-03-13 09:30:10

0

你是開放的黑客攻擊,有人可能只是做?文件= ../etc/passwd文件和/ BAM擁有 您做的更好就如何防範LFI一些檢查