1#region 防止sql注入式攻击(可用于UI层控制)
  2
  3/// 
  4/// 判断字符串中是否有SQL攻击代码
  5/// 
  6/// 传入用户提交数据
  7/// true-安全;false-有注入攻击现有;
  8public bool ProcessSqlStr(string inputString)
  9{
 10    string SqlStr = @"and|or|exec|execute|insert|select|delete|update|alter|create|drop|count|\*|chr|char|asc|mid|substring|master|truncate|declare|xp_cmdshell|restore|backup|net +user|net +localgroup +administrators";
 11    try
 12    {
 13        if ((inputString != null) && (inputString != String.Empty))
 14        {
 15            string str_Regex = @"\b(" + SqlStr + @")\b";
 16
 17            Regex Regex = new Regex(str_Regex, RegexOptions.IgnoreCase);
 18            //string s = Regex.Match(inputString).Value; 
 19            if (true == Regex.IsMatch(inputString))
 20                return false;
 21
 22        }
 23    }
 24    catch
 25    {
 26        return false;
 27    }
 28    return true;
 29}
 30
 31
 32/// 
 33/// 处理用户提交的请求,校验sql注入式攻击,在页面装置时候运行
 34/// System.Configuration.ConfigurationSettings.AppSettings["ErrorPage"].ToString(); 为用户自定义错误页面提示地址,
 35/// 在Web.Config文件时里面添加一个 ErrorPage 即可
 36/// 
 37///     
 38/// 
 39public void ProcessRequest()
 40{
 41    try
 42    {
 43        string getkeys = "";
 44        string sqlErrorPage = System.Configuration.ConfigurationSettings.AppSettings["ErrorPage"].ToString();
 45        if (System.Web.HttpContext.Current.Request.QueryString != null)
 46        {
 47
 48            for (int i = 0; i < System.Web.HttpContext.Current.Request.QueryString.Count; i++)
 49            {
 50                getkeys = System.Web.HttpContext.Current.Request.QueryString.Keys[i];
 51                if (!ProcessSqlStr(System.Web.HttpContext.Current.Request.QueryString[getkeys]))
 52                {
 53                    System.Web.HttpContext.Current.Response.Redirect(sqlErrorPage + "?errmsg=" + getkeys + "有SQL攻击嫌疑!");
 54                    System.Web.HttpContext.Current.Response.End();
 55                }
 56            }
 57        }
 58        if (System.Web.HttpContext.Current.Request.Form != null)
 59        {
 60            for (int i = 0; i < System.Web.HttpContext.Current.Request.Form.Count; i++)
 61            {
 62                getkeys = System.Web.HttpContext.Current.Request.Form.Keys[i];
 63                if (!ProcessSqlStr(System.Web.HttpContext.Current.Request.Form[getkeys]))
 64                {
 65                    System.Web.HttpContext.Current.Response.Redirect(sqlErrorPage + "?errmsg=" + getkeys + "有SQL攻击嫌疑!");
 66                    System.Web.HttpContext.Current.Response.End();
 67                }
 68            }
 69        }
 70    }
 71    catch
 72    {
 73        // 错误处理: 处理用户提交信息!
 74    }
 75}
 76#endregion
 77
 78
 79
 80
 81#region 转换sql代码(也防止sql注入式攻击,可以用于业务逻辑层,但要求UI层输入数据时候进行解码)
 82/// 
 83/// 提取字符固定长度
 84/// 
 85/// 
 86/// 
 87/// 
 88public string CheckStringLength(string inputString, Int32 maxLength)
 89{
 90    if ((inputString != null) && (inputString != String.Empty))
 91    {
 92        inputString = inputString.Trim();
 93
 94        if (inputString.Length > maxLength)
 95            inputString = inputString.Substring(0, maxLength);
 96    }
 97    return inputString;
 98}
 99
