tags:

views:

59

answers:

3

I have a C# program that I want to dynamically create databases with. Although only privileged users will be using this application, I want to follow best practices security wise. How do I go about doing this? I don't think I can use a parameterized query in this case since I'm not wanting to pass in a string, I want to pass in an identifier.

Here's the insecure way I've got in there now as a placeholder:

using (MySqlConnection connection = new MySqlConnection(connectionString))
        using (MySqlCommand command = connection.CreateCommand())
        {
            connection.Open();
            command.CommandText = "DROP SCHEMA IF EXISTS " + schema;
            command.ExecuteNonQuery();
            command.CommandText = "CREATE SCHEMA " + schema;
            command.ExecuteNonQuery();
        }

Any ideas on this?

A: 

simply run a regular expression against schema to verify that it is a valid name? (contains no spaces, colons etc). I'm not sure if you can or can't use parameterised queries in this case, but if you do, it will fail creating a database called TRANCATE TABLE users; anyway :)

clocKwize
So your suggestion is to simply be really careful? I suppose that would work. I was hoping there was an industry standard way of doing things.
Jason Thompson
yeah, same you do with any user input, validate it against a set of rules to ensure it is valid.
clocKwize
A: 

I don't know why do you want to create databases dynamically, but I think the correct way of doing this is not to generate databases dynamically.

The only exception I can think of is if you were creating your own database management system. If that's the case, maybe you could look at the source code of some open source MySQL database manager, like phpMyAdmin. (I don't know any for .Net.)

svick
The reason why I'm wanting to dynamically create a database is because I'm writing an multi tenant application and I want allow the admin of the app to be able to provision a new customer on the fly without my intervention. That being said, do you have a better way other than dynamically creating the database at request?
Jason Thompson
+1  A: 

You can use the backtick delimiter to ensure the strings are correctly quoted and ensure that whatever is entered by the user is used as a literal identifier.

See: http://dev.mysql.com/doc/refman/5.0/en/identifiers.html and http://stackoverflow.com/questions/261455/using-backticks-around-field-names

That way the command that is passed to the server would look like: "DROP SCHEMA IF EXISTS foo" which will tolerate using reserved words and other incorrect string values as identifiers.

Joe Kuemerle