views:

59

answers:

3

Are Parametrize Queries in .NET safe from SQL Inject? That is, does .NET automatically escape dangerous characters when you use Parameters?

+11  A: 

When you use parameters, they typically won't be sent as text in the first place. They can use the native wire protocol for the database. If the parameter is a text parameter itself, then it will typically be encapsulated appropriate in the protocol so that the database knows it's a parameter rather than SQL.

While I guess a provider could just translate the parameters into a full SQL statement, it would be an awful way of doing things.

So basically "yes" - parameterised queries are effectively safe from SQL injection attacks, so long as you don't have stored procedures dynamically executing your parameters as SQL, etc.

Jon Skeet
+2  A: 

When you use parameters, .Net's SQL client will send the parameter values to SQL server in the raw TDS stream.

However, this does not protect you from bad SQL.
If your SQL calls EXECUTE with a string that contains a concatenated parameter, you'll still be vulnerable.

SLaks
A: 

As far as string values, yes - .NET will escape them for you, which you can see by trying to find values in a table like "--comment", which would break a concatenated statement, but which work fine with a parameterized query.

As Jon states, though, things like numbers and dates will be sent in their native format, which is safer/faster still.

rwmnau
I'm not sure I'd say they're really being *escaped* as such - they're likely to be encapsulated in such a way that removes the requirement for escaping. It's more likely to be "the next 20 bytes form a string parameter encoded in UTF-8" - it won't matter if that data includes quotes etc, as it won't be treated as SQL.
Jon Skeet
Indeed - "encapsulated" is a much more accurate way to say it, since "escaping" is only something you do when the parser has special characters you can't use, which doesn't apply in this case.
rwmnau