//如果是.net的,可以在Global.asax.cs文件的Application_BeginRequest方法中加入如下代码,当提交的表单中包含sql的关键字时,将不允许提交:protected void Application_BeginRequest(Object sender, EventArgs e)
{
                        
StartProcessRequest();   
}#region SQL注入式攻击代码分析   
///    <summary>   
/// 处理用户提交的请求   
///    </summary>   
private void StartProcessRequest()   
{   
try   
{   
string getkeys = "";   
string sqlErrorPage = "index.aspx";//转向的错误提示页面   
if (System.Web.HttpContext.Current.Request.QueryString != null)   
{    for (int i = 0; i< System.Web.HttpContext.Current.Request.QueryString.Count; i++)   
{   
getkeys = System.Web.HttpContext.Current.Request.QueryString.Keys[i];   
if (!ProcessSqlStr(System.Web.HttpContext.Current.Request.QueryString[getkeys]))   
{   
System.Web.HttpContext.Current.Response.Redirect(sqlErrorPage);   
System.Web.HttpContext.Current.Response.End();   
}   
}   
}   
if (System.Web.HttpContext.Current.Request.Form != null)   
{   
for (int i = 0; i< System.Web.HttpContext.Current.Request.Form.Count; i++)   
{   
getkeys = System.Web.HttpContext.Current.Request.Form.Keys[i];   
if (getkeys == "__VIEWSTATE") continue;   
if (!ProcessSqlStr(System.Web.HttpContext.Current.Request.Form[getkeys]))   
{   
System.Web.HttpContext.Current.Response.Redirect(sqlErrorPage);   
System.Web.HttpContext.Current.Response.End();   
}   
}   
}   
}   
catch   
{   
// 错误处理: 处理用户提交信息!   
}   
}   
///    <summary>   
/// 分析用户请求是否正常   
///    </summary>   
///    <param name="Str">传入用户提交数据   </param>   
///    <returns>返回是否含有SQL注入式攻击代码   </returns>   
private bool ProcessSqlStr(string Str)   
{   
bool ReturnValue = true;   
try   
{   
if (Str.Trim() != "")   
{   
string SqlStr = "and|exec|insert|select|delete|update|count|*|chr|mid|master|truncate|char|declare"; //提交表单时不允许包含这些关键字,楼主可以根据需要进行删减。   string[] anySqlStr = SqlStr.Split("|".ToCharArray());   
foreach (string ss in anySqlStr)   
{   
if (Str.ToLower().IndexOf(ss) >= 0)   
{   
ReturnValue = false;   
break;   
}   
}   
}   
}   
catch   
{   
ReturnValue = false;   
}   
return ReturnValue;   
}   
#endregion

解决方案 »

  1.   

    在SQL Server 2005的示例数据库AdventureDB中有一个例子,用数据库触发器监控对数据库的查询\插入\更新.
      

  2.   

    在SQL里面处理太不灵活,而且麻烦。工作量大
      

  3.   

    1,治本,程序一个个的改,一定要注意参数的处理。参数不一定是 request, 也可能是cookies等等。
    只要一切从外部获取或读入的地方都要注意。2,治标,限定数据库用户的权限,减小危害范围。你希望的通过iis日志或监视来找到别人注入点的方式,有可取之处,但也非长远之计。今天你补了一个,明天或者还有另一个,要安全就要治本。
    如果很懒,或者说确实工作量大,一个个改不可能(至少短期内不可能)可以找个注入检测工具,扫一下你的网站,可以一定程度上减少注入点。治本的方法,网上说的也很多,做法也简单,就是如果文件多,那确实比较烦琐。
    a,对精准类型,判断变量类型,比如isdate,isnumeric等。
    b,对非精准类型,比如varchar,text,char等参数,将'转义。
    c,对一些特定性参数,自己处理,比如要传入 年-月, 你自己可在参数后加上 -1 再用 isdate检测(当然,这只是简化参数合法性判断的一些技巧)
    d,若是asp.net,尽可以以传参方式执行。