Prevent SQL Injection in SELECT statement - c#

I am using VS2005 C# ASP.NET and SQL Server 2005.
I have a search function on my asp page and I feel that my SELECT query is vulnerable to SQL injection.
This is my current SELECT statement:
string LoggedInUser = (User.Identity.Name);
SqlDataSource1.SelectCommand = "SELECT * FROM [TABLE1] where [" + DropDownList1.Text + "] like '%" + searchTB.Text + "%' AND [empUser] LIKE '%"+LoggedInUser+"%'";
SqlDataSource1.DataBind();
*where searchTB is my search text box; DropDownList1 is my search category; and LoggedInUser is the username of the logged in user.
I have implemented parameter instead of concatenation in one of my INSERT statement:
string sql = string.Format("INSERT INTO [TABLE2] (Username) VALUES (#Username)");
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("Username", usernameTB.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
I would like to change my SELECT statement like my INSERT statement, using parameter instead. May I know how should I change it?
Thank you

You can add parameters to your selectcommand using
SqlDataSource s = new SqlDataSource();
s.SelectParameters.Add("paramName", "paramValue");
There are other parameter collections for delete, update and insert too.
s.DeleteParameters
s.UpdateParameters
s.InsertParameters
More Information:
MSDN: SqlDataSource.SelectParameters Property
Programmatically Using SqlDataSource
hope this helps

See Using Parameters with the SqlDataSource Control
And SqlDataSource.SelectParameters Property
You can specify SelectParameters Property for SqlDataSource to use parameterized SQL query

Write a method that gets the data sourse and use sql parameters for the query. Here is a good example how to add parameters in a command object
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#ID", SqlDbType.Int);
command.Parameters["#ID"].Value = customerID;
I would use a method for the query so that I separate the Database Access from the UI functionality. Also, this allows to reuse the query.

It's not a straightforward task to dynamically specify a fieldname in query, so I'd suggest just doing switch/case validation for field name, like this:
switch (DropDownList1.Text)
{
case "ValidField1":
case "ValidField2":
...
break;
default:
throw new ArgumentException(...); // or prevent query execution with some other statement
}
SqlDataSource1.SelectCommand = "SELECT * FROM [TABLE1] where [" + DropDownList1.Text + "] like #value AND [empUser] LIKE #user";
SqlDataSource1.SelectParameters.Add("value", "%" + searchTB.Text + "%");
SqlDataSource1.SelectParameters.Add("user", "%"+LoggedInUser+"%");
SqlDataSource1.DataBind();

You can simply use a filter expression for the SQL datasource SQL Datasource filter expression
You can write your own select function method with object datasource/datatable

Related

Search Database for rows, whose Column contains a specific string [Search-Query]

I was wondering why this SQL Query doesn't return anything:
mySqlCommand.CommandText = "SELECT * FROM `users` WHERE Username LIKE %#Username% ORDER BY Id DESC";
mySqlCommand.Parameters.AddWithValue("#Username", this.search.Text);
IT's not a reader problem or anything like this, if i remove "WHERE Username LIKE %#Username% ", it works fine.
I call this whole MySQL-Query in a KeyPress-Event of a Textbox.
this.search is the Textbox. I want to search for rows where the Username Column contains the Characters i entered in the Textbox.
Try to use
//For LIKE query
SqlParameter parameter = new SqlParameter("#query", SqlDbType.NVarChar);
parameter.Value = string.Format("%{0}%", this.search.Text);
IList<Users> results = ctx.Database.SqlQuery<Users>("SELECT * FROM Users WHERE Username LIKE #query", parameter).ToList();
I solved it using this:
mySqlCommand.CommandText = "SELECT * FROM `users` WHERE Username LIKE #Username ORDER BY Id DESC";
mySqlCommand.Parameters.AddWithValue("#Username", "%" + this.search.Text + "%");
I would strongly recommend using a stored procedure, will help against SQL Injection attacks, and you want to disallow your app to use insert, update and delete scripts and only allow it to use execute statements for stored procedures.
But you want to change this line from
mySqlCommand.CommandText = "SELECT * FROMusersWHERE Username LIKE %#Username% ORDER BY Id DESC";
to
mySqlCommand.CommandText = "SELECT * FROMusersWHERE Username LIKE '%#Username%' ORDER BY Id DESC";

Using parameters in sql query to determine which column to use

I am trying to pull data from my table based on the button a user clicks, so if they click the 1940's button it will pull all products from that decade but I cant get the query to work. It has to do with the #decade parameter because that is where I am getting the user input from but it doesnt like it when I am trying to choose a column using that parameter
ImageButton decadeBtn = (ImageButton)sender;
var decade = decadeBtn.CommandArgument;
yearHead.InnerText = decade.ToString();
string cmd="";
DataSet ds;
if (typeOfArchive == "On Hand")
{
cmd = #"Select * From ARCHIVE_DECADE_TBL WHERE DECADE_#decade=#decade AND PRODUCT_LINE=#Line AND LOCATION is not null;";
}
else if(typeOfArchive == "All Other"){
cmd = #"Select * From ARCHIVE_DECADE_TBL WHERE DECADE_#decade=#decade AND PRODUCT_LINE=#Line AND LOCATION is null";
}
using (OleDbConnection dbConn = new OleDbConnection(connectionString))
using (OleDbDataAdapter dbCmdDecade = new OleDbDataAdapter(cmd, dbConn))
{
dbConn.Open();
dbCmdDecade.SelectCommand.Parameters.Add("#decade", OleDbType.Integer).Value = decade;
dbCmdDecade.SelectCommand.Parameters.Add("#line", OleDbType.VarChar).Value = productLine;
ds = new DataSet();
dbCmdDecade.Fill(ds, "products");
}
No you can't use a parameter in that way. As a rule, you cannot use a parameter to define a column name or a table name (or concatenating it to form a column name). A parameter could only be used to define a value used in the query. (or with a stored procedure to create an SQL Text inside the sp to be executed but that is another more complex story),
However, assuming that you are not allowing your users to type directly the decade value (Sql Injection vulnerability), then it is pretty simple to create a string with the column name desidered and use it in your query.
Add a method that just concatenate together you decade string with your prefix for the DECADE column
private string GetDecadeColumn(string decade)
{
return "DECADE_" + decade;
}
and in you query
if (typeOfArchive == "On Hand")
{
cmd = #"Select * From ARCHIVE_DECADE_TBL WHERE " +
GetDecadeColumn(decade) +
" AND PRODUCT_LINE=#Line AND LOCATION is not null;";
}
else if(typeOfArchive == "All Other"){
cmd = #"Select * From ARCHIVE_DECADE_TBL WHERE " +
GetDecadeColumn(decade) +
" AND PRODUCT_LINE=#Line AND LOCATION is null";
}
So ARCHIVE_DECADE_TBL has columns that are named something like DECADE_1990 with a value of 1990, DECADE_2000 with a value of 2000, etc?
It really should be designed to just be called "DECADE" with the value being 1990/2000/etc, but if that's not possible, you'll have to build your query dynamically. I don't believe those parameters will work to set the column name. They can set a value to check for, but not the column names.
You'll have to build the query out manually in c#, so something like:
cmd = #"Select * From ARCHIVE_DECADE_TBL WHERE DECADE_" + decade + #" = #decade AND PRODUCT_LINE=#Line AND LOCATION is not null;";
Now, if I misunderstood and your column is actually named DECADE_#decade, then I think you'll just need to change your variable so it's not #decade, so something like #mydecade. The conflict there will confuse it.
Sooooo like...
cmd = #"Select * From ARCHIVE_DECADE_TBL WHERE DECADE_#decade=#mydecade AND PRODUCT_LINE=#Line AND LOCATION is not null;";
And then down below:
dbCmdDecade.SelectCommand.Parameters.Add("#mydecade", OleDbType.Integer).Value = decade;
That probably shouldn't have an # in the column name though. :)

In C# how to get value from text box using quotes

In my program i need to get value from the database , so using a texbox so that client type anything and i can search from database.
My code is
SqlCommand sqlcmd = sqlcon.CreateCommand();
sqlcmd.CommandText = "Select distinct transactionName from dbo.tbl where terminalId = " + textBox_cardNumber.Text;
the above is not my full code but here in my code i am using textbox_cardNumber ...
I want that in quotes ''
it should be like
Select distinct transactionName from dbo.tbl where terminalId = '0097'
So my question is how to get in quotes???
Use a parameterized query like this
SqlCommand sqlcmd = sqlcon.CreateCommand();
sqlcmd.CommandText = "Select distinct transactionName from dbo.tbl " +
"where terminalId = #id";
sqlCmd.Parameters.AddWithValue("#id", textBox_cardNumber.Text);
....
In this way you defer the job to recognize your data (the textbox text) as a string to the Framework code that knows how to correctly quote your value. Also you remove the possibilities of Sql Injection attacks
"'" + textBox_cardNumber.Text + "'";
I hope I understood you!
You can also try this, but this is not good practice, used always Parameter.
sqlcmd.CommandText = "Select distinct transactionName from dbo.tbl where terminalId = '" + textBox_cardNumber.Text +"'";
You can try this code:
SqlCommand sqlcmd = sqlcon.CreateCommand();
sqlcmd.CommandText = "Select distinct transactionName from dbo.tbl where terminalId = '"
+ textBox_cardNumber.Text+"'";
Instead of string concatenation, you can should use parameterized sql instead. Because this kind of codes are open for SQL Injection attacks.
SqlCommand sqlcmd = sqlcon.CreateCommand();
sqlcmd.CommandText = "SELECT DISTINCT transactionName FROM dbo.tbl
WHERE terminalId = #terminalID";
sqlcmd.Parameters.AddWithValue("#terminalID", textBox_cardNumber.Text);
A side note, take a look at SQL Injection Attacks by Example
You need to make use of prepared statements in which you use parameters.
Otherwise, you need to add quotes around your input string, but it will leave you open for SQL injection

where condition in MySQL Insert statement

Can I use where condition in Insert statement????
I have coded like this, its showng me an error call MySQLException was unhandled, You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE RegistrationID='3'' at line 1. My code:-
MySqlCommand cmd1 = new MySqlCommand("INSERT INTO registration(DueAmount) VALUES ('"+textBox5.Text + "') WHERE RegistrationID='"+textBox2.Text+"'",connection);
You're mixing 2 different statements.
An UPDATE statement updates an existing row in your table.
An INSERT statement adds a new row in your table.
I think you want to use an UPDATE statement and modify an existing row.
MySqlCommand cmd1 = new MySqlCommand("
UPDATE Registration Set DueAmount= '"+textBox5.Text
+ "' WHERE RegistrationID='"+textBox2.Text+"'",connection);
The correct syntax of INSERT doesn't have WHERE clause. I think you want UPDATE instead of INSERT,
UPDATE registration
SET DueAmount = 'txt5'
WHERE RegistrationID = 'txt2'
the only way you can use WHERE in SELECT is when you are using INSERT INTO....SELECT statement.
one more thing, since you are using ADO.NET, make sure that you parameterized your query to avoid SQL Injection, and use USING statement.
string query = "UPDATE registration
SET DueAmount = #dateAmount
WHERE RegistrationID = #RegID"
using (MySqlCommand cmd1 = new MySqlCommand(query,connection))
{
cmd1.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#dateAmount", textBox5.Text);
cmd.Parameters.AddWithValue("#RegID", textBox2.Text);
// other codes
}
INSERT with WHERE doesn't make sense. INSERT always inserts a new row. You might be looking for REPLACE INTO which does a insert if that record doesnt exist or an update if it does based on its primary key.
INSERT puts a new line to database. You can not put a new line WHERE sth is sth. But you can UPDATE it. Hope this helps.
You need to use an UPDATE statement.
tHS SYNTAX IS SIMILAR: "UPDATE registration SET DueAmount = '" + textBox5.Text + "' WHERE RegistrationID='"+textBox2.Text+"'"
You can try with Update
var query = "UPDATE Registration SET DueAmount= $Paremeter1 WHERE RegistrationID = $Paremeter2";
var cmd1 = new MySqlCommand(query, connection);
cmd1 .Parameters.AddWithValue("$Paremeter1", textBox5.Text);
cmd1 .Parameters.AddWithValue("$Paremeter2", textBox2.Text);

SQL Select statement from a webpage control and check relevant check boxes according to result

I have a sql select statement in my VS2005 C# server-side coding for a web application and I am meeting some errors.
Below is a screenshot of the controls in the webpage:
Data Source SqlDataSource1 : Query:SELECT [Name] FROM [Users].
Dropdownlist UserNameList : Lists all userName retrieved from SqlDataSource1.
Checkboxes AdminCb and UserCb : Automatically checks if the userType of the userName is as.
Button loadUser : Gets the user type and checks the check boxes accordingly.
Below is my code for my loadUser button
SqlConnection conn = new SqlConnection("Data Source=DATASOURCE");
string sql = string.Format("SELECT [User Type] FROM [Users] where Name like " + UserNameList.Text);
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
if(sql== "Administrator"){
AdminCb.Checked=true;
}
if(sql== "User"){
UserCb.Checked=true;
}
Currently I am stuck with the error (Wong is the 2nd word of the user's name):
Questions:
1) How can change my Sql query so that it can take in more than 1word?
2) And will I be able to check boxes once I am able to run my sql query?
Thank You.
You must have to use Parameter and call the ExecuteScalar() method instead of ExecuteNonQuery().
string sql = "SELECT [User Type] FROM [Users] where [Name]=#Name";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#Name",SqlDbType.VarChar,50).Value=UserNameList.Text;
conn.Open();
Object result=cmd.ExecuteScalar();
conn.Close();
if(result!=null)
{
string usertype=result.ToString();
if(usertype=="Administrator")
{}
else
{}
}
In case, if result returned from the database contains more then one rows then use ExecuteReader() method.
string sql = "SELECT [User Type] FROM [Users] where [Name] like #Name";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#Name",SqlDbType.VarChar,50).Value="%" + UserNameList.Text + "%";
conn.Open();
SqlDataReader result=cmd.ExecuteReader();
while(result.Read())
{
///
}
result.Close();
conn.Close();
Since you are concatenating the SQL string, if the input itself has a single quote in it, it thinks this is the end of the input, and the continuing input is SQL statements, which is why you may be getting that error.
Switch to using a parameter, or make sure any single quotes are escaped as a pair of single quotes, like:
string sql = string.Format("SELECT [User Type] FROM [Users] where Name like " + UserNameList.Text.Replace("'", "''"));
Since the error is indicating there is something wrong with the Name, I would take a closer look at this line:
string sql = string.Format("SELECT [User Type] FROM [Users] where Name like " + UserNameList.Text);
If you are using string.Format, you might as well use it
string sql = string.Format("SELECT [User Type] FROM [USERS] where Name like {0}", UserNameList.Text);

Categories

Resources