Sanitising inputs when creating a sql string by concatenation in C#

  • I'm not sure if this is really the right sub forum but it seemed the closest fit. It's really about .Net development against SQLServer in general than anything to do with 2014 specifically. If I've miss-fired feel free to move the thread.

    A bit of background : I have a need to create a table in a sql server database from C# code. The kicker is that the user must be able to specify the table and field names via the UI. I can do a bit of sanity checking but as long as they enter something reasonable I need to accept it. Normaly I always ADO parameters to sanitise any user parameters but they can't be applied to table and field names, only values. As far as I'm aware that leaves me needing to concatenate strings and that's something I usually avoid like the plague due to risk of SQL injection.

    My actual question : Assuming string concatenation is my only way forward (if that assumptions flawed, please point me in a better direction) how can I sanitise the values that would go into the table name and fieldname bits of a CREATE TABLE statement to ensure that injection can't occur? I've been pondering it and I think I just need to check for semi-colons. Without a semi-colon I don't think a user could inject an extra statement could they? I'm just feeling a bit paranoid that I've missed something.

    Any advice on the specific question or just on a better overall aproach would be greatly apreciated

  • Lowering security permissions to minimum should help too.

    GRANT CREATE TABLE to user

    and ALTER permission on the schema should be enough:

    Link 1, Link 2

  • You could create the table with a placeholder name you generate, then use sp_rename @generatedName, @userName; to pass the user defined name as a parameter so that you don't have to concatenate it into a string.

    You could probably do something similar with the columns you were creating. Pass them into the proc in a table variable, then iterate over them and issue a series of alter commands.

    It should go without saying, but I'm sure you realize something that is altering the DB schema should probably be locked down pretty hard from the front end in any case.

  • You could create the table with a placeholder name you generate, then use sp_rename @generatedName, @userName; to pass the user defined name as a parameter so that you don't have to concatenate it into a string

    I like your thinking. I wasn't aware of that sp so will have to give it a look.

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply