PHP安全根

Jam*_*mes 6 php security root

我的朋友在我的脚本中发现了一个问题,它提供了对根文件的访问.

这个url给出了passwd文件:

http://site.com/attachment.php?file=../../../../../../etc/passwd
Run Code Online (Sandbox Code Playgroud)

如何逃脱这个安全漏洞?

Sta*_*arx 14

不要使用URL String下载文件....定义唯一ID来表示文件,而不是路径.

您可能已经看到了这样的下载http://www.mysite.com/download.php?id=23423,使用此ID,从数据库中取出文件名和路径,然后下载它.


You*_*nse 4

有几种不同的解决方案。如果只能有一个文件名,则可以使用 basename() 解决方案。

但是,如果可以是路径,则需要更复杂的解决方案

//assume current directory, but can be set anything. Absolute path of course
$basedir   = dirname(__FILE__);
//assume our files are below document root. 
//Otherwise use it's root dir instead of DOCUMENT_ROOT
$filename  = realpath($_SERVER['DOCUMENT_ROOT'].$_GET['file']);
if (substr($filename,0,strlen($basedir)) !== $basedir) {
  header ("HTTP/1.0 403 Forbidden"); 
  exit; 
}
Run Code Online (Sandbox Code Playgroud)

还有一个有用的 PHP 配置选项open_basedir