• JS/C#/ASP 防止sql注入


    SQL注入式攻击是利用是指利用设计上的漏洞,在目标服务器上运行Sql命令以及进行其他方式的攻击
    动态生成Sql命令时没有对用户输入的数据进行验证是Sql注入攻击得逞的主要原因。
    比如:
    如果你的查询语句是select * from admin where username='"&user&"' and password='"&pwd&"'"

    那么,如果我的用户名是:1' or '1'='1
    那么,你的查询语句将会变成:
    select * from admin where username='1 or '1'='1' and password='"&pwd&"'"
    这样你的查询语句就通过了,从而就可以进入你的管理界面。

    所以防范的时候需要对用户的输入进行检查。特别式一些特殊字符,比如单引号,双引号,分号,逗号,冒号,连接号等进行转换或者过滤。

    需要过滤的特殊字符及字符串有:
    net user
    xp_cmdshell
    /add
    exec master.dbo.xp_cmdshell
    net localgroup administrators
    select
    count
    Asc
    char
    mid
    '
    :
    "
    insert
    delete from
    drop table
    update
    truncate
    from
    %

    下面是我写的两种关于解决注入式攻击的防范代码,供大家学习参考!
    js版的防范SQL注入式攻击代码~:

    [CODE START]
    <script language="javascript">
    <!--
    var url = location.search;
    var re=/^\?(.*)(select%20|insert%20|delete%20from%20|count\(|drop%20table|update%20truncate%20|asc\(|mid\(|char\(|xp_cmdshell|exec%20master|net%20localgroup%20administrators|\"|:|net%20user|\'|%20or%20)(.*)$/gi;
    var e = re.test(url);
    if(e) {
    alert("地址中含有非法字符~");
    location.href="error.asp";
    }
    //-->
    <script>
    [CODE END]

    asp版的防范SQL注入式攻击代码~:
    [CODE START]
    <%
    On Error Resume Next
    Dim strTemp

    If LCase(Request.ServerVariables("HTTPS")) = "off" Then
    strTemp = "http://"
    Else
    strTemp = "https://"
    End If

    strTemp = strTemp & Request.ServerVariables("SERVER_NAME")
    If Request.ServerVariables("SERVER_PORT") <> 80 Then strTemp = strTemp & ":" & Request.ServerVariables("SERVER_PORT")

    strTemp = strTemp & Request.ServerVariables("URL")

    If Trim(Request.QueryString) <> "" Then strTemp = strTemp & "?" & Trim(Request.QueryString)

    strTemp = LCase(strTemp)

    If Instr(strTemp,"select%20") or Instr(strTemp,"insert%20") or Instr(strTemp,"delete%20from") or Instr(strTemp,"count(") or Instr(strTemp,"drop%20table") or Instr(strTemp,"update%20") or Instr(strTemp,"truncate%20") or Instr(strTemp,"asc(") or Instr(strTemp,"mid(") or Instr(strTemp,"char(") or Instr(strTemp,"xp_cmdshell") or Instr(strTemp,"exec%20master") or Instr(strTemp,"net%20localgroup%20administrators") or Instr(strTemp,":") or Instr(strTemp,"net%20user") or Instr(strTemp,"'") or Instr(strTemp,"%20or%20") then
    Response.Write "<script language='javascript'>"
    Response.Write "alert('非法地址!!');"
    Response.Write "location.href='error.asp';"
    Response.Write "<script>"
    End If
    %>
    [CODE END]

    C# 检查字符串,防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;

    /// <summary>
    /// 当有数据时交时,触发事件
    /// </summary>
    /// <param name="sender"> </param>
    /// <param name="e"> </param>
    protected void Application_BeginRequest(Object sender, EventArgs e)
    {
    //遍历Post参数,隐藏域除外
    foreach (string i in this.Request.Form)
    {
    if (i == "__VIEWSTATE") continue;
    this.goErr(this.Request.Form[i].ToString());
    }
    //遍历Get参数。
    foreach (string i in this.Request.QueryString)
    {
    this.goErr(this.Request.QueryString[i].ToString());

    }

    }

    /// <summary>
    ///SQL注入过滤
    /// </summary>
    /// <param name="InText">要过滤的字符串 </param>
    /// <returns>如果参数存在不安全字符,则返回true </returns>
    public bool SqlFilter(string InText)
    {
    string word = "and |exec |insert |select |delete |update |chr |mid |master |or |truncate |char |declare |join |cmd | |' |--";//这里加要过滤的SQL字符
    if (InText == null)
    return false;
    foreach (string i in word.Split(' |'))
    {
    if ((InText.ToLower().IndexOf(i + " ") > -1) | | (InText.ToLower().IndexOf(" " + i) > -1))
    {
    return true;
    }
    }
    return false;
    }

    /// <summary>
    /// 校验参数是否存在SQL字符
    /// </summary>
    /// <param name="tm"> </param>
    private void goErr(string tm)
    {
    if (SqlFilter(tm))
    {
    Response.Write(" <script>window.alert('参数存在不安全字符');"+" </"+"script>");
    }
    }

    protected void Application_BeginRequest(Object sender, EventArgs e)
    {
    //SQL防注入
    string Sql_1 = "exec |insert+ |select+ |delete |update |count |chr |mid |master+ |truncate |char |declare |drop+ |drop+table |creat+ |creat+table";
    string Sql_2 = "exec+ |insert+ |delete+ |update+ |count( |count+ |chr+ |+mid( |+mid+ |+master+ |truncate+ |char+ |+char( |declare+ |drop+ |creat+ |drop+table |creat+table";
    string[] sql_c = Sql_1.Split(' |');
    string[] sql_c1 = Sql_2.Split(' |');

    if (Request.QueryString != null)
    {
    foreach (string sl in sql_c)
    {
    if (Request.QueryString.ToString().ToLower().IndexOf(sl.Trim()) >= 0)
    {
    Response.Write("警告!你的IP已经被记录!");//
    Response.Write(sl);
    Response.Write(Request.QueryString.ToString());
    Response.End();
    break;
    }
    }
    }

    if (Request.Form.Count > 0)
    {
    string s1 = Request.ServerVariables["SERVER_NAME"].Trim();//服务器名称
    if (Request.ServerVariables["HTTP_REFERER"] != null)
    {
    string s2 = Request.ServerVariables["HTTP_REFERER"].Trim();//http接收的名称
    string s3 = "";
    if (s1.Length > (s2.Length - 7))
    {
    s3 = s2.Substring(7);
    }
    else
    {
    s3 = s2.Substring(7, s1.Length);
    }
    if (s3 != s1)
    {
    Response.Write("你的IP已被记录!警告!");//
    Response.End();
    }
    }
    }
    }

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

  • 相关阅读:
    ElasticSearch简介(一)——基础
    .net core 3.0中动态卸载程序集
    修改VisualStudio的智能提示字体大小
    使用VisualStudio或VisualStudio Code作为代码比较工具
    编写一个爬虫类库——(二)准备
    编写一个爬虫类库——(一)想法
    linearLayout 和 relativeLayout的属性区别(转)
    如何在Root的手机上开启ViewServer,使得HierachyViewer能够连接(转)
    反编译APK文件的三种方法(转)
    Java中的锁(转)
  • 原文地址:https://www.cnblogs.com/rocker/p/1661764.html
Copyright © 2020-2023  润新知