Rik*_*i B 6 c# asp.net security httphandler sanitize
我创建了这个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");
}
}
Run Code Online (Sandbox Code Playgroud)
Fab*_*ske 10
我通常使用这个简单的代码来检查这个问题:
(我直接输入它可能无法编译,只是为了给你这个想法)
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;
}
Run Code Online (Sandbox Code Playgroud)
目标是使用Path.GetFullPath.此方法将任何/../ etc转换为完整路径.然后检查返回的路径是否在允许的目录中.
请注意,此方法可能会返回与预期不同的路径,请阅读MSDN以获取详细说明