Creating a database in C # and SQL injection

I have the following code used to create some database from a C # application

SqlConnection myConnection = new SqlConnection(ConnectionString);
string myQuery = "CREATE DATABASE " + tbxDatabase.Text; //read from textbox
myConnection.Open();
SqlCommand myCommand = new SqlCommand(myQuery, myConnection);
myCommand.ExecuteNonQuery();

Now I'm worried if this is safe, will C # accept the hacker's input as “A; DROP TABLE B” or something like that? How to make it safer?

+5
source share
5 answers

Table and column names cannot be parameterized, but for the first line of protection, wrap the table name with a delimiter, such as curly braces,

string myQuery = "CREATE DATABASE [" + tbxDatabase.Text + "]";

or create a user definition function that checks the input value, for example

private bool IsValid(string tableName)
{
    // your pseudocode
    // return somthing
}

then in your code

if (IsValid(tbxDatabase.Text))
{
    SqlConnection myConnection = new SqlConnection(ConnectionString);
    string myQuery = "CREATE DATABASE [" + tbxDatabase.Text + "]";
    myConnection.Open();
    SqlCommand myCommand = new SqlCommand(myQuery, myConnection);
    myCommand.ExecuteNonQuery();
}
else
{
    // invalid name
}
+4
source

, , - , , .

# ypu ,

+1

+1

.

.

EDIT: , , CREATE , .

, , , . , -, a-z, A-Z.

0

- sql QUOTENAME(), .

CREATE PROC example_create_db ( @db_name NVARCHAR(256) )
AS 
    BEGIN
        DECLARE @sql NVARCHAR(1000)
    /*
        QUOTENAME() adds the surrounding []'s
    */

        SET @sql = 'CREATE DATABASE ' + QUOTENAME(@db_name) 
        EXEC sp_executesql
    END
0

All Articles