基于PHP.Mysql,apache复现文件下载漏洞并修复
时间: 2024-03-27 22:37:57 浏览: 12
文件下载漏洞是指在网站中,用户可以通过构造恶意请求,访问到本应该禁止访问的文件,从而导致敏感信息泄露的漏洞。下面是一个基于PHP.Mysql,apache的文件下载漏洞示例:
```php
<?php
// 从GET参数中获取要下载的文件名
$file = $_GET['file'];
// 拼接文件路径
$filepath = "/var/www/html/uploads/".$file;
// 下载文件
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($filepath));
header('Content-Length: ' . filesize($filepath));
readfile($filepath);
?>
```
上面的代码中,用户可以通过构造恶意请求,访问到服务器上/uploads目录下的任意文件。攻击者只需要将`$_GET['file']`参数设置为`../../etc/passwd`,就可以下载服务器上的/etc/passwd文件,并获取敏感信息。
为了修复这个漏洞,我们需要对用户输入的数据进行过滤和验证,确保其符合预期的格式和内容。比如,可以使用PHP的`realpath`函数来获取文件的真实路径,以避免恶意请求访问到非法文件:
```php
<?php
// 从GET参数中获取要下载的文件名
$file = $_GET['file'];
// 拼接文件路径
$filepath = "/var/www/html/uploads/".basename($file);
// 判断文件是否存在
if (file_exists($filepath)) {
// 获取文件的真实路径
$realpath = realpath($filepath);
if (substr($realpath, 0, strlen("/var/www/html/uploads/")) === "/var/www/html/uploads/") {
// 下载文件
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($filepath));
header('Content-Length: ' . filesize($filepath));
readfile($filepath);
} else {
echo "无法访问非法文件!";
}
} else {
echo "文件不存在!";
}
?>
```
通过使用`realpath`函数获取文件的真实路径,并判断是否在/uploads目录下,可以避免恶意请求访问到非法文件,从而修复文件下载漏洞。