How does a SQL Injection happen?

11

Why creating parameters for each field that will be updated helps prevent SQL Injection? Example:

SqlCommand comm = new SqlCommand("UPDATE Contatos Set Telefone = @Telefone, " +
                             "Cidade = @Cidade, " +
                             "Email = @Email, " +
                             "Endereco = @Endereco " +
                             "WHERE Nome = @Nome", conn);
comm.Parameters.AddWithValue("@Telefone", txtTelefone.Text);
comm.Parameters.AddWithValue("@Cidade", txtCidade.Text);
comm.Parameters.AddWithValue("@Email", txtEmail.Text);
comm.Parameters.AddWithValue("@Endereco", txtEndereco.Text); 
comm.Parameters.AddWithValue("@Nome", txtNome.Text);
    
asked by anonymous 27.11.2015 / 16:23

2 answers

7
  

How does a SQL Injection happen?

Let's change your example a little bit:

SqlCommand comm = new SqlCommand("UPDATE Contatos Set Telefone = '" + txtTelefone.Text +  "'" +
                         "WHERE Nome = @Nome", conn);

Suppose now that I type in txtTelefone the following command:

0 where 1=0; drop database MeuSistema;

Depending on the user's permission, do you agree that the entire database can be deleted?

This is SQL Injection . Usually it is not used to erase databases, but to include false information to hijack the system or change its behavior.

This is quite common in weak and open source frameworks. There are sources of information on the Internet specializing in attacks on certain frameworks. Closed code can also happen.

  

Why creating parameters for each field that will be updated helps prevent SQL Injection?

Because the parameters are evaluated before they are entered. In this example with AddWithValue() the check is not very efficient because there is no check of the data type of the parameter. Here you talk more about .

For these cases, prefer the method Add() . :

comm.Parameters.Add("@Telefone", SqlDbType.Int);
    
27.11.2015 / 16:34
3

These methods know how to clean content. They remove any potentially dangerous text. Since something is very limited there, ie just numbers or a text like string (between quotation marks), anything that runs away from it is considered junk and is discarded. So elements that are part of the SQL syntax can not be injected into the query by changing its content.

The injection problem occurs by constructing the query text freely, accepting anything as valid. Protection comes just by letting only a few very specific parts be used flexibly and come from an external source.

    
27.11.2015 / 16:33