如何确保文件路径在给定的子目录中? [英] How do I make sure a file path is within a given subdirectory?
问题描述
我想确保通过查询字符串设置的文件路径不会超出所需的子目录.现在,我正在检查:
I want to make sure a file path set via query string does not go outside of the desired subdirectory. Right now, I am checking that:
- 路径不以
/
"开头,以防止用户给出绝对路径. - 路径不包含
..
",以防止用户提供所需子目录之外的路径. - 路径不包含
:
",防止使用url(即http://
"、ftp://
"等).我是否应该在 Windows 服务器上运行此脚本(不太可能),这也将阻止以驱动器说明符(即C:\
")开头的绝对路径.注意:我知道冒号是 Unix 文件名中的有效字符,但我永远不会在文件名中使用它. - 路径不以
\
"开头.以防万一我改变主意在 Windows 服务器上运行,这会阻止指定 Windows 网络路径(即\\someserver\someshare
").同样,我知道反斜杠是一个有效的 Unix 文件名字符,但我也不会在任何文件名中使用它.
- The path does not start with "
/
", to prevent the user from giving an absolute path. - The path does not contain "
..
", to prevent the user from giving a path that is outside of the desired subdirectory. - The path does not contain "
:
", to prevent the use of a url (i.e. "http://
", "ftp://
", etc.). Should I ever run this script on a Windows server (not likely), this will also prevent absolute paths beginning with a drive specifier (i.e. "C:\
"). Note: I'm aware that a colon is a valid character in a Unix filenames, but I will never be using it in a filename. - The path does not start with "
\
". Just in case I change my mind about running on a Windows server, this prevents Windows network paths from being specified (i.e. "\\someserver\someshare
"). Again, I'm aware that a backslash is a valid Unix filename character, but I also won't be using it in any filenames.
这些检查是否足够?
背景
我有一个 PHP 脚本,它采用(通过查询字符串)要向用户显示的示例源文件的路径.所以我可能会给他们一个链接,比如view_sample.php?path=accounting_app/report_view.php
"或view_sample.php?path=ajax_demo/get_info.js
".
I have a PHP script that takes (via query string) the path to a sample source file to be shown to a user. So I might give them a link like "view_sample.php?path=accounting_app/report_view.php
" or "view_sample.php?path=ajax_demo/get_info.js
".
脚本基本上是这样的:
$path = $_GET['path'];
if(path_is_valid($path) && is_file("sample/$path"))
{
header('Content-Type: text/plain');
readfile("sample/$path");
}
我担心恶意用户会看到该 url 并尝试执行诸如view_sample.php?path=../../database/connection_info.php
"之类的操作并获得对一个不在示例"目录中的文件.
My concern is that a malicious user would see the url and try to do something like "view_sample.php?path=../../database/connection_info.php
" and gain access to a file which is not in the "sample" directory.
我上面定义的四项检查(将在 path_is_valid()
函数中实现)是否足以锁定恶意用户?(另外,我认为检查 1、3 和 4 基本上无关紧要,因为我预先设置了相对路径,但如果我不这样做,检查就足够了吗?)
Are the four checks I defined above (which would be implemented in the path_is_valid()
function) sufficient to lock out a malicious user? (Also, I think checks 1, 3, and 4 are basically irrelevant since I am prepending a relative path, but if I didn't do this would the checks be sufficient?)
推荐答案
致电
$path = realpath("sample/$path");
然后检查生成的路径是否以您期望的目录开头.
Then check that the resulting path starts with the directory you're expecting.
这篇关于如何确保文件路径在给定的子目录中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!