asp.net anti-SQL injection code

Source: Internet
Author: User
The code is as follows Copy Code
Web.config file Call

<add verb= "*" path= "*.aspx" validate= "false" type= "Sqlin.sqlinpost"/>

</system.web>

SqlInPost.cs placed in the App_Code directory:

SqlInPost.cs
Using System;
Using System.Data;
Using System.Configuration;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Web.UI.HtmlControls;
Using System.Text.RegularExpressions;
Using System.Collections.Specialized;
Namespace Sqlin
{
<summary>
Summary description of Sqlinpost
</summary>
public class Sqlinpost:ihttphandlerfactory
{
Public Sqlinpost ()
{
//
TODO: Add constructor logic here
//
}
Public virtual IHttpHandler GetHandler (HttpContext context, string RequestType, String url, string pathtranslated)
{
Get compiled instance (through reflection)
PageHandlerFactory factory = (pagehandlerfactory) activator.createinstance (typeof (PageHandlerFactory), true);
IHttpHandler handler = Factory. GetHandler (context, RequestType, url, pathtranslated);
Filter string
if (RequestType = = "POST")
{
Page page = handler as page;
if (page!= null)
Page. Preload + = new EventHandler (filterstrfactoryhandler_preload);
}
if (RequestType = = "Get")
{
Page page = handler as page;
if (page!= null)
Page. Preload + = new EventHandler (FILTERSTRFACTORYHANDLER_PRELOAD1);
}
Return
return handler;
}
Filter special characters in textbox, input, and textarea
void Filterstrfactoryhandler_preload (object sender, EventArgs e)
{
Try
{
Page page = sender as page;
NameValueCollection postdata = page. Request.Form;
foreach (String postkey in PostData)
{
Control CTL = page. FindControl (Postkey);
if (ctl as TextBox!= null)
{
((TextBox) CTL). Text = Common.inputtext ((TextBox) CTL). Text);
Continue
}
if (ctl as HtmlInputControl!= null)
{
((HtmlInputControl) CTL). Value = Common.inputtext ((htmlinputcontrol) CTL). Value);
Continue
}
if (ctl as HtmlTextArea!= null)
{
((HtmlTextArea) CTL). Value = Common.inputtext ((htmltextarea) CTL). Value);
Continue
}
}
}
Catch {}
}
Filtration QueryString
void Filterstrfactoryhandler_preload1 (object sender, EventArgs e)
{
Try
{
Page page = sender as page;
NameValueCollection QUERYNV = page. Request.QueryString;
bool Issafe = true;
for (int i = 0; i < Querynv.count; i++)
{
if (! Issafestring (Querynv.get (i)))
{
Issafe = false;
Break
}
}
if (!issafe)
{
Page. Response.Write ("Illegal transfer value!");
Page. Response.End ();
}
}
Catch {}
}
public virtual void Releasehandler (IHttpHandler handler)
{
}
Determine if a safe string
public bool Issafestring (string p)
{
BOOL ret = true;
string[] Unsafearray = new STRING[22];
Unsafearray[0] = "'";
UNSAFEARRAY[1] = "xp_cmdshell";
UNSAFEARRAY[2] = "exec Master.dbo.xp_cmdshell";
UNSAFEARRAY[3] = "net localgroup Administrators";
UNSAFEARRAY[4] = "Delete from";
UNSAFEARRAY[5] = "NET user";
UNSAFEARRAY[6] = "/add";
UNSAFEARRAY[7] = "drop table";
UNSAFEARRAY[8] = "Update";
UNSAFEARRAY[9] = "SELECT";
UNSAFEARRAY[10] = "; and";
UNSAFEARRAY[11] = "; exec";
UNSAFEARRAY[12] = "; create";
UNSAFEARRAY[13] = "; insert";
UNSAFEARRAY[14] = "and";
UNSAFEARRAY[15] = "EXEC";
UNSAFEARRAY[16] = "create";
UNSAFEARRAY[17] = "Insert";
UNSAFEARRAY[18] = "master.dbo";
UNSAFEARRAY[19] = ";-";
UNSAFEARRAY[20] = "--";
UNSAFEARRAY[21] = "1 =";
foreach (string s in Unsafearray)
{
if (P.tolower (). IndexOf (s) >-1)
{
ret = false;
Break
}
}
return ret;
}
}
public class Common
{
public static string Inputtext (string text)
{
Text = text. Trim ();
if (string. IsNullOrEmpty (text)
return string. Empty;
Text = Regex.Replace (text, "[\s]{2,}", ""); Two or more spaces
Text = Regex.Replace (text, "<[b| b][r| r]/*>) +| (<[p| P] (. |    \ n) "," *?> "); <br>
Text = Regex.Replace (text, "\s*&[n| n][b| b][s| s][p|    p];\s*) + "," "); &nbsp;
Text = Regex.Replace (text, <. | \ n) *?> ", String.    Empty); Any other tags
Text = text. Replace ("'", "" ");
Text = text. Replace ("xp_cmdshell", "");
Text = text. Replace ("Exec Master.dbo.xp_cmdshell", "");
Text = text. Replace ("net localgroup Administrators", "");
Text = text. Replace ("Delete from", "");
Text = text. Replace ("NET user", "");
Text = text. Replace ("/add", "");
Text = text. Replace ("drop table", "");
Text = text. Replace ("Update", "");
return text;
}
}
}


Example Two

The code is as follows Copy Code

Create a new Global.asax in the website, add
void Application_BeginRequest (object source, EventArgs e)
{
COMP. ProcessRequest PR = new COMP. ProcessRequest ();
pr. Startprocessrequest ();
}

Comp inside the file ProcessRequest.cs code is as follows public class ProcessRequest
{
SQL injection Attack Code Analysis #region SQL injection Attack Code analysis
/**////<summary>
Handling requests submitted by a user
</summary>
public void Startprocessrequest ()
{
Try
{
String getkeys = "";
String sqlerrorpage = "/";
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]. ToLower ()))
{
System.Web.HttpContext.Current.Response.Redirect (Sqlerrorpage);
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 (! Processsqlstr (System.web.httpcontext.current.request.form[getkeys]. ToLower ()))
//        {
System.Web.HttpContext.Current.Response.Redirect (Sqlerrorpage);
System.Web.HttpContext.Current.Response.End ();
//        }
//    }
//}

}
Catch
{
Error handling: Processing user submission information!
}
}
/**////<summary>
To analyze whether a user request is normal
</summary>
<param name= "STR" > Incoming user submit data </param>
<returns> returns if SQL injection attack code is included </returns>
private bool Processsqlstr (string Str)
{
BOOL ReturnValue = true;
Try
{
if (str!= "" && str!= NULL)
{
String sqlstr = "";
if (sqlstr = = "" | | SQLSTR = null)
{
Sqlstr = "' |and|exec|insert|select|delete|update|count|*|chr|mid|master|truncate|char|declare";
}
string[] Anysqlstr = sqlstr.split (' | ');
foreach (String ss in Anysqlstr)
{
if (Str.indexof (ss) >= 0)
{
ReturnValue = false;
}
}
}
}
Catch
{
ReturnValue = false;
}
Return returnvalue;
}
#endregion
}
 

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.