+5 votes
63 views
I have to program an application management system for my OJT company. The front end will be done in C# and the back end in SQL.

Now I have never done a project of this scope before; in school we had only basic lessons about SQL. Somehow our teacher completely failed to discuss SQL injections, something which I have only now come in contact with by reading about it on the net.

So anyway my question is: how do you prevent SQL injections in C#? I vaguely think that it can be done by properly masking the text fields of the application so that it only accepts input in a specified format. For example: an e-mail textbox should be of the format "example@examplecompany.tld". Would this approach be sufficient? Or does .NET have pre-defined methods that handle stuff like this? Can I apply a filter to a textbox so it only accepts email-address format or a name textbox so it doesn't accept special chars?

ah ok. now i understand :) so basically i should interface with the database through a framework and not sql?

+1

What you're advocating here is an ORM - Like the entity framework. I use it myself and love it but it does have some drawbacks - like being really slow for bulk operations. The alternative is to use parameterised commands - you write the SQL with placeholders for your variables and then pass the variables in to a different method which takes care of merging them into the query for you (in fact, they're passed seperately to the Db server which handles the rest)

well as of now there are about 3000 records in the exisiting db, but this will be expanded dramatically during the course of this year. i will list the two choices (EF & parameterised commands) with advantages and disadvantages of each and let my project supervisor decide :

4 Answers

+3 votes

SQL injection can be a tricky problem but there are ways around it. Your risk is reduced your risk simply by using an ORM like Linq2Entities, Linq2SQL, NHibrenate. However you can have SQL injection problems even with them.

The main thing with SQL injection is user controlled input (as is with XSS). In the most simple example if you have a login form (I hope you never have one that just does this) that takes a username and password.

SELECT * FROM Users WHERE Username = '" + username + "' AND password = '" + password + "'"
+3

Im not aware of any SQL injection risks with EF/Similar ORMs as they use parameterised queries internally - can you provide a link? Thanks 

+1

The example I gave above with the stored proc would still be susceptible to a SQL injection attack even if you use an ORM like Entity Framework to call the procedure because the vulnerability is in the proc itself. Therefore what I was trying to convey is that you cannot simply use an ORM and think that you have covered 100% for SQL injection attack cases

+1 vote

By using the SqlCommand and its child collection of parameters all the pain of checking for sql injection is taken away from you and will be handled by these classes.

Here is an example, taken from one of the articles above:

private static void UpdateDemographics(Int32 customerID,
    string demoXml, string connectionString)
{
    // Update the demographics for a store, which is stored  
    // in an xml column.  
    string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
        + "WHERE CustomerID = @ID;";

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(commandText, connection);
        command.Parameters.Add("@ID", SqlDbType.Int);
        command.Parameters["@ID"].Value = customerID;

        // Use AddWithValue to assign Demographics. 
        // SQL Server will implicitly convert strings into XML.
        command.Parameters.AddWithValue("@demographics", demoXml);

        try
        {
            connection.Open();
            Int32 rowsAffected = command.ExecuteNonQuery();
            Console.WriteLine("RowsAffected: {0}", rowsAffected);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}
0 votes

My answer is quite easy:

Use Entity Framework for communication between C# and your SQL database. That will make parameterized SQL strings that isn't vulnerable to SQL injection.

As a bonus, it's very easy to work with as well.

+1 vote

SQL injection should not be prevented by trying to validate your input; instead, that input should be properly escaped before being passed to the database.

How to escape input totally depends on what technology you are using to interface with the database. In most cases and unless you are writing bare SQL (which you should avoid as hard as you can) it will be taken care of automatically by the framework so you get bulletproof protection for free.

You should explore this question further after you have decided exactly what your interfacing technology will be.

...