【发布时间】:2013-04-02 10:04:25
【问题描述】:
我创建了这个 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");
}
}
【问题讨论】:
-
一般来说,您应该拒绝无效输入,而不是尝试删除有害序列 - 考虑一下您的替换对
./.做了什么。还有一堆导致奇怪的模式,如空文件名、前导和尾随点和空格、控制字符、SHORTN~1.AMEs 和可能的保留文件名(com1等)。在文件名中使用输入很难正确,especially in Windows - 如果可以(正如 Jason 建议的那样)使用生成的 ID 作为本地磁盘上的文件名,那就更好了。 -
@bobince 那里有很棒的提示。这就是我问这个问题的原因,因为我知道会有更好的方法来解决这个问题,我只是在像这样的重要问题上寻找一些指导。
标签: c# asp.net security httphandler sanitize