Home  >  Article  >  Backend Development  >  php—Null character problem

php—Null character problem

伊谢尔伦
伊谢尔伦Original
2016-11-22 10:46:531029browse

由于 PHP 的文件系统操作是基于 C 语言的函数的,所以它可能会以您意想不到的方式处理 Null 字符。 Null字符在 C 语言中用于标识字符串结束,一个完整的字符串是从其开头到遇见 Null 字符为止。 以下代码演示了类似的攻击:

Example #1 会被 Null 字符问题攻击的代码

<?php
    $file = $_GET[&#39;file&#39;]; // "../../etc/passwd\0"
    if (file_exists(&#39;/home/wwwrun/&#39;.$file.&#39;.php&#39;)) {
        // 文件/home/wwwrun/../../etc/passwd存在的话那么file_exists方法会返回true
        include &#39;/home/wwwrun/&#39;.$file.&#39;.php&#39;;
        // the file /etc/passwd will be included
    }
?>

因此,任何用于操作文件系统的字符串(特别是程序外部输入的字符串)都必须经过适当的检查。以下是上述例子的改进版本:

Example #2 验证输入的正确做法

<?php
    $file = $_GET[&#39;file&#39;];
    // 对字符串进行白名单检查
    switch ($file) {
        case &#39;main&#39;:
        case &#39;foo&#39;:
        case &#39;bar&#39;:
            include &#39;/home/wwwrun/include/&#39;.$file.&#39;.php&#39;;
            break;
        default:
            include &#39;/home/wwwrun/include/main.php&#39;;
    }
?>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn