Question - What is SQL injection and how do I protect my application from SQL injection attacks

J.D. Meier, Alex Mackman, Blaine Wastell, Prashant Bansode, Andy Wigley, Kishore Gopalan

Applies to

Answer:

If you are generating dynamic SQL queries based on user input, a SQL injection attack can inject malicious SQL commands that can be executed by the database. The injection attack can occur when your application uses user input to construct dynamic SQL statements to access the database or if your code passes string containing unfiltered user input to stored procedures. To prevent SQL injection attacks you need to:

Here is a sample of a RegularExpressionValidator control to validate a email address

<form id="WebForm" method="post" runat="server">
  <asp:TextBox id="txtName" runat="server"></asp:TextBox>
  <asp:RegularExpressionValidator id="nameRegex"runat="server" ControlToValidate="emailAddress" ValidationExpression"],@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ErrorMessage="Invalid email address">
  </asp:regularexpressionvalidator>
</form>
SqlDataAdapter myCommand = new SqlDataAdapter("SELECT au_lname, au_fname FROM Authors WHERE au_id = @au_id", conn);
SqlParameter parm = myCommand.SelectCommand.Parameters.Add("@au_id",SqlDbType.VarChar, 11);
parm.Value = Login.Text;

Additional Resources

Attributes

  • Author: J.D. Meier, Alex Mackman, Blaine Wastell, Prashant Bansode, Andy Wigley, Kishore Gopalan

  • Category: Data Access

  • filePath: ..\Libraries\patterns & practices Library\faq\61baa667-796c-4477-b9db-009575948157.xml

  • Pri: 2

  • Rule Type: Implementation

  • Source: patterns & practices Library

  • Status: Release

  • Technology: ASP.NET 2.0

  • Title: Question - What is SQL injection and how do I protect my application from SQL injection attacks

  • Topic: Security

  • Type: Question and Answer

  • ID: 61baa667-796c-4477-b9db-009575948157