100/// 
101/// 将输入字符串中的sql敏感字,替换成"[敏感字]",要求输出时,替换回来
102/// 
103/// 
104/// 
105public string MyEncodeInputString(string inputString)
106{
107    //要替换的敏感字
108    string SqlStr = @"and|or|exec|execute|insert|select|delete|update|alter|create|drop|count|\*|chr|char|asc|mid|substring|master|truncate|declare|xp_cmdshell|restore|backup|net +user|net +localgroup +administrators";
109    try
110    {
111        if ((inputString != null) && (inputString != String.Empty))
112        {
113            string str_Regex = @"\b(" + SqlStr + @")\b";
114
115            Regex Regex = new Regex(str_Regex, RegexOptions.IgnoreCase);
116            //string s = Regex.Match(inputString).Value; 
117            MatchCollection matches = Regex.Matches(inputString);
118            for (int i = 0; i < matches.Count; i++)
119                inputString = inputString.Replace(matches[i].Value, "[" + matches[i].Value + "]");
120
121        }
122    }
123    catch
124    {
125        return "";
126    }
127    return inputString;
128
129}
130
131/// 
132/// 将已经替换成的"[敏感字]",转换回来为"敏感字"
133/// 
134/// 
135/// 
136public string MyDecodeOutputString(string outputstring)
137{
138    //要替换的敏感字
139    string SqlStr = @"and|or|exec|execute|insert|select|delete|update|alter|create|drop|count|\*|chr|char|asc|mid|substring|master|truncate|declare|xp_cmdshell|restore|backup|net +user|net +localgroup +administrators";
140    try
141    {
142        if ((outputstring != null) && (outputstring != String.Empty))
143        {
144            string str_Regex = @"\[\b(" + SqlStr + @")\b\]";
145            Regex Regex = new Regex(str_Regex, RegexOptions.IgnoreCase);
146            MatchCollection matches = Regex.Matches(outputstring);
147            for (int i = 0; i < matches.Count; i++)
148                outputstring = outputstring.Replace(matches[i].Value, matches[i].Value.Substring(1, matches[i].Value.Length - 2));
149
150        }
151    }
152    catch
153    {
154        return "";
155    }
156    return outputstring;
157}
158#endregion

我们的解决方式是:
1、首先在UI录入时,要控制数据的类型和长度、防止SQL注入式攻击,系统提供检测注入式攻击的函数,一旦检测出注入式攻击,该数据即不能提交;
2、业务逻辑层控制,通过在方法内部将SQL关键字用一定的方法屏蔽掉,然后检查数据长度,保证提交SQL时,不会有SQL数据库注入式攻击代码;但是这样处理后,要求UI输出时将屏蔽的字符还原。因此系统提供屏蔽字符 的函数和还原字符的函数。
3、在数据访问层,绝大多数采用存储过程访问数据,调用时以存储过程参数的方式访问,也会很好的防止注入式攻击。

