Asp.net anti-injection code
Last Update:2018-12-07
Source: Internet
Author: User
/// <Summary>
/// Add the startprocessrequest () function to application_beginrequest ()
/// </Summary>
Protected void application_beginrequest (Object sender, eventargs e) {startprocessrequest ();
}
# Region SQL injection attacksCodeAnalysis
/
// <Summary>
/// Process user-submitted requests
/// </Summary>
Private void startprocessrequest ()
{
Try
{
String getkeys = "";
String sqlerrorpage = "/default. aspx"; // If an invalid parameter exists, go to the error prompt page.
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;
If (! Processsqlstr (system. Web. httpcontext. Current. Request. querystring [getkeys])
{
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;
If (getkeys = "_ viewstate") continue;
If (! Processsqlstr (system. Web. httpcontext. Current. Request. Form [getkeys])
{
System. Web. httpcontext. Current. response. Redirect (sqlerrorpage );
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;
If (! Processsqlstr (system. Web. httpcontext. Current. Request. Cookies [getkeys]. tostring ()))
{
System. Web. httpcontext. Current. response. Redirect (sqlerrorpage );
System. Web. httpcontext. Current. response. End ();
}
}
}
}
Catch
{
// Error handling: process user submitted information!
}
}
/// <Summary>
/// Analyze whether the user request is normal
/// </Summary>
/// <Param name = "str"> input user to submit data </param>
/// <Returns> whether SQL injection attack code is returned </returns>
Private bool processsqlstr (string Str)
{
Bool returnvalue = true; t
Ry
{
If (Str. Trim ()! = "")
{
String sqlstr = "and | exec | insert | select | Delete | update | count | * | CHR | mid | master | truncate | char | declare ";
String [] anysqlstr = sqlstr. Split ('| ');
F
Oreach (string SS in anysqlstr)
{
If (Str. tolower (). indexof (SS)> = 0)
{
Returnvalue = false;
Break;
}
}
}
}
Catch
{
Returnvalue = false;
} Return returnvalue;
}
# Endregion [/PRE]