winform防止sqlserver注入_C#验证防止阻断Sql注入代码

C#验证是否存在Sql注入代码

构造SQL的注入关键字符

//QueryString 数据检测GET恶意数据

private const string StrKeyWord = @".*(select|insert|delete|from|count(|drop table|update|truncate|asc(|mid(|char(|xp_cmdshell|exec master|netlocalgroup administrators|:|net user|""|or|and).*";

private const string StrRegex = @"[-|;|,|/|(|)|[|]|}|{|%|@|*|!|']";

///

/// 获取Post的数据

///

public static string ValidUrlPostData()

{

bool result = false;

string res = string.Empty;

for (int i = 0; i < HttpContext.Current.Request.Form.Count; i++)

{

result = ValidData(HttpContext.Current.Request.Form[i].ToString());

if (result)

{

res = "检测出POST恶意数据: 【" + HttpContext.Current.Request.Form[i].ToString() + "】 URL: 【" + HttpContext.Current.Request.RawUrl + "】来源: 【" + HttpContext.Current.Request.UserHostAddress + "】";

break;

}//如果检测存在漏洞

}

return res;

}

///

/// 获取QueryString中的数据

///

public static string ValidUrlGetData()

{

bool result = false;

string res = string.Empty;

for (int i = 0; i < HttpContext.Current.Request.QueryString.Count; i++)

{

result = ValidData(HttpContext.Current.Request.QueryString[i].ToString());

if (result)

{

res = "检测出GET恶意数据: 【" + HttpContext.Current.Request.QueryString[i].ToString() + "】 URL: 【" + HttpContext.Current.Request.RawUrl + "】来源: 【" + HttpContext.Current.Request.UserHostAddress + "】";

break;

}//如果检测存在漏洞

}

return res;

}

///

/// 验证是否存在注入代码

///

///

public static bool ValidData(string inputData)

{

//里面定义恶意字符集合

//验证inputData是否包含恶意集合

if (Regex.IsMatch(inputData.ToLower(), GetRegexString()))

{

return true;

}

else

{

return false;

}

}

///

/// 获取正则表达式

///

///

///

private static string GetRegexString()

{

//构造SQL的注入关键字符

string[] strBadChar =

{

"and"

,"exec"

,"insert"

,"select"

,"delete"

,"update"

,"count"

,"from"

,"drop"

,"asc"

,"char"

,"or"

,"%"

,";"

,":"

,"\'"

,"\""

,"-"

,"chr"

,"mid"

,"master"

,"truncate"

,"char"

,"declare"

,"SiteName"

,"net user"

,"xp_cmdshell"

,"/add"

,"exec master.dbo.xp_cmdshell"

,"net localgroup administrators"

};

//构造正则表达式

string str_Regex = ".*(";

for (int i = 0; i < strBadChar.Length - 1; i++)

{

str_Regex += strBadChar[i] + "|";

}

str_Regex += strBadChar[strBadChar.Length - 1] + ").*";

return str_Regex;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值