c.net prevents SQL from injecting the code of the class
- 2020-05-30 19:47:30
- OfStack
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// prevent SQL Injection checker
/// </summary>
public class SqlChecker
{
// Current request object
private HttpRequest request;
// Current response object
private HttpResponse response;
// security Url, When there is a Sql When the injection , The security page to which you will be directed , If there's no assignment , Stay on the current page
private string safeUrl = String.Empty;
//Sql When the injection , possible sql The keyword , It can be initialized according to its actual situation , Each keyword is determined by '|' separated
//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 When the injection , Special symbols that may appear ,, It can be initialized according to its actual situation , Each symbol is represented by '|' separated
//private const string StrRegex = @"-|;|,|/|(|)|[|]|}|{|%|@|*|!|'";
private const string StrRegex = @"=|!|'";
public SqlChecker()
{
//
// TODO: Add the constructor logic here
//
}
/// <summary>
/// The object created by this constructor , In the validation Sql After the injection, it will stay on the original page
/// </summary>
/// <param name="_request"> Currently requested Request object </param>
/// <param name="_response"> Currently requested Response object </param>
public SqlChecker(HttpRequest _request, HttpResponse _response)
{
this.request = _request;
this.response = _response;
}
/// <summary>
/// The object created by this constructor , In the validation Sql After injection the request will be directed to _safeUrl Specified security url On the page
/// </summary>
/// <param name="_request"> Currently requested Request object </param>
/// <param name="_response"> Currently requested Response object </param>
/// <param name="_safeUrl"> validation Sql After injection will be directed to security url</param>
public SqlChecker(HttpRequest _request, HttpResponse _response, string _safeUrl)
{
this.request = _request;
this.response = _response;
this.safeUrl = _safeUrl;
}
/// <summary>
/// Read-only property SQL The keyword
/// </summary>
public string KeyWord
{
get
{
return StrKeyWord;
}
}
/// <summary>
/// Read-only property filters special characters
/// </summary>
public string RegexString
{
get
{
return StrRegex;
}
}
/// <summary>
/// When there is a Sql Error message that needs to be prompted when injecting ( It's mostly running 1 Some client-side scripts )
/// </summary>
public string Msg
{
get
{
string msg = "<script type='text/javascript'> "
+ " alert(' Do not enter illegal characters !'); ";
if (this.safeUrl == String.Empty)
msg += " window.location.href = '" + request.RawUrl + "'";
else
msg += " window.location.href = '" + safeUrl + "'";
msg += "</script>";
return msg;
}
}
/// <summary>
/// check URL Whether there is a SQL Possible keywords for injection.
/// </summary>
/// <returns> There are SQL Returns when the keyword is injected true Otherwise return false</returns>
public bool CheckRequestQuery()
{
bool result = false;
if (request.QueryString.Count != 0)
{
// if URL , the parameters are tested one by one.
foreach (string queryName in this.request.QueryString)
{
// screening 1 Some special request status values , mainly 1 Some parameters about the state of the page view
if (queryName == "__VIEWSTATE" || queryName == "__EVENTVALIDATION")
continue;
// Start checking that the request parameter values are valid
if (CheckKeyWord(request.QueryString[queryName]))
{
// As long as there is a 1 Three possibilities Sql Injection parameters , You just quit
result = true;
break;
}
}
}
return result;
}
/// <summary>
/// Check to see if the submission form exists SQL Possible keywords for injection
/// </summary>
/// <returns> There are SQL Returns when the keyword is injected true Otherwise return false</returns>
public bool CheckRequestForm()
{
bool result = false;
if (request.Form.Count > 0)
{
// If the number of submitted form items is not 0, Compare the parameters one by one
foreach (string queryName in this.request.Form)
{
// screening 1 Some special request status values , mainly 1 Some parameters about the state of the page view
if (queryName == "__VIEWSTATE" || queryName == "__EVENTVALIDATION")
continue;
// Start by checking that the submitted form parameter values are valid
if (CheckKeyWord(request.Form[queryName]))
{
// As long as there is a 1 Three possibilities Sql Injection parameters , You just quit
result = true;
break;
}
}
}
return result;
}
/// <summary>
/// check _sword Whether the inclusion SQL The keyword
/// </summary>
/// <param name="_sWord"> The string to check </param>
/// <returns> There are SQL Returns when the keyword is injected true Otherwise return false</returns>
public bool CheckKeyWord(string _sWord)
{
bool result = false;
// model 1 : The corresponding Sql Possible keywords for injection
string[] patten1 = StrKeyWord.Split('|');
// model 2 : The corresponding Sql Possible special symbols for injection
string[] patten2 = StrRegex.Split('|');
// Start to check model 1:Sql Possible keywords for injection The injection condition of
foreach (string sqlKey in patten1)
{
if (_sWord.IndexOf(" " + sqlKey) >= 0 || _sWord.IndexOf(sqlKey + " ") >= 0)
{
// As long as there is a 1 Three possibilities Sql Injection parameters , You just quit
result = true;
break;
}
}
// Start to check model 1:Sql Possible special symbols for injection The injection condition of
foreach (string sqlKey in patten2)
{
if (_sWord.IndexOf(sqlKey) >= 0)
{
// As long as there is a 1 Three possibilities Sql Injection parameters , You just quit
result = true;
break;
}
}
return result;
}
/// <summary>
/// perform Sql Injection of validation
/// </summary>
public void Check()
{
if (CheckRequestQuery() || CheckRequestForm())
{
response.Write(Msg);
response.End();
}
}
}
Instructions:
// Use can be decided according to the need is to be overall ( That is, for the entire application ) the Sql Injection of check
// , Again, locality ( That is, on a particular page ) the Sql Injection of check
/*=========== Global Settings : in Global.asax.cs Add the following code to =============
protected void Application_BeginRequest(Object sender, EventArgs e)
{
SqlChecker SqlChecker = new SqlChecker(this.Request,this.Response);
// or SqlChecker SqlChecker = new SqlChecker(this.Request,this.Response,safeUrl);
SqlChecker.Check();
}
/*============ local : You can do this at any time directly with the following code Sql Injection test ===============
SqlChecker SqlChecker = new SqlChecker(this.Request,this.Response);
// or SqlChecker SqlChecker = new SqlChecker(this.Request,this.Response,safeUrl);
SqlChecker.Check();