SQL Injection or Script injection - MVC-5 - Is it a concern?

1

I am developing an application in MVC-5 and I have read several articles on SQL Injection.

I would like to know if I have to take any security measures or modify my selects, or if the MVC-5 already has a shield against this situation.

Throughout my project I'm using the format below to select data from my tables:

string query = "SELECT * FROM TABELA WHERE CHAVE = '"+CH+"'";
            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
            using (var command = new SqlCommand(query, connection))
            {
                connection.Open();
                using (var reader = command.ExecuteReader())
    
asked by anonymous 05.01.2017 / 22:18

2 answers

2

I think there is a confusion between technologies.

ASP.NET MVC is a framework for WEB, as such it is able to protect against:

  • HTML Injection, when someone places HTML tags in a text field for example.
  • Script Injection, when someone puts a script tag in a text field for example.

For these two, the validation is double, it does not let enter this type of string, but if you force it to allow it it will do HTML Encoding when it will show on the screen to ensure that these tags appear in plain text and not HTML, making them harmless.

It still has cross-scripting protection, using a ValidationToken.

All this has to do with a WEB interface, which is what MVC is.

Now SQL Injection, who can provide you with a ready security is the Entity Framework. It is highly recommended to use it. It will sanitize any value before putting it into a query. Even you no longer need to do queries, just use lambda expressions.

Your example would look like: var dado = db.Tabela.Where(x=> x.Chave == CH).SingleOrDefault();

It will clean the value of CH to avoid dangerous characters like SQL comments, single quotes and etc ...

But there are many ways to protect yourself, however, most are not "pre-ready."

I hope it helps ...

    
20.04.2017 / 12:01
1

Instead of concatenating strings to form your query. use Parameters.Add of SqlCommand to prevent Sql Injection.

The following example applies to your code:

string query = "SELECT * FROM TABELA WHERE CHAVE = @CH";

using (var command = new SqlCommand(query, connection))
{
    SqlParameter param  = new SqlParameter();
    param.ParameterName = "@CH";
    param.Value         = CH;

    command.Parameters.Add(param);        

    connection.Open();

    using (var reader = command.ExecuteReader())
    
20.04.2017 / 15:41