using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// 防SQL注入检查器
/// </summary>
public class SqlChecker
{
    //当前请求对象
    private HttpRequest request;
    //当前响应对象
    private HttpResponse response;
    //安全Url,当出现Sql注入时,将导向到的安全页面,如果没赋值,则停留在当前页面
    private string safeUrl = String.Empty;

//Sql注入时,可能出现的sql关键字,可根据自己的实际情况进行初始化,每个关键字由'|'分隔开来
    //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 StrKeyWord = @"select|insert|delete|from|drop table|update|truncate|exec master|netlocalgroup administrators|:|net user|or|and";
    //Sql注入时,可能出现的特殊符号,,可根据自己的实际情况进行初始化,每个符号由'|'分隔开来
    //private const string StrRegex = @"-|;|,|/|(|)|[|]|}|{|%|@|*|!|'";
    private const string StrRegex = @"=|!|'";
    public SqlChecker()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }
    /// <summary>
    /// 由此构造函数创建的对象,在验证Sql注入之后将停留在原来页面上
    /// </summary>
    /// <param name="_request">当前请求的 Request 对象</param>
    /// <param name="_response">当前请求的 Response 对象</param>
    public SqlChecker(HttpRequest _request, HttpResponse _response)
    {
        this.request = _request;
        this.response = _response;
    }
    /// <summary>
    /// 由此构造函数创建的对象,在验证Sql注入之后将请求将导向由 _safeUrl 指定的安全url页面上
    /// </summary>
    /// <param name="_request">当前请求的 Request 对象</param>
    /// <param name="_response">当前请求的 Response 对象</param>
    /// <param name="_safeUrl">验证Sql注入之后将导向的安全 url</param>
    public SqlChecker(HttpRequest _request, HttpResponse _response, string _safeUrl)
    {
        this.request = _request;
        this.response = _response;
        this.safeUrl = _safeUrl;
    }
    /// <summary>
    /// 只读属性 SQL关键字
    /// </summary>
    public string KeyWord
    {
        get
        {
            return StrKeyWord;
        }
    }
    /// <summary>
    /// 只读属性过滤特殊字符
    /// </summary>
    public string RegexString
    {
        get
        {
            return StrRegex;
        }
    }
    /// <summary>
    /// 当出现Sql注入时需要提示的错误信息(主要是运行一些客户端的脚本)
    /// </summary>
    public string Msg
    {
        get
        {
            string msg = "<script type='text/javascript'> "
            + " alert('请勿输入非法字符!'); ";

if (this.safeUrl == String.Empty)
                msg += " window.location.href = '" + request.RawUrl + "'";
            else
                msg += " window.location.href = '" + safeUrl + "'";

msg += "</script>";
            return msg;
        }
    }
    /// <summary>
    /// 检查URL参数中是否带有SQL注入的可能关键字。
    /// </summary>
    /// <returns>存在SQL注入关键字时返回 true,否则返回 false</returns>
    public bool CheckRequestQuery()
    {
        bool result = false;
        if (request.QueryString.Count != 0)
        {
            //若URL中参数存在,则逐个检验参数。
            foreach (string queryName in this.request.QueryString)
            {
                //过虑一些特殊的请求状态值,主要是一些有关页面视图状态的参数
                if (queryName == "__VIEWSTATE" || queryName == "__EVENTVALIDATION")
                    continue;
                //开始检查请求参数值是否合法
                if (CheckKeyWord(request.QueryString[queryName]))
                {
                    //只要存在一个可能出现Sql注入的参数,则直接退出
                    result = true;
                    break;
                }
            }
        }
        return result;
    }
    /// <summary>
    /// 检查提交表单中是否存在SQL注入的可能关键字
    /// </summary>
    /// <returns>存在SQL注入关键字时返回 true,否则返回 false</returns>
    public bool CheckRequestForm()
    {
        bool result = false;
        if (request.Form.Count > 0)
        {
            //若获取提交的表单项个数不为0,则逐个比较参数
            foreach (string queryName in this.request.Form)
            {
                //过虑一些特殊的请求状态值,主要是一些有关页面视图状态的参数
                if (queryName == "__VIEWSTATE" || queryName == "__EVENTVALIDATION")
                    continue;
                //开始检查提交的表单参数值是否合法
                if (CheckKeyWord(request.Form[queryName]))
                {
                    //只要存在一个可能出现Sql注入的参数,则直接退出
                    result = true;
                    break;
                }
            }
        }
        return result;
    }
    /// <summary>
    /// 检查_sword是否包涵SQL关键字
    /// </summary>
    /// <param name="_sWord">需要检查的字符串</param>
    /// <returns>存在SQL注入关键字时返回 true,否则返回 false</returns>
    public bool CheckKeyWord(string _sWord)
    {
        bool result = false;
        //模式1 : 对应Sql注入的可能关键字
        string[] patten1 = StrKeyWord.Split('|');
        //模式2 : 对应Sql注入的可能特殊符号
        string[] patten2 = StrRegex.Split('|');
        //开始检查 模式1:Sql注入的可能关键字 的注入情况
        foreach (string sqlKey in patten1)
        {
            if (_sWord.IndexOf(" " + sqlKey) >= 0 || _sWord.IndexOf(sqlKey + " ") >= 0)
            {
                //只要存在一个可能出现Sql注入的参数,则直接退出
                result = true;
                break;
            }
        }
        //开始检查 模式1:Sql注入的可能特殊符号 的注入情况
        foreach (string sqlKey in patten2)
        {
            if (_sWord.IndexOf(sqlKey) >= 0)
            {
                //只要存在一个可能出现Sql注入的参数,则直接退出
                result = true;
                break;
            }
        }
        return result;
    }
    /// <summary>
    /// 执行Sql注入验证
    /// </summary>
    public void Check()
    {
        if (CheckRequestQuery() || CheckRequestForm())
        {
            response.Write(Msg);
            response.End();
        }
    }
}

