Monday, April 5, 2010

How to avoid SQL Injection


What Is SQL Injection?

SQL injection is security vulnerability, a serious security threat that enables an attacker to execute unauthorized SQL commands by embedding them in the SQL statements by taking advantage of non-validated input in Web applications that attempt to build SQL queries dynamically.


When Does It Occur?

This typically happens in situations where your application accepts user input and builds SQL statements dynamically without a proper input validation mechanism. How? Let s assume there is a login form where the user needs to fill in the user name and the password and then click the Submit button to log in to an application. Suppose the user fills out the form as shown below:

Login: OR =

Password: OR =

The resultant query is:

SELECT userName FROM Users WHERE userName = '' OR ''='' AND Password = '' OR ''=''

This, of course, will always return true.

A smart intruder can inject SQL statements into a SQL query that is built dynamically in your application and can turn the query into the form, as shown below:

SELECT * FROM products WHERE productID = 1 or 1=1

This would always return true, irrespective of the value of the product id. Hence, your data is under threat!


How Do I Prevent It?

The following points highlight the effective measures that can be adopted to prevent SQL injection attacks:

  • Prevent unauthorized access to the database and limit the permissions that are granted to the database user account that the application uses.
  • Validate user input properly before using it, stripping off the potentially malicious characters.
  • Always use parameterized SQL queries and stored procedures rather than building the SQL statements dynamically.
  • Avoid displaying the actual database errors or messages to the end users.

No comments:

Post a Comment