readfile漏洞如何避免

时间:2015-12-14 23:52:17

标签: php security curl readfile

我听说函数readfile作为php函数很容易受到攻击,所以我禁用了它,我有一个脚本来下载文件,它使用了这个函数:

$url = strip_tags($_GET['path']);

$fileName = strip_tags($_GET['file']);

header ("Content-type: octet/stream");
header ("Content-disposition: attachment; filename=".$fileName.";");
header ("Content-Length: ".filesize($url.$fileName));
readfile($url.$fileName);
exit;

如果它容易受到攻击,是否有办法避免它或用其他功能替换它,我尝试了cURL,但是下载失败,我来自this link

使用cURL:

<?php
set_time_limit(0);
$fp = fopen (dirname(__FILE__) . '/localfile.tmp', 'w+');//This is the file where we save the    information
$ch = curl_init(str_replace(" ","%20",$url));//Here is the file we are downloading, replace spaces with %20
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_FILE, $fp); // write curl response to file
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch); // get curl response
curl_close($ch);
fclose($fp);
?>

提前致谢

1 个答案:

答案 0 :(得分:1)

readfile本身并不容易受到攻击。仅当您将未经过清理的数据作为参数传递给它时,才会给出可能的攻击向量。

我的意思是$url。您的示例不会显示网址的来源。

让我们使用最坏的情况并假设$ url来自$ _POST,例如

$url = $_POST['url'];并将其与一个很好的Path Traversal攻击(https://www.owasp.org/index.php/Path_Traversal)结合起来。

您可以限制对当前目录(__DIR__)的文件访问权限。 或者使用realpath()并排除/限制readfile可以执行的操作。

参考:How to avoid path traversal attacks

好的,我已经测试了你的cURL例子。它有效!

<?php

$url = 'http://www.thetimes.co.uk/tto/news/rss';

set_time_limit(0);
$fp = fopen (dirname(__FILE__) . '/localfile.tmp', 'w+');//This is the file where we save the    information
$ch = curl_init(str_replace(" ","%20",$url));//Here is the file we are downloading, replace spaces with %20
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_FILE, $fp); // write curl response to file
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch); // get curl response
curl_close($ch);
fclose($fp);

这会下载新闻/ RSS Feed网址的内容,并将其保存到localfile.tmp