數(shù)據(jù)庫防腳本注入

字號:


    網(wǎng)站安全非常重要,所以一個網(wǎng)站必須要有對攻擊的基礎(chǔ)防范措施,比如腳本攻擊,跨域攻擊,數(shù)據(jù)庫注入攻擊等。下面分享一個使用的防止數(shù)據(jù)庫Sql腳本注入的使用類
    using System;
    using System.Collections.Generic;
    using System.Text;
    namespace NZS.Common
    {
    public class Filter
    {
    ///
    /// 檢測是否含有危險字符(防止Sql注入)
    ///
    /// 預(yù)檢測的內(nèi)容
    /// 返回True或false
    public static bool HasSqlKeywords(string contents)
    {
    bool ReturnValue = false;
    if (contents.Length > 0)
    {
    string LowerStr = contents.ToLower();
    string RxStr = @”(/sand/s)|(/sand/s)|(/slike/s)|(select/s)|(insert/s)|(delete/s)|(update/s[/s/S].*/sset)|(create/s)|(/stable)|(<[iframe|/iframe|script|/script])|(‘)|(/sexec)|(declare)|(/struncate)|(/smaster)|(/sbackup)|(/smid)|(/scount)|(cast)|(%)|(/sadd/s)|(/salter/s)|(/sdrop/s)|(/sfrom/s)|(/struncate/s)|(/sxp_cmdshell/s)”; //Match 檢查數(shù)據(jù)庫里面關(guān)鍵字和一些特殊字符,如單引號
    System.Text.RegularExpressions.Regex Rx = new System.Text.RegularExpressions.Regex(RxStr);
    ReturnValue = Rx.IsMatch(LowerStr, 0);
    }
    return ReturnValue;
    }
    ///
    /// 過濾 Sql 語句字符串中的注入腳本
    ///
    /// 傳入的字符串
    /// 過濾后的字符串
    public static string SqlFilter(string str)
    {
    str = str.Replace(“””, “‘’”);
    //單引號替換成兩個單引號
    str = str.Replace(“‘”, “‘”);
    //半角封號替換為全角封號,防止多語句執(zhí)行
    str = str.Replace(“;”, “;”);
    //半角括號替換為全角括號
    str = str.Replace(“(“, “(”);
    str = str.Replace(“)”, “)”);
    ///////////////要用正則表達(dá)式替換,防止字母大小寫得情況////////////////////
    //去除執(zhí)行存儲過程的命令關(guān)鍵字
    str = str.Replace(“Exec”, “”);
    str = str.Replace(“Execute”, “”);
    //去除系統(tǒng)存儲過程或擴展存儲過程關(guān)鍵字
    str = str.Replace(“xp_”, “x p_”);
    str = str.Replace(“sp_”, “s p_”);
    //防止16進(jìn)制注入
    str = str.Replace(“0x”, “0 x”);
    return str;
    }
    }
    }