浅谈C#.NET防止SQL注入式攻击的更多相关文章

  1. 【转】浅谈常用的几种web攻击方式

    浅谈常用的几种web攻击方式 一.Dos攻击(Denial of Service attack) 是一种针对服务器的能够让服务器呈现静止状态的攻击方式.有时候也加服务停止攻击或拒绝服务攻击.其原理就是 ...

  2. 什么是SQL注入式攻击

    什么是SQL注入式攻击? 所谓SQL注入式攻击,就是攻击者把SQL命令插入到Web表单的输入域或页面请求的查询字符串,欺骗服务器执行恶意的SQL命令.在某些表单中,用户输入的内容直接用来构造(或者影响 ...

  3. SQL注入式攻击

    百度百科:http://baike.baidu.com/link?url=GQbJ2amTzTahZA7XJSBDLYYkN3waQ9JCoJ0l--tCWlvKQibe0YaH4hpmgEnLyn0 ...

  4. 防止sql注入式攻击 SQL注入学习——三层架构

    解决方案是:1.首先在UI录入时,要控制数据的类型和长度.防止SQL注入式攻击,系统提供检测注入式攻击的函数,一旦检测出注入式攻击,该数据即不能提交:2.业务逻辑层控制,通过在方法内部将SQL关键字用 ...

  5. SQL注入详细介绍及如何防范SQL注入式攻击

    一. SQL注入攻击的简单示例. statement := "SELECT * FROM Users WHERE Value= " + a_variable + " 上面 ...

  6. 什么是SQL注入式攻击和如何防范?

    什么是SQL注入式攻击? 所谓SQL注入式攻击,就是攻击者把SQL命令插入到Web表单的输入域或页面请求的查询字符串,欺骗服务器执行恶意的SQL命令.在某些表单中,用户输入的内容直接用来构造(或者影响 ...

  7. 什么是SQL注入式攻击?

    什么是SQL注入式攻击? 所谓SQL注入式攻击,就是攻击者把SQL命令插入到Web表单的输入域或页面请求的查询字符串,欺骗服务器执行恶意的SQL命令.在某些表单中,用户输入的内容直接用来构造(或者影响 ...

  8. 浅谈MySQL中优化sql语句查询常用的30种方法 - 转载

    浅谈MySQL中优化sql语句查询常用的30种方法 1.对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 order by 涉及的列上建立索引. 2.应尽量避免在 where 子句中使 ...

  9. 如何防范SQL注入式攻击

    一.什么是SQL注入式攻击? 所谓SQL注入式攻击,就是攻击者把SQL命令插入到Web表单的输入域或页面请求的查询字符串,欺骗服务器执行恶意的SQL命令.在某些表单中,用户输入的内容直接用来构造(或者 ...

随机推荐

  1. Android studio Maven仓库使用

    原文:How to distribute your own Android library through jCenter and Maven Central from Android Studio ...

  2. Ubuntu下常见的问题记录与处理

    经常使用Ubuntu系统,总会遇到各种问题,找到了解决方法,记录在此吧!常言好记性不好烂笔头~ 以下是目前遇到的一些问题,不分先后记录,后面遇到新的问题并找到解决方法也会更新记录的~ 一.共享文件(使 ...

  3. 【Head First Java 读书笔记】(七)继承

    继承与多态 了解继承 继承的关系意味着子类继承了父类的实例变量和方法.父类比较抽象,子类比较具体. 继承层次的设计 找出具有共同属性和行为的对象(用继承来防止子类中出现重复的程序代码) 设计代表共同状 ...

  4. Redis缓存相关

    Redis缓存服务搭建及实现数据读写 RedisHelper帮助类 /// <summary> /// Redis 帮助类文件 /// </summary> public cl ...

  5. 20145233《网络对抗》Exp7 DNS网络欺诈技术防范

    20145233<网络对抗>Exp7 DNS网络欺诈技术防范 实验问题思考 通常在什么场景下容易受到DNS spoof攻击 公共的无线局域网中,容易受到攻击者的攻击,因为这样就会连入局域网 ...

  6. Spring.NET 整合Nhibernate

    因为最近无意中学了AOP ,所以想一探究竟,看看.net里这个Spring.Net 到底是怎么回事,请有需要的童鞋往下,不需要的请alt+w.因为是先配置的 Nhibernate 所以就从这个开始.开 ...

  7. 数独高阶技巧之八——SDC

    在本系列的第四篇“简单异数链”中,向大家介绍了XY-Wing等一系列Wing类技巧,并提到可以用(拐弯的)数组的观念来理解这些结构,经过第六篇ALS的学习之后,大家回过头再去看Wing,应该可以发现相 ...

  8. DB2知识文档

    DB2知识文档 一.db2 基础 基本语法 注释:“--”(两个减号) 字符串连接:“||” 如set msg=’aaaa’||’bbbb’,则msg为’aaaabbbb’ 字符串的引用:‘’(一定用 ...

  9. CSS:如何清除a标签之间的默认留白间距

    即使我们使用了类似 *{margin: 0;padding: 0;} 这样的代码重置了浏览器默认样式,也会发现类似<a>标签这种inline-block元素,它们之间也还存在着间距. de ...

  10. codeforces|CF1054D Changing Array

    因为数据范围是2e5级别的,所以我们考虑用异或前缀和来处理区间的异或情况.(比如说a包括b,那么我们通过异或可以知道b对于a的补区间的信息) 之后因为对任意\(a_i\)进行取反操作,会改变它和它之后 ...