asp.net下檢測SQL注入式攻擊代碼

來源:互聯網
上載者:User

兩個類:
(頁面資料校正類)PageValidate.cs 基本通用。
代碼如下: 複製代碼 代碼如下:using System;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;

namespace Common
{
/// <summary>
/// 頁面資料校正類
/// </summary>
public class PageValidate
{
private static Regex RegNumber = new Regex("^[0-9]+$");
private static Regex RegNumberSign = new Regex("^[+-]?[0-9]+$");
private static Regex RegDecimal = new Regex("^[0-9]+[.]?[0-9]+$");
private static Regex RegDecimalSign = new Regex("^[+-]?[0-9]+[.]?[0-9]+$"); //等價於^[+-]?\d+[.]?\d+$
private static Regex RegEmail = new Regex("^[\\w-]+@[\\w-]+\\.(com|net|org|edu|mil|tv|biz|info)$");//w 英文字母或數位字串,和 [a-zA-Z0-9] 文法一樣
private static Regex RegCHZN = new Regex("[\u4e00-\u9fa5]");

public PageValidate()
{
}

#region 數字字串檢查

/// <summary>
/// 檢查Request查詢字串的索引值,是否是數字,最大長度限制
/// </summary>
/// <param name="req">Request</param>
/// <param name="inputKey">Request的索引值</param>
/// <param name="maxLen">最大長度</param>
/// <returns>返回Request查詢字串</returns>
public static string FetchInputDigit(HttpRequest req, string inputKey, int maxLen)
{
string retVal = string.Empty;
if(inputKey != null && inputKey != string.Empty)
{
retVal = req.QueryString[inputKey];
if(null == retVal)
retVal = req.Form[inputKey];
if(null != retVal)
{
retVal = SqlText(retVal, maxLen);
if(!IsNumber(retVal))
retVal = string.Empty;
}
}
if(retVal == null)
retVal = string.Empty;
return retVal;
}
/// <summary>
/// 是否數字字串
/// </summary>
/// <param name="inputData">輸入字串</param>
/// <returns></returns>
public static bool IsNumber(string inputData)
{
Match m = RegNumber.Match(inputData);
return m.Success;
}
/// <summary>
/// 是否數字字串 可帶加號或減號
/// </summary>
/// <param name="inputData">輸入字串</param>
/// <returns></returns>
public static bool IsNumberSign(string inputData)
{
Match m = RegNumberSign.Match(inputData);
return m.Success;
}
/// <summary>
/// 是否是浮點數
/// </summary>
/// <param name="inputData">輸入字串</param>
/// <returns></returns>
public static bool IsDecimal(string inputData)
{
Match m = RegDecimal.Match(inputData);
return m.Success;
}
/// <summary>
/// 是否是浮點數 可帶加號或減號
/// </summary>
/// <param name="inputData">輸入字串</param>
/// <returns></returns>
public static bool IsDecimalSign(string inputData)
{
Match m = RegDecimalSign.Match(inputData);
return m.Success;
}

#endregion

#region 中文檢測

/// <summary>
/// 檢測是否有中文字元
/// </summary>
/// <param name="inputData"></param>
/// <returns></returns>
public static bool IsHasCHZN(string inputData)
{
Match m = RegCHZN.Match(inputData);
return m.Success;
}

#endregion

#region 郵件地址
/// <summary>
/// 是否是浮點數 可帶加號或減號
/// </summary>
/// <param name="inputData">輸入字串</param>
/// <returns></returns>
public static bool IsEmail(string inputData)
{
Match m = RegEmail.Match(inputData);
return m.Success;
}

#endregion

#region 其他

/// <summary>
/// 檢查字串最大長度,返回指定長度的串
/// </summary>
/// <param name="sqlInput">輸入字串</param>
/// <param name="maxLength">最大長度</param>
/// <returns></returns>
public static string SqlText(string sqlInput, int maxLength)
{
if(sqlInput != null && sqlInput != string.Empty)
{
sqlInput = sqlInput.Trim();
if(sqlInput.Length > maxLength)//按最大長度截取字串
sqlInput = sqlInput.Substring(0, maxLength);
}
return sqlInput;
}
/// <summary>
/// 字串編碼
/// </summary>
/// <param name="inputData"></param>
/// <returns></returns>
public static string HtmlEncode(string inputData)
{
return HttpUtility.HtmlEncode(inputData);
}
/// <summary>
/// 設定Label顯示Encode的字串
/// </summary>
/// <param name="lbl"></param>
/// <param name="txtInput"></param>
public static void SetLabel(Label lbl, string txtInput)
{
lbl.Text = HtmlEncode(txtInput);
}
public static void SetLabel(Label lbl, object inputObj)
{
SetLabel(lbl, inputObj.ToString());
}
//字串清理
public static string InputText(string inputString, int maxLength)
{
StringBuilder retVal = new StringBuilder();

// 檢查是否為空白
if ((inputString != null) && (inputString != String.Empty))
{
inputString = inputString.Trim();

//檢查長度
if (inputString.Length > maxLength)
inputString = inputString.Substring(0, maxLength);

//替換危險字元
for (int i = 0; i < inputString.Length; i++)
{
switch (inputString[i])
{
case '"':
retVal.Append(""");
break;
case '<':
retVal.Append("<");
break;
case '>':
retVal.Append(">");
break;
default:
retVal.Append(inputString[i]);
break;
}
}
retVal.Replace("'", " ");// 替換單引號
}
return retVal.ToString();

}
/// <summary>
/// 轉換成 HTML code
/// </summary>
/// <param name="str">string</param>
/// <returns>string</returns>
public static string Encode(string str)
{
str = str.Replace("&","&");
str = str.Replace("'","''");
str = str.Replace("\"",""");
str = str.Replace(" "," ");
str = str.Replace("<","<");
str = str.Replace(">",">");
str = str.Replace("\n","<br>");
return str;
}
/// <summary>
///解析html成 普通文本
/// </summary>
/// <param name="str">string</param>
/// <returns>string</returns>
public static string Decode(string str)
{
str = str.Replace("<br>","\n");
str = str.Replace(">",">");
str = str.Replace("<","<");
str = str.Replace(" "," ");
str = str.Replace(""","\"");
return str;
}

#endregion

}
}

通用檔案(Global.asax),儲存為Global.asax檔案名稱 放到網站根木馬下即可。(其他功能自行補上)複製代碼 代碼如下:<script language="C#" runat="server"><!--
protected void Application_BeginRequest(Object sender, EventArgs e)
{
StartProcessRequest();
}

/// <summary>
/// 處理使用者提交的請求
/// </summary>
private void StartProcessRequest()
{
try
{
string getkeys = "";

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.Write("Get,出現錯誤,包含非法字串");
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.Write("Post,出現錯誤,包含非法字串");
System.Web.HttpContext.Current.Response.End();
}
}
}
if(System.Web.HttpContext.Current.Request.Cookies!=null)
{
for (int i = 0; i < System.Web.HttpContext.Current.Request.Cookies.Count; i++)
{
getkeys = System.Web.HttpContext.Current.Request.Cookies.Keys[i];
if (getkeys == "__VIEWSTATE") continue;
if (!ProcessSqlStr(System.Web.HttpContext.Current.Request.Cookies[getkeys].Value))
{
System.Web.HttpContext.Current.Response.Write("Cookies,出現錯誤,包含非法字串");
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 = "select¦insert¦delete¦update¦declare¦sysobjects¦syscolumns¦cast¦truncate¦master¦mid¦exec";

string[] anySqlStr = SqlStr.Split('¦');
foreach (string ss in anySqlStr)
{
if (Str.ToLower().IndexOf(ss) >= 0)
{
ReturnValue = false;
break;
}
}
}
}
catch
{
ReturnValue = false;
}
return ReturnValue;
}

// --></script>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.