gpt4 book ai didi

c# - 清理字符串以防止相对 URI 路径

转载 作者:太空狗 更新时间:2023-10-29 21:05:11 24 4
gpt4 key购买 nike

我创建了这个 HTTP 处理程序来更新本地 SQL Express 数据库中的信息。

我意识到用户可以使用相对 URI 路径“/../../file.zip”作为查询字符串,并且能够下载限制区域之外的文件。

该站点尚未上线,因此目前还不是安全问题,但我真的很想防止此类事情发生。

我添加了一个简单的 string.replace 行,用于从输入查询中删除任何“..”。

我还应该在这里做些什么来确保这一点吗?

public void ProcessRequest(HttpContext context)
{
string filesPath = "C:/Downloads/";
string fileName = context.Request.QueryString["filename"];
fileName = fileName.Replace("'", "''").Replace("..", "").Replace("/", "").Replace("\\", "");

if (!string.IsNullOrEmpty(fileName) && File.Exists(filesPath + fileName))
{
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", fileName));
context.Response.WriteFile(filesPath + fileName);
//Do work to update SQL database here
}
else
{
context.Response.ContentType = "text/plain";
context.Response.Write(filesPath + fileName + " Invalid filename");
}
}

最佳答案

我通常使用这个简单的代码来检查这个问题:

(我是直接打出来的,所以可能编译不了,只是给大家一个思路)

private string getPath(string basePath, string fileName)
{
var fullPath = System.IO.Path.GetFullPath(System.IO.Path.Combine(basePath, fileName));
if (fullPath.StartsWith(basePath))
return fullPath;
return null;
}

目标是使用 Path.GetFullPath。此方法会将任何/../等转换为完整路径。然后检查返回的路径是否在允许的目录中。
请注意,此方法可能会返回与预期略有不同的路径,请阅读 MSDN详细解释

关于c# - 清理字符串以防止相对 URI 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15927972/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com