Friday 16 March 2012

Preventing SQL injection attacks using C#.NET


What is a SQL Injection Attack?
A SQL Injection attack is a form of attack that comes from user input that has not been checked to see that it is valid. The objective is to fool the database system into running malicious code that will reveal sensitive information or otherwise compromise the server.
There are two main types of attacks. First-order attacks are when the attacker receives the desired result immediately, either by direct response from the application they are interacting with or some other response mechanism, such as email. Second-order attacks are when the attacker injects some data that will reside in the database, but the payload will not be immediately activated.

Avoiding SQL Injection



protected void Button1_Click(object sender, EventArgs e)
{
  string connect = "MyConnString";
 
string username= Regex.Replace(txtuname.Text.ToString(), "[^-a-zA-Z0-9_./:&()#!@$%^&*?]+", "", RegexOptions.Compiled);

string Pwd = Regex.Replace(txtpwd.Text.ToString(), "[^-a-zA-Z0-9_./:&()#!@$%^&*?]+", "", RegexOptions.Compiled);
 
  string query = "Select Count(*) From Users Where Username = 
  '" +       username + "' And Password = '" + Pwd + "'";
  int result = 0;
  using (var conn = new SqlConnection(connect))
  {
    using (var cmd = new SqlCommand(query, conn))
    {
      conn.Open();
      result = (int)cmd.ExecuteScalar();
    }
  }
  if (result > 0)
  {
    Response.Redirect("home.aspx");
  }
  else
  {
    Literal1.Text = "Invalid credentials";
}

Using this
string username= Regex.Replace(txtuname.Text.ToString(), "[^-a-zA-Z0-9_./:&()#!@$%^&*?]+", "", RegexOptions.Compiled);

string Pwd = Regex.Replace(txtpwd.Text.ToString(), "[^-a-zA-Z0-9_./:&()#!@$%^&*?]+", "", RegexOptions.Compiled);


you will avoid all type of sql injection

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Powered by Blogger