SQL injection is a technique that exploits a security vulnerability within the database layer of an application.Using this technique the attacker tries to run his own malicious query against the database.The key component of these malicious queries is that they try to exploit websites that rely on scripts to dynamically generate content from the database.
Let us try to understand in steps how an attacker attempts to do SQL injection
Step 1: Find a vulnerable website
Typically the attacker will scan the urls' of website to see if the url contains any part that may be passed to database as parameter eg : query strings . Once the attacker has identified the url's , he will pass harmful/malicious code in parameter to get additional information like database layout ,table details etc. Typically the success of the attacker will depend on how strongly security implementations have been implemented in the application.
Step 2: Try to exploit the vulnerability
In case the application is not guarded against sql injection the attacker will utilize this vulnerability by providing specially modified sql scripts which the database will run as if they are safe application scripts.Since the scripts being run belong to the attacker he can get sufficient information to ruin the database or even extract customer's private information from database.
How to prevent SQL injection ?
The key to preventing SQL injection focuses on database management techniques to best practices for handling bad inputs.Following are some of major best practices to avoid SQL injection:
a) Ensure user input is validated against a set of defined rules for length, type and pre-defined business rules.
b) Avoid use of over-privileged database logins. You should ensure that users with the permission to access the database have the least privileges.
c) Use strongly typed parameterized query , stored procedures or ORM.
d) Avoid dynamic sql construction, in case it is being used ensure type-safe parameters are being used.
e) Avoid disclosing database error information in case of an error. Only custom error should be shown to the client.
f) Never store sensitive data in clear-text within a database.This will ensure that even if attacker is able to access data he cannot misuse it.