How can I avoid SQL injection attacks in my ASP.NET application?
I need to avoid being vulnerable to SQL injection in my ASP.NET application. How might I accomplish this?
Even though your question is very generic, a few rules always apply:
- Use parameterized queries (
SqlCommand
withSqlParameter
) and put user input into parameters. - Don't build SQL strings out of unchecked user input.
- Don't assume you can build a sanitizing routine that can check user input for every kind of malformedness. Edge cases are easily forgotten. Checking numeric input may be simple enough to get you on the safe side, but for string input just use parameters.
- Check for second-level vulnerabilites - don't build SQL query strings out of SQL table values if these values consist of user input.
- Use stored procedures to encapsulate database operations.
Use Prepared Statements (link to an ASP.NET tutorial that uses prepared statements in the 'To add nodes for products' section). that's all there is to it.
Well, that or use an ORM, like Linq to SQL or NHibernate, they internally use prepared statements.
Use parameters! It really is that simple :-)
Create your queries like this (for MS Sql server with C#):
SqlCommand getPersons = new SqlCommand("SELECT * FROM Table WHERE Name = @Name", conn);
Here @Name is the parameter where you want to avoid sql injection and conn is an SqlConnection object. Then to add the parameter value you do the following:
getPersons.Parameters.AddWithValue("@Name", theName);
Here theName is a variable that contains the name you are searching for.
Now it should be impossible to do any sql injections on that query.
Since it is this simple there is no reason not to use parameters.
Never trust user input - Validate all textbox entries using validation controls, regular expressions, code, and so on
Never use dynamic SQL - Use parameterized SQL or stored procedures
Never connect to a database using an admin-level account - Use a limited access account to connect to the database
Don't store secrets in plain text - Encrypt or hash passwords and other sensitive data; you should also encrypt connection strings
Exceptions should divulge minimal information - Don't reveal too much information in error messages; use customErrors to display minimal information in the event of unhandled error; set debug to false
Useful link on MSDN Stop SQL Injection