是ASCII“../&”唯一的字节序列,指示在PHP中的目录遍历? [英] Is ASCII "../" the only byte sequence that indicates a directory traversal in PHP?
问题描述
我有一个PHP应用程序使用 $ _ GET
参数来选择文件系统上的JS / CSS文件。
I have a PHP app that uses a $_GET
parameter to select JS/CSS files on the filesystem.
如果我拒绝所有请求,其中输入字符串包含 ./
, \
7位ASCII范围,这是否足以防止父目录遍历,当路径传递到PHP的底层(基于C)文件函数?
If I deny all requests in which the input string contains ./
, \
or a byte outside the visible 7-bit ASCII range, is this sufficient to prevent parent directory traversals when the path is passed to PHP's underlying (C-based) file functions?
我知道空字节漏洞,但是有任何其他替代/
I'm aware of null-byte vulnerabilities, but are there any other alternative/malformed character encodings tricks that might squeak by these checks?
这是基本的想法(不是生产代码):
Here's the basic idea (not production code):
$f = $_GET['f']; // e.g. "path/to/file.js"
// goal: select only unhidden CSS/JS files within DOC_ROOT
if (! preg_match('@^[\x20-\x7E]+$@', $f) // outside visible ASCII
|| false !== strpos($f, "./") // has ./
|| false !== strpos($f, "\\") // has \
|| 0 === strpos(basename($f), ".") // .isHiddenFile
|| ! preg_match('@\\.(css|js)$i@', $f) // not JS/CSS
|| ! is_file($_SERVER['DOCUMENT_ROOT'] . '/' . $f)) {
die();
}
$content = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/' . $f);
更新:我的问题是关于C文件系统函数如何解释任意ASCII序列(例如,如果有未记录的转义序列),但我意识到这可能是系统依赖的,实际上可能是不可回报的。
Update: My question is really about how the C filesystem functions interpret arbitrary ASCII sequences (e.g. if there are undocumented escape sequences), but I realize this is likely system-dependent and perhaps unanswerable in practice.
我的活动验证另外要求 realpath($ fullPath)
以 realpath($ _ SERVER ['DOCUMENT_ROOT'])
开头,确保文件在DOC_ROOT ,但是这个发布的目标是沟通 realpath()
(它在各种环境中被证明是不可靠的),同时仍然允许不同寻常,但有效的URI,例如 / 〜user / [my files] /file.plugin.js
。
My active validation additionally requires that realpath($fullPath)
start with realpath($_SERVER['DOCUMENT_ROOT'])
, ensuring that the file is within the DOC_ROOT, but a goal of this posting was to ditch realpath()
(it's proven unreliable in various environments) while still allowing unusual, but valid URIs like /~user/[my files]/file.plugin.js
.
推荐答案
,但将输入的 realpath
与已知根进行比较是我能想到的最佳解决方案。 Realpath将解析路径/文件系统的所有隐藏功能,包括符号链接。
You mention it yourself, but comparing realpath
of the input to a known root is the best solution I can think of. Realpath will resolve any hidden features of the path/filesystem, including symlinks.
这篇关于是ASCII“../&”唯一的字节序列,指示在PHP中的目录遍历?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!