任何人都可以确认,在我下面的代码片段中是否可能存在路径遍历漏洞?如果是,那么我应该做出哪些改变。
[RedirectingAction]
public ActionResult Download(string fileName)
{
byte[] fileBytes = System.IO.File.ReadAllBytes(Server.MapPath("~/ClientDocument/") + fileName);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
最佳答案
是的,它很脆弱。
为了证明这一点,我建立了一个名为 WebApplication1.sln
的新 MVC 项目。
以下请求下载解决方案文件:
http://localhost:56548/Home/Download?fileName=../../WebApplication1.sln
You can write a naive check:
private static readonly char[] InvalidFilenameChars = Path.GetInvalidFileNameChars();
public ActionResult Download(string fileName)
{
if (fileName.IndexOfAny(InvalidFilenameChars) >= 0)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var rootPath = Server.MapPath("~/ClientDocument/");
byte[] fileBytes = System.IO.File.ReadAllBytes(Path.Combine(rootPath, fileName));
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
这将检查
fileName
参数是一个有效的文件名。这不包括目录分隔符,因此它们不能将路径作为文件名传递。但是,完全安全的唯一方法是限制您的应用程序拥有的权限。仅授予它对您的虚拟目录的权限,而不授予其他权限。
关于c# - 我下面的代码中可能存在路径遍历漏洞吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37383143/