问题
I want to check if a file path is in current directory tree.
Suppose the parameter is given as js/script.js. My working directory (WD) is /home/user1/public_html/site
Now for current WD if someone supplies js/script.js I can simply check it by appending to the WD. It works for such normal path. But if anyone (may be an attacker) wants to pass ../../../../etc/password it'd be a problem.
I know it can be suppressed by removing the .. characters using some RegEx. And that will solve it for sure. But I want to know how can I create some sort of chrooted environment sot that whatever path/to/script is passed it will be searched under WD?
Edit: I am aware of http://php.net/chroot. it requires your app to run with root privileges.
回答1:
http://php.net/manual/en/function.realpath.php
$chroot = '/var/www/site/userdata/';
$basefolder = '/var/www/site/userdata/mine/';
$param = '../../../../etc/password';
$fullpath = realpath($basefolder . $param);
if (strpos($fullpath, $chroot) !== 0) {
// GOTCHA
}
来源:https://stackoverflow.com/questions/8518350/how-do-i-know-if-a-file-exists-in-the-current-directory-tree