views:

168

answers:

6

Hi I was wondering if anyone knew of some good websites detailing prevention for SQL injection for .NET web applications. Any resources would be greatly appricated, thank you.

+1  A: 

If you use the SqlCommand.Parameters collection to pass parameters and never inject user text into you Sql query text, there's no risk.

Think Before Coding
+5  A: 

I think that, if you google a bit on 'preventing sql injection in .NET', you'll find lots of good resources. :)

Anyway, one very important thing, is to not use string-concatenation in order to build your queries. Instead, use parametrized queries. ADO.NET allows to do this, in a very easy way:

string sql = "SELECT * FROM Persons WHERE Persons.Lastname LIKE @p_Name";

SqlCommand cmd = new SqlCommand (sql);

cmd.Parameters.Add ("@p_Name", SqlDbType.Varchar).Value = textBox1.Text + "%";
Frederik Gheysels
A kind of "SQL injection" is still possible in your example code - you should escape wildcard characters (%,_,[, etc...) in textBox1.Text. See: "Using Wildcard Characters as Literals" on http://msdn.microsoft.com/en-us/library/aa933232(SQL.80).aspx
Danko Durbić
Also, string concatenation is okay, as long as the value substitution comes via parameters.
Joel Coehoorn
Yep, no injection risk here.
Think Before Coding
No risk of SQL injection, but of "LIKE pattern"-injection (what if the user enters %), which is not as dangerous, but may return unwanted results.
Danko Durbić
See also: http://stackoverflow.com/questions/258757/escape-a-string-in-sql-server-so-that-it-is-safe-to-use-in-like-expression
Danko Durbić
A: 

the first thing to know is to parameterize your queries or use stored procs....

Never use ad-hoc sql in code where you just append the value

give only read and write permissions (or only read for those pages that should not write)

SQLMenace
+1  A: 
  • golden rule: never concatenate user input
  • if you write your own command strings in .NET, use the Parameters collection
  • if you use LINQ, it will usually do it for you
  • if you write commands in TSQL, use sp_executesql or your vendor's equivalent
Marc Gravell
A: 

Here's a good resource on parametrization of SQL. And some more stuff on security in general.

brian
A: 

The MSDN Magazine article Stop SQL Injection Attacks Before They Stop You seems to be fairly complete.

While containing less detailed information about your specific question, SDL Embraces The Web is a good source of other things you should be thinking about in addition to preventing SQL injection attacks.

The usual disclaimers apply, I don't necessarily agree with all of the information presented in those articles, but the information presented will hopefully get you thinking about ways SQL injection (and other) attacks can be mitigated on a public website.

Grant Wagner