// 使用时可以根据需要决定是要进行全局性(即针对整个应用程序)的Sql注入检查 
// ,还是局部性(即在针对某个页面)的Sql注入检查

/*=========== 全局性设置:在Global.asax.cs 中加上以下代码 ============= 

protected void Application_BeginRequest(Object sender, EventArgs e) 

SqlChecker SqlChecker = new SqlChecker(this.Request,this.Response); 
//或 SqlChecker SqlChecker = new SqlChecker(this.Request,this.Response,safeUrl); 
SqlChecker.Check(); 
}

/*============ 局部性:在任何时候都可直接用以下代码来实现Sql注入检验 =============== 

SqlChecker SqlChecker = new SqlChecker(this.Request,this.Response); 
//或 SqlChecker SqlChecker = new SqlChecker(this.Request,this.Response,safeUrl); 
SqlChecker.Check();

来自http://www.jb51.net/article/34671.htm

c#.net全站防止SQL注入类的代码的更多相关文章

  1. ecshop SQL注入漏洞导致代码执行

    漏洞名称:ecshop SQL注入漏洞导致代码执行补丁编号:11208761补丁文件:/includes/libinsert.php补丁来源:云盾自研漏洞描述:ecshop的/includes/lib ...

  2. SQL注入原理及代码分析(二)

    前言 上一篇文章中,对union注入.报错注入.布尔盲注等进行了分析,接下来这篇文章,会对堆叠注入.宽字节注入.cookie注入等进行分析.第一篇文章地址:SQL注入原理及代码分析(一) 如果想要了解 ...

  3. [漏洞分析]thinkcmf 1.6.0版本从sql注入到任意代码执行

    0x00 前言 该漏洞源于某真实案例,虽然攻击没有用到该漏洞,但在分析攻击之后对该版本的cmf审计之后发现了,也算是有点机遇巧合的味道,我没去找漏洞,漏洞找上了我XD thinkcmf 已经非常久远了 ...

  4. DedeCMS全版本通杀SQL注入漏洞利用代码及工具

    dedecms即织梦(PHP开源网站内容管理系统).织梦内容管理系统(DedeCms) 以简单.实用.开源而闻名,是国内最知名的PHP开源网站管理系统,也是使用用户最多的PHP类CMS系统,近日,网友 ...

  5. SQL注入原理及代码分析(一)

    前言 我们都知道,学安全,懂SQL注入是重中之重,因为即使是现在SQL注入漏洞依然存在,只是相对于之前现在挖SQL注入变的困难了.而且知识点比较多,所以在这里总结一下.通过构造有缺陷的代码,来理解常见 ...

  6. DedeCMS全版本通杀SQL注入漏洞利用代码

    EXP: Exp:plus/recommend.php?action=&aid=1&_FILES[type][tmp_name]=\'   or mid=@`\'` /*!50000u ...

  7. jdbc PreparedStatement 防止sql注入的关键代码片段

    mysql-connector-java-5.1.38.jar PreparedStatement 的 setString(int parameterIndex, String x) 方法 for ( ...

  8. SQL注入攻防入门详解

    =============安全性篇目录============== 本文转载 毕业开始从事winfrm到今年转到 web ,在码农届已经足足混了快接近3年了,但是对安全方面的知识依旧薄弱,事实上是没机 ...

  9. SQL注入—我是如何一步步攻破一家互联网公司的

    最近在研究Web安全相关的知识,特别是SQL注入类的相关知识.接触了一些与SQL注入相关的工具.周末在家闲着无聊,想把平时学的东东结合起来攻击一下身边某个小伙伴去的公司,看看能不能得逞.不试不知道,一 ...

随机推荐

  1. ubuntu-利用pdnsd-TCP方式获取IP-拒绝DNS污染

    那,自从国内技术出现了DNS污染问题呢,时常导致很多国外网站访问不正常,所以通过参考一些博客所属避免DNS污染的方法,决定搭建一个Ubuntu JeOS下的DNS缓存服务器,该服务器利用TCP方式获取 ...

  2. jquery 获取鼠标和元素的坐标点

    获取当前鼠标相对img元素的坐标 $('img').mousemove(function(e) { varpositionX=e.pageX-$(this).offset().left; //获取当前 ...

  3. 块状元素(div)与内联元素(span)

    <pre class="html" name="code"><html xmlns="http://www.w3.org/1999/ ...

  4. 实现ApplicationContextAware接口时,获取ApplicationContext为null

    将懒加载关闭,@Lazy(false),默认为true import org.springframework.beans.BeansException; import org.springframew ...

  5. 使用Git命令上传本地项目

    前提,安装git,使用cmd进入项目根目录. 初始化git init 再添加文件git add .git commit -m '项目名' 上传项目到Github仓库git remote add ori ...

  6. javaweb 拦截器报错

    拦截器报错   The content of element type "interceptor-ref" must match "(param)*".内容元素 ...

  7. 简单三个表之间关联 与 case when语句的应用

    select p.conttract_id,l.order_code,jz.cur_branch from wy_auto_workflow_log l,wg_pjhsb p,wg_jzmb jz w ...

  8. webconfig中注册HttpHandler报错:检测到在集成的托管管道模式下不适用的 ASP.NET 设置。

    为什么会出现以上错误? 在IIS7的应用程序池有两种模式,一种是"集成模式",一种是"经典模式". 经典模式 则是我们以前习惯的IIS 6 的方式. 如果使用集 ...

  9. C语言编程技巧-signal(信号)[转]

    自 http://www.uml.org.cn/c++/200812083.asp 信号是Linux编程中非常重要的部分,本文将详细介绍信号机制的基本概念.Linux对信号机制的大致实现方法.如何使用 ...

  10. 转 LoadRunner 技巧之协议分析

    在做性能测试的时候,协议分析是困扰初学者的难题,选择错误的协议会导致Virtual User Generator 录制不到脚本:或录制的脚本不完整,有些应用可能需要选择多个协议才能完整的记录 客户端与 ...