任何人都可以确认,在我的下面的代码片段中是否可以使用Path Traversal Vulnerabilities? 如果是,那么我应该做出哪些改变。
[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); }Can anyone please confirm, is Path Traversal Vulnerabilities is possible in my below code snippet? if yes then what changes I should make.
[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你可以写一个天真的检查:
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参数是否是有效的文件名。 这会排除目录分隔符,因此它们不能将路径作为文件名传递。
但是, 完全安全的唯一方法是限制应用程序的权限。 仅授予您对虚拟目录的权限,而不授予其他任何权限。
Yes, it is vulnerable.
Just to prove it, I set up a new MVC project called WebApplication1.sln
The following request downloads the solution file:
http://localhost:56548/Home/Download?fileName=../../WebApplication1.slnYou 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); }Which will check that the fileName argument is a valid file name. This excludes directory separator characters, so they cannot pass a path as a filename.
However, the only way to be completely safe, is to restrict the permissions your application has. Only grant it permission to your virtual directory, and nothing else.
更多推荐
发布评论