asp.net core 中的路径遍历漏洞

时间:2021-03-31 05:04:00

标签: c# asp.net-core checkmarx secure-coding path-traversal

我已经尝试过这些解决方案

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);

请告诉我如何解决这个安全问题。

提前致谢。

1 个答案:

答案 0 :(得分:1)

路径遍历是关于你从用户输入构建路径,主要是你对用户输入有一个假设,例如,用户给你year和{{ 1}},然后返回正确的图像:index

遍历是用户给你一个相对部分,例如,对于$"App/Photos/${year}/${index}.png"-year,这样路径就是../private。< /p>

为了清理这个例子(你需要考虑更多的情况,不要做任何假设),你需要使用 App/private/1.png。在使用 filePath.Replace("..", "") 访问文件系统之前。

相关问题