PHP 8.3.4 Released!

空字符(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 note

User Contributed Notes 2 notes

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

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