Galin Iliev's blog

Software Architecture & Development

How bad is SQL Injection

I have been presenting IIS (Internet Information Services) for a while and there is one slide in my deck which says that there is No critical security patch since RTM for IIS6.

Recently there was some news about 500k web pages was exploited with SQL Injection hack(more info here and here).

Although this could put some shadow on IIS security it has to be clear that this is not an IIS exploit. This is application exploit. Any application could suffer SQL Injection (video: Length: 6:01 - Size: 6.37 MB ).

It is not like uploading harmful file on the server and execute it, isn't it?

So it has to be clear: Do not use such code:

public bool Login(string userName, string password)
{
    string command = string.Format("SELECT COUNT(*) FROM User WHERE UserName='{0}' AND Password='{1}'",
        userName, password);

    using (conn)
    {
        SqlCommand cmdLogin = new SqlCommand(command, conn);
        conn.Open();
        int res = cmdLogin.ExecuteScalar();
        return res == 1;
    }
}

Do you know why?!

Because if you get as password the following string ' OR 1=1 '; drop table Users; you will drop the table from DB and apparently the application will stop working.

Do it this way:

public bool Login(string userName, string password)
{
    string command = string.Format("SELECT COUNT(*) FROM User WHERE UserName=@UserName AND Password=@Password",
        userName, password);

    using (conn)
    {
        SqlCommand cmdLogin = new SqlCommand(command, conn);
        cmdLogin.Parameters.AddWithValue("@UserName", userName);
        cmdLogin.Parameters.AddWithValue("@Password", password);

        conn.Open();
        int res = cmdLogin.ExecuteScalar();
        return res == 1;
    }
}

It is much safer...

Hope this helps!

Comments (1) -

  • Hank

    7/16/2011 10:03:03 AM | Reply

    At last, soeomne comes up with the "right" answer!

Loading