Search code examples
c#.netsecuritysql-injection

Ensure that a string is not an sql command


is there something like

CheckStringForSql(string);

for C#?

I know that I can use parameters, but one of my stored procedures uses sp_executeSQL with a parameter that comes from an xml document. So theoretically anyone can run sql commands, if they know where to put them in.

Any ideas?


Solution

  • The correct way to avoid SQL injection is through parameterized queries, which actually encode any values that wouldn't fit properly into the SQL context they're being injected into.

    Supposing there's a vast bulk of legacy code that you know is vulnerable to SQL injection, you could still try checking for suspicious values on input in another part of your code. For example, by default ASP.NET tries to prevent javascript/HTML injection using a filter on every request.

    But this approach is open to false-positives, where you reject perfectly legitimate data because it looks like it was intended to be an injection attack. And it's not nearly as reliable as writing your data-access code with best practices in the first place.