针对sqll注入,对现有程序进行修改。 主要是过滤关键字! 修改简单 将原来取数据的Request.Form[key]替换为YourCompanyRequest.Form[key] 同样Request.QueryString[key]替换为TxYourCompanyRequest.QueryString[key]即可 using System; 2using System.Collections.Specialized; 3using System.Collections.Generic; 4using System.Text.RegularExpressions; 5using System.Web; 6 7namespace CommonFun 8{ 9 public static class YourCompanyRequest 10 { 11 12 public static NameValueCollection Form 13 { 14 get 15 { 16 NameValueCollection form = new NameValueCollection(); 17 foreach (string key in HttpContext.Current.Request.Form.AllKeys) 18 { 19 form.Add(key, FilteStringForSqlInject(HttpContext.Current.Request.Form[key])); 20 } 21 return form; 22 } 23 24 } 25 26 public static NameValueCollection QueryString 27 { 28 get 29 { 30 NameValueCollection queryString = new NameValueCollection(); 31 foreach (string key in HttpContext.Current.Request.QueryString.AllKeys) 32 { 33 queryString.Add(key, FilteStringForSqlInject(HttpContext.Current.Request.QueryString[key])); 34 } 35 return queryString; 36 } 37 } 38 39 /**
40 /// 替换sql语句中的有问题符号 41 /// 42 public static string ChkSQL(string str) 43 { 44 string str2; 45 46 if (str == null) 47 { 48 str2 = ""; 49 } 50 else 51 { 52 str = str.Replace("'", "''"); 53 str2 = str; 54 } 55 return str2; 56 } 57 58 /**
59 /// 改正sql语句中的转义字符 60 /// 61 public static string mashSQL(string str) 62 { 63 string str2; 64 65 if (str == null) 66 { 67 str2 = ""; 68 } 69 else 70 { 71 str = str.Replace("/'", "'"); 72 str2 = str; 73 } 74 return str2; 75 } 76 77 /**
78 /// 检测是否有Sql危险字符 79 /// 80 ///
要判断字符串 81 ///
判断结果
82 public static bool IsSafeSqlString(string str) 83 { 84 85 return !Regex.IsMatch(str, @"[-|;|,|//|/(|/)|/[|/]|/}|/{|%|@|/*|!|/']"); 86 } 87 88 /**
89 /// 检测是否有危险的可能用于链接的字符串 90 /// 91 ///
要判断字符串 92 ///
判断结果
93 public static bool IsSafeUserInfoString(string str) 94 { 95 return !Regex.IsMatch(str, @"^/s*$|^c://con//con$|[%,/*" + "/"" + @"/s/t/</>/&]|游客|^Guest"); 96 } 97 98 public static string FilteStringForSqlInject(string str) 99 { 100 string s = str; 101 102 if (!IsSafeSqlString(s)) 103 { 104 s = ChkSQL(s); 105 s = ReplaceForSqlKeyWords(s); 106 } 107 return s; 108 } 109 110 public static string ReplaceForSqlKeyWords(string str) 111 { 112 str = str.ToLower(); 113 str = str.Replace("select", "select"); 114 str = str.Replace("exec", "exec"); 115 str = str.Replace("execute", "execute"); 116 str = str.Replace("update", "update"); 117 str = str.Replace("insert", "insert"); 118 str = str.Replace("declare", "declare"); 119 str = str.Replace("cursor", "cursor"); 120 str = str.Replace("sysobjects", "sysobjects"); 121 return str; 122 } 123 } 124}
防sql注入!
最新推荐文章于 2024-11-08 14:07:13 发布