Tuesday 10 July 2012

SQL Injection Attack - PHP & MySQL

In this attack, a  hacker is able to execute SQL queries in your website's database. This attack is usually performed by entering text into a form field which causes a subsequent SQL query, generated from the PHP form processing code, to execute part of the content of the form field as though it were SQL. The effects of this attack range from the harmless (simply using SELECT to pull another data set) to the devastating (DELETE, for instance).

It is a basically a trick to inject SQL command or query as a input mainly in the form of the POST or GET method in the web pages. Most of the websites takes parameter from the form and make SQL query to the database.
For a example, in a product detail page of php, it basically takes a parameter product_id from a GET method and get the product detail from database using SQL query. With SQL injection attack, a intruder can send a crafted SQL query from the URL of the product detail page and that could possibly do lots of damage to the database. And even in worse scenario, it could even drop the database table as well.

For Example
you have login page and ask user to login via putting username & password into form.
suppose that a intruder called user injected x’ OR ‘x’='x in the username field and x’ OR ‘x’='x in the password field. Then the final query will become like this.

SELECT * FROM users WHERE username=’x’ OR ‘x’='x’ AND password=’x’ OR ‘x’='x’;

Now what happen, it will return the first record of table users 
user who is not authorize, will be able to login in website.

use mysql_real_escape_string function to avoid the problem.


How can I prevent SQL-injection in PHP?
1. USe PDO
$stmt = $pdo->prepare('SELECT * FROM users WHERE name = :name');
$stmt->execute(array('name' => $name));
foreach ($stmt as $row) {
    /* Do your Action **/

    /* Do your Action **/

2. USe MySqlI instead of MySQL. MySQLI is far better than MySql
$stmt = $dbConnection->prepare('SELECT * FROM users WHERE name = ?');
$stmt->bind_param('s', $name);
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    /* Do your Action **/

    /* Do your Action **/

3. Use framework and execute the query with framework like zend, cakephp and magento etc. But for this you must install the framework.