您的位置:首页 > 编程语言 > PHP开发

PHP安全编程:阻止文件名被操纵

2017-06-16 14:00 483 查看
在很多情形下会使用动态包含,此时目录名或文件名中的部分会保存在一个变量中。例如,你可以缓存你的部分动态页来降低你的数据库服务器的负担。

[php] view
plaincopy

<?php  

  

include "/cache/{$_GET['username']}.html";  

  

?>  

为了让这个漏洞更明显,示例中使用了$_GET。如果你使用了受污染数据时,这个漏洞同样存在。使用$_GET['username']是一个极端的例子,通过它可以把问题看得更清楚。

虽然上面的流程有其优点,但它同时为攻击者提供了一个可以自由选择缓存页的良机。例如,一个用户可以方便地通过编辑URL中的username的值来察看其他用户的缓存文件。事实上,攻击者可以通过简单的更改username的值为相应的文件名(不加扩展名)来察看/cache目录下的所有扩展名为.html的文件。

[php] view
plaincopy

<a href="http://example.org/index.php?username=filename" target="_blank">http://example.org/index.php?username=filename</a>  

尽管该程序限制了攻击者所操作的目录和文件名,但变更文件名并不是唯一的手段。攻击者可以创造性地达到在文件系统中进行跨越的目的,而去察看其他目录中的.html文件以发现敏感信息。这是因为可以在字串使用父目录的方式进行目录跨越:

[php] view
plaincopy

<a href="http://example.org/index.php?username=../admin/users" target="_blank">http://example.org/index.php?username=../admin/users</a>  

上面URL的运行结果如下:

[php] view
plaincopy

<?php  

  

include "/cache/../admin/users.html";  

  

?>  

此时,..意味着/cache的父目录,也就是根目录。这样上面的例子就等价于:

[php] view
plaincopy

<?php  

  

include "/admin/users.html";  

  

?>  

由于所有的文件都会在文件系统的根目录下,该流程就允许了一个攻击者能访问你服务器上所有的.html文件。

在某些平台上,攻击者还可以使用一个NULL来终止字符串,例如:http://example.org/index.php?username=../etc/passwd%00

这样就成功地绕开了.html文件扩展名的限制。当然,一味地去通过猜测攻击者的所有恶意攻击手段是不可能的,无论你在文件上加上多少控制,也不能排除风险。重要的是在动态包含时永远不要使用被污染数据。攻击手段不是一成不变的,但漏洞不会变化。只要通过过滤数据即可修复这个漏洞。

[php] view
plaincopy

<?php  

  

$clean = array();  

  

/* $_GET['filename'] is filtered and stored in $clean['filename']. */  

  

include "/path/to/{$clean['filename']}";  

  

?>  

如果你确认参数中只有文件名部分而没有路径信息时,另一个有效的技巧是通过使用basename()来进行数据的过滤:

[php] view
plaincopy

<?php  

  

$clean = array();  

  

if (basename($_GET['filename'] == $_GET['filename'])  

{  

    $clean['filename'] = $_GET['filename'];  

}  

  

include "/path/to/{$clean['filename']}";  

  

?>  

如果你允许有路径信息但想要在检测前把它化简,你可以使用realpath()函数:

[php] view
plaincopy

<?php  

  

$filename = realpath("/path/to/{$_GET['filename']}");  

  

?>  

通过上面程序处理得到的结果($filename)可以被用来确认是否位于/path/to目录下:

[php] view
plaincopy

<?php  

  

$pathinfo = pathinfo($filename);  

  

if ($pathinfo['dirname'] == '/path/to')  

{  

    /* $filename is within /path/to */.  

}  

  

?>  

如果检测不通过,你就应该把这个请求记录到攻击日志以备后查。这个在你把这个流程作为深度防范措施时特别重要,因为你要确定其它的安全手段失效的原因。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: