Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating database in C# and SQL injection

I have the following code used to create some database from 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 worry if it is safe, will C# accept hacker input like "A; DROP TABLE B" or something similar? How to make it safer?

like image 632
RRM Avatar asked Feb 26 '13 15:02

RRM


People also ask

Can you create a database in C?

Creating a database application in C/C++ is a daunting task, especially for a novice programmer. Although the actually code is quite simple, it is the configuration issues such as importing right library, drivers to use, how to access them, and so forth, that make it an uphill battle.

What is a database in C?

For C projects, the database schema is specified in the eXtremeDB Data Definition Language (DDL) which identifies the database, defines each data class, its elements, its relationship to other data classes, and data access methods.

Is C good for databases?

C is used if you need absolutely predictable behavior, such as in core OS code, embedded devices, drivers, other types of system code, or often database engines (where I've used it most). C++ is more for larger projects of the sort where you may otherwise use Java but you need better performance or have legacy code.


1 Answers

Table Names and columns names cannot be parameterized but for the first line of defense, wrap the tablename with delimiter such as braces,

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

or create a user define function that checks for the value of the input, eg

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

then on 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
}
like image 168
John Woo Avatar answered Oct 05 '22 10:10

John Woo