Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does SqlCommand sanitize parameters?

Using SqlParameters is a recommended method to prevent SQL Injection in your database queries. Where can I find the code/function that internally sanitizes these parameters? I'd like to re-use this function in a custom implementation of mine. I tried to find it using Reflector, but was unsuccessful.

like image 645
Josh Stodola Avatar asked May 29 '09 14:05

Josh Stodola


1 Answers

It protects against SQL Injection, not XSS, and there is no code or function that sanitizes the parameter data.

The protection is accomplished by transmitting the parameter values to the server separately from the query string, so that the values are never substituted directly into the sql statement.

So instead of sql server running something like this:

SELECT * FROM [table] WHERE [column] = ParameterValue

It's more as if it ran something like this:

DECLARE @ParamValue int
  -- //@ParamValue variable is populated from the framework in a safe way
SELECT * FROM [table] WHERE [column] = @ParamValue

This is faster and much more secure and robust than a function that would have to evaluate the parameter data. Such a function would need to be very complex (read: error prone) to handle things like custom escape characters and future enhancements.

This neatly side steps the whole issue: data is data, code is code, and never the twain shall meet.


Your comment to the other, now deleted, answer:

If I pass in the value O'Rourke, it encodes it to be O''Rourke so that it doesn't break the query. Correct?

No, that is not correct. The variable is created directly from a data block, and so no special escaping or encoding is needed.

like image 61
Joel Coehoorn Avatar answered Oct 07 '22 03:10

Joel Coehoorn