略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: 空字符(Null bytes)相关问题

2024-03-29

空字符(Null bytes)相关问题

由于 PHP 使用底层 C 函数进行文件系统相关操作,因此它可能会以完全意想不到的方式处理空字符。 在 C 语言中空字符标识字符串的结束,所以一个完整的字符串是从其开头到遇见空字符为止。 下面的示例展示了易受攻击的代码,演示了这个问题:

示例 #1 会被空字符攻击的代码

<?php
$file 
$_GET['file']; // "../../etc/passwd\0"
if (file_exists('/home/wwwrun/'.$file.'.php')) {
    
// 当 /home/wwwrun/../../etc/passwd 文件存在的时候 file_exists 将会返回 true
    
include '/home/wwwrun/'.$file.'.php';
    
// 将会加载 /etc/passwd 文件
}
?>

因此,在文件系统操作中都应该正确检查任何被污染的字符串。这是上个示例的改进版本:

示例 #2 验证输入的正确性

<?php
$file 
$_GET['file']; 

// 对值进行白名单检查
switch ($file) {
    case 
'main':
    case 
'foo':
    case 
'bar':
        include 
'/home/wwwrun/include/'.$file.'.php';
        break;
    default:
        include 
'/home/wwwrun/include/main.php';
}
?>
add a noteadd a note

User Contributed Notes 2 notes

up
10
Anonymous
8 years ago
Looks like this issue was fixed in PHP 5.3 https://bugs.php.net/bug.php?id=39863
up
3
cornernote [at] gmail.com
7 years ago
clean input of null bytes:

<?php
$clean
= str_replace(chr(0), '', $input);
?>

官方地址:https://www.php.net/manual/en/security.filesystem.nullbytes.php

冷却塔厂家 广告
-- 广告
北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3