C #. net full-site code to prevent SQL Injection

Source: Internet
Author: User

Copy codeThe Code is 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;
// Secure Url. When SQL Injection occurs, it is directed to the Security page. If no value is assigned, it stays on the current page.
Private string safeUrl = String. Empty;

// Possible SQL keywords during SQL injection can be initialized based on your actual situation. Each keyword is separated by '| '.
// Private const string StrKeyWord = @ "select | insert | delete | from | count (| drop table | update | truncate | asc (| mid (| char (| xp_mongoshell | 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 ";
// Special symbols that may occur during SQL injection. You can initialize them according to your actual situation. Each symbol is separated by '| '.
// Private const string StrRegex = @ "-|; |, |/| (|) | [|] |}||%| @ | * |! | '";
Private const string StrRegex = @ "= |! | '";
Public SqlChecker ()
{
//
// TODO: add the constructor logic here
//
}
/// <Summary>
/// The object created by the constructor will stay on the original page after verifying SQL Injection
/// </Summary>
/// <Param name = "_ request"> Request object of the current request </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 the constructor directs the request to the secure url page specified by _ safeUrl after verifying SQL Injection
/// </Summary>
/// <Param name = "_ request"> Request object of the current request </param>
/// <Param name = "_ response"> the Response object of the current request </param>
/// <Param name = "_ safeUrl"> verify the security url that will be redirected after SQL Injection </param>
Public SqlChecker (HttpRequest _ request, HttpResponse _ response, string _ safeUrl)
{
This. request = _ request;
This. response = _ response;
This. safeUrl = _ safeUrl;
}
/// <Summary>
/// Read-only attribute SQL keyword
/// </Summary>
Public string KeyWord
{
Get
{
Return StrKeyWord;
}
}
/// <Summary>
/// Read-only attribute filters out special characters
/// </Summary>
Public string RegexString
{
Get
{
Return StrRegex;
}
}
/// <Summary>
/// The error message to be prompted when SQL Injection occurs (mainly to run some client scripts)
/// </Summary>
Public string Msg
{
Get
{
String msg = "<script type = 'text/javascript '>"
+ "Alert ('do not enter invalid characters! ');";

If (this. safeUrl = String. Empty)
Msg + = "window. location. href = '" + request. RawUrl + "'";
Else
Msg + = "window. location. href = '" + safeUrl + "'";

Msg + = "</script> ";
Return msg;
}
}
/// <Summary>
/// Check whether URL parameters contain possible keywords of SQL injection.
/// </Summary>
/// <Returns> true is returned if the keyword SQL Injection exists. Otherwise, false is returned. </returns>
Public bool CheckRequestQuery ()
{
Bool result = false;
If (request. QueryString. Count! = 0)
{
// If parameters in the URL exist, check the parameters one by one.
Foreach (string queryName in this. request. QueryString)
{
// Special request Status values, mainly parameters related to page view status
If (queryName = "_ VIEWSTATE" | queryName = "_ EVENTVALIDATION ")
Continue;
// Start to check whether the request parameter value is valid
If (CheckKeyWord (request. QueryString [queryName])
{
// Exit if there is a parameter that may result in SQL injection.
Result = true;
Break;
}
}
}
Return result;
}
/// <Summary>
/// Check whether any keyword of SQL Injection exists in the submission form
/// </Summary>
/// <Returns> true is returned if the keyword SQL Injection exists. Otherwise, false is returned. </returns>
Public bool CheckRequestForm ()
{
Bool result = false;
If (request. Form. Count> 0)
{
// If the number of items in the obtained submitted form is not 0, compare the parameters one by one.
Foreach (string queryName in this. request. Form)
{
// Special request Status values, mainly parameters related to page view status
If (queryName = "_ VIEWSTATE" | queryName = "_ EVENTVALIDATION ")
Continue;
// Start to check whether the submitted form parameter value is valid
If (CheckKeyWord (request. Form [queryName])
{
// Exit if there is a parameter that may result in SQL injection.
Result = true;
Break;
}
}
}
Return result;
}
/// <Summary>
/// Check whether _ sword contains the SQL keyword
/// </Summary>
/// <Param name = "_ sWord"> string to be checked </param>
/// <Returns> true is returned if the keyword SQL Injection exists. Otherwise, false is returned. </returns>
Public bool CheckKeyWord (string _ sWord)
{
Bool result = false;
// Mode 1: The keyword corresponding to SQL Injection
String [] patten1 = StrKeyWord. Split ('| ');
// Mode 2: special symbols corresponding to SQL Injection
String [] patten2 = StrRegex. Split ('| ');
// Start Check Mode 1: Possible keyword injection of SQL Injection
Foreach (string sqlKey in patten1)
{
If (_ sWord. IndexOf ("" + sqlKey)> = 0 | _ sWord. IndexOf (sqlKey + "")> = 0)
{
// Exit if there is a parameter that may result in SQL injection.
Result = true;
Break;
}
}
// Start Check Mode 1: Possible injection of special symbols for SQL Injection
Foreach (string sqlKey in patten2)
{
If (_ sWord. IndexOf (sqlKey)> = 0)
{
// Exit if there is a parameter that may result in SQL injection.
Result = true;
Break;
}
}
Return result;
}
/// <Summary>
/// Perform SQL Injection Verification
/// </Summary>
Public void Check ()
{
If (CheckRequestQuery () | CheckRequestForm ())
{
Response. Write (Msg );
Response. End ();
}
}
}

Instructions for use:

Copy codeThe Code is as follows:

// You can determine whether to perform a global SQL Injection check (for the entire application) as needed.
//, Or a local SQL Injection check (for a page)

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

Protected void Application_BeginRequest (Object sender, EventArgs e)
{
SqlChecker = new SqlChecker (this. Request, this. Response );
// Or SqlChecker = new SqlChecker (this. Request, this. Response, safeUrl );
SqlChecker. Check ();
}

/* ============= Locality: you can use the following code to test SQL injection at any time ================

SqlChecker = new SqlChecker (this. Request, this. Response );
// Or 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.