I am implementing a simple directory listing script in PHP.
我在PHP中实现了一个简单的目录列表脚本。
I want to ensure that the passed path is safe before opening directory handles and echo
ing the results willy-nilly.
我想确保传递的路径是安全的,然后打开目录句柄并不断回应结果。
$f = $_GET["f"];
if(! $f) {
$f = "/";
}
// make sure $f is safe
$farr = explode("/",$f);
$unsafe = false;
foreach($farr as $farre) {
// protect against directory traversal
if(strpos($farre,"..") != false) {
$unsafe = true;
break;
}
if(end($farr) != $farre) {
// make sure no dots are present (except after the last slash in the file path)
if(strpos($farre,".") != false) {
$unsafe = true;
break;
}
}
}
Is this enough to make sure a path sent by the user is safe, or are there other things I should do to protected against attack?
这是否足以确保用户发送的路径是安全的,还是我应该采取其他措施来防止攻击?
1 个解决方案
#1
It may be that realpath()
is helpful to you.
可能是realpath()对你有帮助。
realpath()
expands all symbolic links and resolves references to'/./'
,'/../'
and extra'/'
characters in the input path, and returns the canonicalized absolute pathname.realpath()展开所有符号链接并解析对输入路径中'/./','/../'和额外'/'字符的引用,并返回规范化的绝对路径名。
However, this function assumes that the path in question actually exists. It will not perform canonization for a non-existing path. In this case FALSE is returned.
但是,此函数假定所讨论的路径实际存在。它不会对不存在的路径执行canonization。在这种情况下,返回FALSE。
#1
It may be that realpath()
is helpful to you.
可能是realpath()对你有帮助。
realpath()
expands all symbolic links and resolves references to'/./'
,'/../'
and extra'/'
characters in the input path, and returns the canonicalized absolute pathname.realpath()展开所有符号链接并解析对输入路径中'/./','/../'和额外'/'字符的引用,并返回规范化的绝对路径名。
However, this function assumes that the path in question actually exists. It will not perform canonization for a non-existing path. In this case FALSE is returned.
但是,此函数假定所讨论的路径实际存在。它不会对不存在的路径执行canonization。在这种情况下,返回FALSE。