Monday, August 24, 2009

SQL Injection Example

Design A Form of the Web Page
<table>
<tr>
<td>
UserName:
</td>
<td>
<asp:TextBox ID="tbxUserName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Password:
</td>
<td>
<asp:TextBox ID="tbxPassword" runat="server" TextMode="Password"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2" align="right">
<asp:Button ID="btnLogin" runat="server" Text="Login" Width="150px" OnClick="btnLogin_Click"/>
</td>
</tr>
<tr>
<td colspan="2" align="left">
<asp:Literal ID="Literal1" runat="server" Text=""></asp:Literal>
</td>
</tr>
</table>
//Now the Code Behind of the Button Login
string conn = ConfigurationManager.ConnectionStrings["FileDBConnectionString"].ConnectionString;
string query = "Select Count(*) From Users Where Username = '" + tbxUserName.Text + "' And Password = '" + tbxPassword.Text + "'";
int result = 0;
SqlConnection connection = new SqlConnection(conn);
connection.Open();
SqlCommand cmd = new SqlCommand(query, connection);
result = (int)cmd.ExecuteScalar();
if (result > 0)
{
connection.Close();
Response.Redirect("LoggedIn.aspx");
}
else
{
Literal1.Text = "Invalid credentials";
connection.Close();
}
If we copy the "'or'1'='1"(without quotation marks) both in the password textbox and username textbox it will redirect you on to the LoggedIn page this is what we called SQL Injection


In order to control the SQL Injection we have to add few code of line Just before the Query
string username = tbxUserName.Text.Replace("'", "''");
string password = tbxPassword.Text.Replace("'", "''");
And query would be change into
string query = "Select Count(*) From Users Where Username = '" + username + "' And Password = '" + password + "'";

No comments:

Post a Comment