【问题标题】:How can I sanitize my include statements?如何清理我的包含语句?
【发布时间】:2009-11-25 19:25:53
【问题描述】:

如何清除此问题以使用户无法将页面拉出本地域?

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

【问题讨论】:

  • 包含路径基于用户输入的文件通常被认为是不好的做法。
  • 虽然我同意摩尔的观点,但 Greg 展示了一种安全有效地做到这一点的方法

标签: php security include


【解决方案1】:

最安全的方法是将您的网页列入白名单:

$page = 'home.php';

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

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

include $page;

【讨论】:

    【解决方案2】:
    // 获取我们要查看的页面的绝对文件名 $page = realpath($_GET['page']); // 获取页面所在的目录 $mydir = 目录名(__FILE__); // 查看包含的页面是否在这个允许的目录中 if ($page === false || substr($page, 0, strlen($mydir) != $mydir) { die('走开黑客'); } 别的 { 包括 $page; }

    【讨论】:

    • 假设“$mydir”中没有敏感信息,我可能也会这样做。
    • 最好的选择是解析 URI (/some/page.html) 并使用它来确定需要包含哪个文件(或调用的函数,或创建的类, 管他呢)。然而,这并不是这个特定问题的真正答案。
    【解决方案3】:

    这未经测试。我只是很快就写好了,但它应该可以工作(我希望),它肯定会为你提供一个从哪里开始的基础。

    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);
    

    【讨论】:

      【解决方案4】:

      只需使用 switch 语句。

      检查是否设置了 $_GET 变量,然后通过案例运行它并让默认转到 home.php

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-11
        • 1970-01-01
        • 1970-01-01
        • 2010-11-04
        • 1970-01-01
        相关资源
        最近更新 更多