views:

204

answers:

1

I need to work around an NHibernate bug I reported here. Essentially, NHibernate will generate multiple SQL parameters for the same HQL parameter, which results in problems for queries that use a parameter in a grouping construct.

Until the bug is fixed, I figured I'd just concatenate the parameter into the HQL. Obviously this is susceptible to SQL injection unless I escape the parameter value (since it's HQL, I can't use regular ADO.NET parameters).

Is there a method within System.Data somewhere that will escape a parameter value, making it safe to concatenate into a SQL string? I'm using SQL Server 2005, and I'm happy to do something specific to that platform for the short term until the NHibernate bug is fixed.

Thanks, Kent

+1  A: 

To my knowledge there is nothing available for you to use (something similar to the Oracle DBMS_ASSERT library would work if it were available in Sql Server). One thing you could do that would protect you would be to simply check your parameter value (i.e. what you are going to concatenate) for any whitespace at all and throw an exception if it includes it - this should protect you against anything destructive in terms of injection. Naturally, this will only be a viable solution if you are concatenating a parameter that doesn't require the ability to find values that actually do contain whitespace, however I would think that would be a limited scenario.

chadhoc
Alas, that is exactly my scenario. It's basically a category name that I'm matching against, which can include whitespace. At worst I will be checking for quotes and throwing if there are any in the parameter value.
Kent Boogaart
Ha, figures that would be the case. If you read through this other SO thread (here: http://stackoverflow.com/questions/1800013/does-this-code-prevent-sql-injection), it provides some pretty good code that will protect against a vast majority of things, but you'll almost always be susceptible to non-printable key attacks (i.e. backspacing).
chadhoc
Cool - thanks. For now I've added a very restrictive check to ensure the input matches a regex of `@"^[A-Za-z\:\, ]*$"`. If not, an exception is thrown.
Kent Boogaart