Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent a SQL Injection escaping strings

Tags:

I have some queries (to an acccess database) like this :

string comando = "SELECT * FROM ANAGRAFICA WHERE E_MAIL='" + user + "' AND PASSWORD_AZIENDA='" + password + "'";

and I'd like to "escape" user and password, preventing an injection.

How can I do it with C# and .NET 3.5? I'm searching somethings like mysql_escape_string on PHP...

like image 217
markzzz Avatar asked Jul 01 '11 12:07

markzzz


People also ask

Does escaping string prevent SQL injection?

Character EscapingCharacter escaping is an effective way of preventing SQL injection. Special characters like “/ — ;” are interpreted by the SQL server as a syntax and can be treated as an SQL injection attack when added as part of the input.

How can SQL injection be prevented?

How to Prevent an SQL Injection. The only sure way to prevent SQL Injection attacks is input validation and parametrized queries including prepared statements. The application code should never use the input directly. The developer must sanitize all input, not only web form inputs such as login forms.

What is the best defense against SQL injection?

You should always use parameterized statements where available, they are your number one protection against SQL injection. You can see more examples of parameterized statements in various languages in the code samples below.


2 Answers

Don't escape the strings to start with - use a parameterized query. Benefits of this over escaping:

  • The code is easier to read
  • You don't have to rely on getting the escaping correct
  • It's possible that there are performance improvements (DB-specific etc)
  • It separates "code" (the SQL) from the data, which is just good sense logically
  • It means you don't need to worry about data formats for things like numbers and dates/times.

The docs for SqlCommand.Parameters give a good, complete example.

like image 40
Jon Skeet Avatar answered Oct 01 '22 17:10

Jon Skeet


You need to use parameters. Well dont have to but would be preferable.

SqlParameter[] myparm = new SqlParameter[2];
myparm[0] = new SqlParameter("@User",user);
myparm[1] = new SqlParameter("@Pass",password);

string comando = "SELECT * FROM ANAGRAFICA WHERE E_MAIL=@User AND PASSWORD_AZIENDA=@Pass";
like image 60
Jethro Avatar answered Oct 01 '22 16:10

Jethro