我的下面的代码中是否可以使用路径遍历漏洞?(Is Path Traversal Vulnerabilities possible in my below code?)

编程入门 行业动态 更新时间:2024-10-25 16:26:49
我的下面的代码中是否可以使用路径遍历漏洞?(Is Path Traversal Vulnerabilities possible in my below code?)

任何人都可以确认,在我的下面的代码片段中是否可以使用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.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); }

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.

更多推荐

本文发布于:2023-08-06 18:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1453782.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:遍历   可以使用   路径   漏洞   代码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!