【发布时间】:2012-10-21 04:34:41
【问题描述】:
找到此代码用于防止使用 HTTPModules 进行一些基本的 MySql 注入
public class SampleSqlInjectionScreeningModuleCS : IHttpModule
{
//Defines the set of characters that will be checked.
//You can add to this list, or remove items from this list, as appropriate for your site
public static string[] blackList = {"--",";--",";","/*","*/","@@","@",
"char","nchar","varchar","nvarchar",
"alter","begin","cast","create","cursor","declare","delete","drop","end","exec","execute",
"fetch","insert","kill","open",
"select", "sys","sysobjects","syscolumns",
"table","update"};
public void Dispose()
{
//no-op
}
//Tells ASP.NET that there is code to run during BeginRequest
public void Init(HttpApplication app)
{
app.BeginRequest += new EventHandler(app_BeginRequest);
}
//For each incoming request, check the query-string, form and cookie values for suspicious values.
void app_BeginRequest(object sender, EventArgs e)
{
HttpRequest Request = (sender as HttpApplication).Context.Request;
foreach (string key in Request.QueryString)
CheckInput(Request.QueryString[key]);
foreach (string key in Request.Form)
CheckInput(Request.Form[key]);
foreach (string key in Request.Cookies)
CheckInput(Request.Cookies[key].Value);
}
//The utility method that performs the blacklist comparisons
//You can change the error handling, and error redirect location to whatever makes sense for your site.
private void CheckInput(string parameter)
{
for (int i = 0; i < blackList.Length; i++)
{
if ((parameter.IndexOf(blackList[i], StringComparison.OrdinalIgnoreCase) >= 0))
{
//
//Handle the discovery of suspicious Sql characters here
//
HttpContext.Current.Response.Redirect("~/About.aspx"); //generic error page on your site
}
}
}
}
这是一个好的代码还是你认为我需要在黑名单中添加更多的东西,或者忘记这个并尝试另一种方法来防止注入?
【问题讨论】:
-
忘记这种方法,您可能会阻止有效内容。验证您的输入是否适合适当的类型,然后查看参数化查询。
-
为什么不直接为 SQL 查询使用参数,不用担心?
-
动态 SQL 是 99.999999999% 的邪恶。当您可以参数化输入并使用存储过程时,清理输入是不可靠的,并且会适得其反。
-
Bridge,整个系统已经围绕字符串中的命令构建,我们并没有真正考虑安全问题。所以我们没有时间重新全部重建,现在在其他项目中我们使用实体框架,更安全。
标签: c# mysql sql-injection