Can MVC.NET prevent SQL-injection at razor or controller level?

4.2k views Asked by At

Has MVC.Net any system to prevent SQL injection attack or I should check it manually in my code?

3

There are 3 answers

2
Marged On

This is independant of the frontend, means to prevent this depend on the language you use and the features of your database connection.

Normally you simply use stored procedures to circumvent injection attacks

See here for an example.

0
GSerg On

Has MVC.Net any system to prevent SQL injection attack?

No, it does not. MVC is completely unaware of SQL servers. It is not its area of responsibility.

I should check it manually in my code?

No. Absolutely not. If you rely on a string check to see if the user's input is intended to create an SQL injection, you will get it wrong. Even if you eventually get it right (at which point your validation code might get really long and complicated), all this effort will be in vain because you never needed to do it in the first place.

What you should do is always use parameters in your queries and never construct an SQL statement via string concatenation. If you are using a sane ORM framework, it will do that for you.

This advice does not change with or without the use of ASP.NET MVC.

0
fdomn-m On

Has MVC.Net any system to prevent SQL injection attack

No, because this is outside the scope of 'MVC'.

MVC deals with the front-end, while SQL injection attacks occur at the back-end. MVC does not know how you are persisting your data, eg Entity-Framework, nHibernate, ADO directly or your own ORM.

should I check in my own code

from the comments, this appears to mean: should I check in my own ORM.

Yes. Always. Regardless of what you are using as a front-end, your own ORM should check (or, more specifically, not allow by design) SQL injection attacks.

This leads to the question:

can MVC check for this

Yes - you can write a custom validator attribute to apply to your poco properties to check for some potential SQL injection attacks.

I say earlier, "not allow by design" because there is no way you will be able to check for 100% of all possible current and future SQL injection methods for all of the DB engines that your ORM handles.

You'll also need to consider that 'attacks' will be different per DB engine (Oracle, TSQL, nosql), so any UI check will need to be aware of the DB engine currently in use.