我已经尝试过这些解决方案
Does my code prevent directory traversal in C#?
Is Path Traversal Vulnerabilities possible in my below code?
How to prevent Path Traversal in .NET
How to avoid Directory Traversal in my code
但是,Checkmarx 扫描仍然存在安全问题,下面是代码
public FileContentResult GetImageFromFilePath(string filePath)
{
byte[] image = null;
if (!string.IsNullOrEmpty(filePath))
{
image = System.IO.File.ReadAllBytes(filePath);
}
if (image == null)
return null;
return File(image, "image/jpeg");
}
问题出在这行代码 image = System.IO.File.ReadAllBytes(filePath);
请让我知道如何解决这个安全问题。
提前致谢。
最佳答案
Path Traversal 是关于你从用户输入构建路径,主要是你对用户输入有一个假设,例如,用户给你 year
和index
,然后返回正确的图像:$"App/Photos/${year}/${index}.png"
。
遍历就是用户给你一个相对的部分,比如对于year
- ../private
这样路径将是 App/private/1.png
。
为了净化这个例子(你需要考虑更多的情况,不要做任何假设),你需要使用 filePath.Replace("..", "")
。在使用 filePath
访问文件系统之前。
关于c# - asp.net core 路径遍历漏洞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66881943/