Code example of a bad example: SQL Injection using C#

Code Snippet
  1. string userName = connection.getAuthenticatedUserName();
  2. string query = "SELECT * FROM items WHERE owner = '" + userName + "' AND item = '" + ItemName.Text + "'";
  3. sda = new SqlDataAdapter(query, conn);
  4. DataTable datatable = new DataTable();
  5. sda.Fill(datatable);

SELECT * FROM items WHERE owner = 'wiley' AND itemname = 'name' OR 'a'='a';

The query executes as:

SELECT * FROM items WHERE owner = <userName> AND item = <item>;

Oops, if an attacker then enters: BadPerson’ OR ‘b’=’b

Into the ItemName textbox, the query then becomes:

SELECT * FROM items WHERE owner = ‘BadPerson’ AND item = 'name' OR 'b'='b';

The pesky OR statement now turns the SQL statement into:

SELECT * FROM items;

Which is a bad thing to happen, you have lost control of your database

image

So what do you do?

  • Assume all input is malicious
  • Manage your error statements, not too cryptic but not too informative, definitely should not reveal too much to that badperson
  • Run code with the lowest privileges required to accomplish tasks
  • Read about securing your code at sites like:

And finally:

  • Blame a large corporation when the SQL Injection occurs

 

imageimageimageimage

When you get a few minutes check out the following blogs!

 

Hey now that you read this blog, check out my other blogs:

Take a look at my colleagues blogs!