C#.net full station to prevent SQL injection Class Code _ Practical Tips

Source: Internet
Author: User
Tags sql injection

Copy Code code as follows:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;

<summary>
Anti-SQL injection checker
</summary>
public class Sqlchecker
{
Current Request Object
Private HttpRequest request;
Current Response Object
Private HttpResponse response;
Security URL, when SQL injection occurs, the security page that will be directed to, if not assigned, stays on the current page
private string safeurl = String.Empty;

SQL injection, the possible SQL keywords can be initialized according to their actual situation, each keyword by ' | ' Separate
Private Const string Strkeyword = @ "Select|insert|delete|from|count (|drop table|update|truncate|asc |mid (|char _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 injection, the possible special symbols, can be initialized according to their actual situation, each symbol by ' | ' Separate
Private Const string Strregex = @ "-|;|,|/| (|)| [|]|}| {|%| @|*|!|'";
Private Const string Strregex = @ "=|!| '";
Public Sqlchecker ()
{
//
TODO: Add constructor logic here
//
}
<summary>
The object created by this constructor will remain on the original page after validating the SQL injection
</summary>
<param name= "_request" > Request object currently requested </param>
<param name= "_response" > The Response object of the current request </param>
Public Sqlchecker (HttpRequest _request, HttpResponse _response)
{
This.request = _request;
This.response = _response;
}
<summary>
The object created by this constructor that will be directed to the security URL page specified by _safeurl after validating SQL injection
</summary>
<param name= "_request" > Request object currently requested </param>
<param name= "_response" > The Response object of the current request </param>
<param name= "_safeurl" > Verify the Security url</param> that will be directed after SQL injection
Public Sqlchecker (HttpRequest _request, HttpResponse _response, String _safeurl)
{
This.request = _request;
This.response = _response;
This.safeurl = _safeurl;
}
<summary>
Read-only property SQL keyword
</summary>
public string KeyWord
{
Get
{
return Strkeyword;
}
}
<summary>
Read-only properties filter special characters
</summary>
public string regexstring
{
Get
{
return Strregex;
}
}
<summary>
Error messages that need to be prompted when SQL injection occurs (primarily to run 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 the URL parameter for possible keywords with SQL injection.
</summary>
<returns> returns True when SQL injection keyword exists, otherwise returns false</returns>
public bool Checkrequestquery ()
{
BOOL result = FALSE;
if (request). Querystring.count!= 0)
{
If the parameter exists in the URL, the parameters are checked individually.
foreach (String queryname in this.request.QueryString)
{
Some special request status values, mainly some parameters about Page view state
if (queryname = = "__viewstate" | | | queryname = = "__eventvalidation")
Continue
Start checking to see if request parameter values are legitimate
If Checkkeyword (request. Querystring[queryname]))
{
If there is an argument that a SQL injection may occur, exit directly
result = true;
Break
}
}
}
return result;
}
<summary>
Check for possible keywords in the submit form for SQL injection
</summary>
<returns> returns True when SQL injection keyword exists, otherwise returns false</returns>
public bool Checkrequestform ()
{
BOOL result = FALSE;
if (request). Form.count > 0)
{
If the number of submitted table items is not 0, the parameters are compared individually
foreach (String queryname in This.request.Form)
{
Some special request status values, mainly some parameters about Page view state
if (queryname = = "__viewstate" | | | queryname = = "__eventvalidation")
Continue
Start checking to see if the submitted form parameter values are legitimate
If Checkkeyword (request. Form[queryname]))
{
If there is an argument that a SQL injection may occur, exit directly
result = true;
Break
}
}
}
return result;
}
<summary>
Check if _sword includes SQL keywords
</summary>
<param name= "_sword" > Need to check the string </param>
<returns> returns True when SQL injection keyword exists, otherwise returns false</returns>
public bool Checkkeyword (string _sword)
{
BOOL result = FALSE;
Mode 1: Possible keywords corresponding to SQL injection
string[] Patten1 = strkeyword.split (' | ');
Pattern 2: Possible special symbols corresponding to SQL injection
string[] Patten2 = strregex.split (' | ');
Start checking for possible keyword injection of mode 1:sql injection
foreach (String sqlkey in Patten1)
{
if (_sword.indexof ("" + Sqlkey) >= 0 | | _sword.indexof (Sqlkey + "") >= 0)
{
If there is an argument that a SQL injection may occur, exit directly
result = true;
Break
}
}
Start checking the injection of possible special symbols for mode 1:sql injection
foreach (String sqlkey in Patten2)
{
if (_sword.indexof (Sqlkey) >= 0)
{
If there is an argument that a SQL injection may occur, exit directly
result = true;
Break
}
}
return result;
}
<summary>
Perform SQL injection validation
</summary>
public void Check ()
{
if (Checkrequestquery () | | Checkrequestform ())
{
Response. Write (MSG);
Response. End ();
}
}
}

Instructions for use:

Copy Code code as follows:

You can use it to determine the SQL injection check for global (that is, for the entire application)
, or local (that is, on a page) SQL injection check


/*=========== Global Settings: Add the following code to the Global.asax.cs =============

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 ();
}

/*============ locality: You can use the following code directly to implement SQL injection test at any time ===============

Sqlchecker sqlchecker = new Sqlchecker (this. Request,this. Response);
or Sqlchecker Sqlchecker = new Sqlchecker (this. Request,this. Response,safeurl);
Sqlchecker.check ();

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.