ASP. NET MVC 5 filters The action parameter with filter to prevent SQL injection, making your code safe and concise

Source: Internet
Author: User
Tags comment tag sql injection

The risk of SQL injection is implicit in the process of developing a program that is slightly unnoticed. Today I'm going to say, ASP. NET MVC 5 uses the filter action parameter to prevent SQL injection, making your code safe and concise. You do not have to check the values of the parameters at each place to see if the user has entered the contents of a dangerous SQL. If there are several drawbacks to each place:

1. Heavy workload

2. Easy to omit

3, not easy to maintain

I'm going to write a filter to prevent SQL's attribute class, to handle the action before the action is executed, and if there is a SQL statement with its value, the illegal characters will be replaced with an empty string.

An example of SQL injection:

The above input has two input boxes, and the user can enter any value, including the value with SQL injection.

Background code:

AdminController.cs

 public  class   Admincontroller:controller { public  A Ctionresult Index (string  name = , string  loginName = , int  page = 1              {viewbag.name  = Name;            Viewbag.loginname  = LoginName;  var  r = dadmin.getlist (name, LoginName, page, 2              return   View (r); }    }}

DAdmin.cs:

 Public classdadmin{ Public StaticPagedataview<msys_admin> GetList (stringNamestringLoginName,intPageintPagesize=Ten) {Pagecriteria criteria=NewPagecriteria (); Criteria. Condition="1=1"; if(!string. IsNullOrEmpty (name)) criteria. Condition+=string. Format ("and Name like '%{0}% '", name); if(!string. IsNullOrEmpty (LoginName)) criteria. Condition+=string. Format ("and LoginName like '%{0}% '", LoginName); Criteria. CurrentPage=page; Criteria. fields="*"; Criteria. PageSize=pageSize; Criteria. TableName="Sys_admin a"; Criteria. PrimaryKey="UID"; varr = common.getpagedata<msys_admin>(criteria); returnR; }}

The above two parameters of the user input name and LoginName do not determine whether there is an illegal SQL injection character, it is directly stitched into the SQL statement, to the database execution, this is very dangerous.

1, such as the user in the name input such content:

%‘--%

The concatenation of the SQL statement is a

SELECT * from Sys_admin WHERE Name like '% '--% '

This "--" is the SQL statement after the comment tag and then stitching the SQL statements as comments, so that the effective is the SQL statement:

SELECT * from Sys_admin WHERE Name like '% '

This indicates that all records are displayed. If the SQL is logged in, the authentication of the user name and password will be skipped.  

2, if the user name input with insert or delete or drop, such as:

Namer person value:% ';D elete from sys_admin--%

The stitched SQL becomes:

SELECT * from Sys_admin WHERE Name "% ';D elete from sys_admin--% '

Such an execution will delete all records of the Sys_admin table.

Summary: you can see how dangerous this SQL injection is.

II. solving MVC SQL injection Scenario 1, defining a string helper class to prevent SQL injection
{     Public Static stringFiltersql (strings) {if(string. IsNullOrEmpty (s))return string.        Empty; S=S.trim ().        ToLower (); S=Clearscript (s); S= S.replace ("=",""); S= S.replace ("'",""); S= S.replace (";",""); S= S.replace ("or",""); S= S.replace ("Select",""); S= S.replace ("Update",""); S= S.replace ("Insert",""); S= S.replace ("Delete",""); S= S.replace ("Declare",""); S= S.replace ("exec",""); S= S.replace ("Drop",""); S= S.replace ("Create",""); S= S.replace ("%",""); S= S.replace ("--",""); returns; }}

This class replaces the SQL-related strings above.

2. Define an attribute class to check and process the action parameter
 Public classantisqlinjectattribute:filterattribute,iactionfilter{ Public voidonactionexecuted (ActionExecutedContext filtercontext) {} Public voidonactionexecuting (ActionExecutingContext filtercontext) {varActionparameters =filterContext.ActionDescriptor.GetParameters (); foreach(varPinchactionparameters) {            if(P.parametertype = =typeof(string))            {                if(Filtercontext.actionparameters[p.parametername]! =NULL) {Filtercontext.actionparameters[p.parametername]=Stringhelper.filtersql (Filtercontext.actionparameters[p.parametername].                ToString ()); }            }        }    }}

Description: This attribute class is inheriting the class FilterAttribute and implementing the interface Iactionfilter, where the method onactionexecuting handles the arguments of the action, OnActionExecuting is the method that runs before the action executes, and onactionexecuted is the method that runs after the action executes.

P.parametertype = = typeof (String)

Because SQL injection is only possible when the parameter type is a string, only arguments that have the action argument as a string are processed here.

Filtercontext.actionparameters[p.parametername] =
Stringhelper.filtersql (Filtercontext.actionparameters[p.parametername]. ToString ());
is to replace the original value with the value of the safe action parameter after filtering.

3. Preventing SQL injection feature classes from being used in MVC controllers
 public  class   admincontroller:controller{[Antisqlinject]  pub Lic  actionresult Index (string  name = , string  loginName = , int  page = 1  ) {ViewBag .        Name  = name;        Viewbag.loginname  = LoginName;  var  r = dadmin.getlist (name, LoginName, page, 2          return   View (r); }}

A SQL check of the action's arguments is required, using only the attribute class Antisqlinject, which is previously defined above. This feature class can be used in any need to prevent SQL injection on the action, do not have to move the opponent to filter all the parameters obtained in the program, safe, convenient and concise.

ASP. NET MVC 5 filters The action parameter with filter to prevent SQL injection, making your code safe and concise

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.