2009-11-25 122 views
3

如何清理此問題,以便用戶無法將頁面拉出本地域外?如何清理我的include語句?

<?php 
if(!empty($_GET['page'])) 
{ 
    include($_GET['page']); 
} 
else 
{ 
    include('home.php'); 
} 
?> 
+0

<?PHP \t \t \t \t \t如果(!空($ _ GET ['頁'])) \t \t \t \t \t { \t \t \t \t \t \t包括($ _ GET [' 頁']); \t \t \t \t \t} \t \t \t \t \t別的 \t \t \t \t \t { \t \t \t \t \t \t包括( 'home.php'); \t \t \t \t \t} \t \t \t \t?> – Mike 2009-11-25 19:26:33

+8

包括其中路徑是基於用戶輸入通常被認爲是不好的做法的文件。 – 2009-11-25 19:33:53

+0

雖然我同意w /摩爾,格雷格顯示了一種方法來安全有效地做到這一點 – 2009-11-25 19:44:15

回答

12

最安全的方法是白名單頁面:

$page = 'home.php'; 

$allowedPages = array('one.php', 'two.php', ...); 

if (!empty($_GET['page']) && in_array($_GET['page'], $allowedPages)) 
    $page = $_GET['page']; 

include $page; 
+0

感謝格雷格。這工作很棒! – Mike 2009-11-25 20:38:40

2
 

// get the absolute file name of the page we want to see 
$page = realpath($_GET['page']); 

// get the directory in which pages are 
$mydir = dirname(__FILE__); 

// see if the included page is inside this allowed dir 
if ($page === false || substr($page, 0, strlen($mydir) != $mydir) { 
die('go away hacker'); 
} else { 
include $page; 
}
+0

假設「$ mydir」中沒有敏感信息,這也是我可能會這麼做的。 – 2009-11-27 15:02:14

+0

最好的選擇是解析URI(/some/page.html)並使用它來確定需要包含哪個文件(或調用的函數,創建的類或其他)。但是,這不是對這個特定問題的答案。 – 2009-11-27 15:11:07

0

這不是測試。我只是寫得很快,但它應該工作(我希望),它一定會爲您提供從何處入手的基礎。

define('DEFAULT_PAGE', 'home.php'); 
define('ALLOWED_PAGES_EXPRESSION', '^[\/]+\.php$|^[\/]+\.html$'); 

function ValidateRequestedPage($p) 
{ 
    $errors_found = False; 

     // Make sure this isn't someone trying to reference directories absolutely. 
    if (preg_match('^\/.+$', $p)) 
    { 
     $errors_found = True; 
    } 

     // Disable access to hidden files (IE, .htaccess), and parent directory. 
    if (preg_match('^\..+$', $p)) 
    { 
     $errors_found = True; 
    } 


     // This shouldn't be needed for secure servers, but test for remote includes just in case... 
    if (preg_match('.+\:\/\/.+', $p)) 
    { 
     $errors_found = True; 
    } 

    if (!preg_match(ALLOWED_PAGES_EXPRESSION, $p)) 
    { 
     $errors_found = True; 
    } 

    return !$errors_found; 
} 

if (!isset($_GET['page'])) { $page = DEFAULT_PAGE; } 
else { $page = $_GET['page']; } 

if (!ValidateRequestedPage($page)) 
{ 
    /* This is called when an error has occured on the page check. You probably 
     want to show a 404 here instead of returning False. */ 
    return False; 
} 

// This suggests that a valid page is being used. 
require_once($page); 
0

只需使用switch語句。

檢查是否$ _GET變量被設置,然後通過的情況下運行,並具有默認去home.php