您的位置:首页 > 数据库

C# 检查字符串,防SQL注入攻击

2008-05-06 16:17 411 查看
SQL注入攻击如下,CheckParams函数,接收参数任意,如参数中有字符串,则对字符串进行检查,如参数中有集合(如Array之类,总之是实现了ICollection的),则对集合中的字符串元素进行检查.大家可根据具体情况来定要过滤的字符,我这个例子里暂定为=号和'号,实际上我个人认为,过滤了这两个,似乎要进行SQL注入就已经比较困难了,当然,我对SQL是菜鸟,欢迎高手指正,谢谢.
方法一
bool CheckParams(params object[] args)
{ string[] Lawlesses={"=","'"};
if(Lawlesses==null||Lawlesses.Length<=0)return true; //构造正则表达式,
例:Lawlesses是=号和'号,则正则表达式为 .*[=}'].* (正则表达式相关内容请见MSDN) 另外,由于我是想做通用而且容易修改的函数,所以多了一步由字符数组到正则表达式,实际使用中,直接写正则表达式亦可;
string str_Regex=".*[";
for(int i=0;i< Lawlesses.Length-1;i++)
str_Regex+=Lawlesses[i]+"|";
str_Regex+=Lawlesses[Lawlesses.Length-1]+"].*";
// foreach(object arg in args)
{ if(arg is string)//如果是字符串,直接检查
{ if(Regex.Matches(arg.ToString(),str_Regex).Count>0)
return false; }
else if(arg is ICollection)//如果是一个集合,则检查集合内元素是否字符串,是字符串,就进行检查 { foreach(object obj in (ICollection)arg)
{ if(obj is string)
{ if(Regex.Matches(obj.ToString(),str_Regex).Count>0)
return false;
}
}
}
}
return true;}
方法二
一.如果参数全为数字:
// 检查字符串是否全为数字
public static bool IsNum(string Str)
{
bool blResult = true;
if (Str == "")
blResult = false;
else
{
foreach (char Char in Str)
{
if (!Char.IsNumber(Char))
{
blResult = false;
break;
}
}
if (blResult)
if (int.Parse(Str) == 0)
blResult = false;
}
return blResult;
}http://www.pconcool.com

应用:
string Topicid = Request.QueryString["Topicid"];
if (!IsNum(Topicid))
Server.Transfer("Error.aspx?ErrID=404");

二.如果参数为文本.

// Html转换
public static string htmlstr(string chr)
{
if(chr==null)
return "";
chr=chr.Replace("<","<");
chr=chr.Replace(">",">");
chr=chr.Replace("/n","<br>");
chr=chr.Replace("/"",""");
chr=chr.Replace("'","'");
chr=chr.Replace(" ","?");
chr=chr.Replace("/r","");
return(chr);
}
应用:string strClass = htmlstr(Request.QueryString["ClassName"]);

方法三:.net整站防sql注入

将下面的代码加入到Global.asax文件中:
/// <summary>
/// 防止SQL注入
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void Application_BeginRequest(Object sender, EventArgs e)
{
StartProcessRequest();

}

#region SQL注入式攻击代码分析
/// <summary>
/// 处理用户提交的请求
/// </summary>
private void StartProcessRequest()
{
try
{
string getkeys = "";
string sqlErrorPage = "error.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('.');
foreach (string ss in anySqlStr)
{
if (Str.ToLower().IndexOf(ss) >= 0)
{
ReturnValue = false;
break;
}
}
}
}
catch
{
ReturnValue = false;
}
return ReturnValue;
}
#endregion

个人网站:欢迎交流 www.tripbee.cn
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: