Magento Tutorials

How to Prevent SQL Injection in Magento

SQL Injection Attack

Direct SQL Command Injection is a technique where an attacker creates or alters existing SQL commands to expose hidden data, or to override valuable ones, or even to execute dangerous system level commands on the database host. It will cause many harmful things to your Magento Store, and your database.
The attacker could create a new admin account in your existing one, steal critical information, insert data, delete data,…

Here is an example of SQL Injection attack

<?php
// We didn't check $_POST['password'], it could be anything the user wanted!
// For example:
$_POST['username'] = 'david';
$_POST['password'] = '' or "='";
// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND
password='{$_POST['password']}'";
mysql_query($query);
// This means the query sent to MySQL would be:
echo $query;
?>

The query sent to MySQL: SELECT * FROM users WHERE user=’david’ AND password=” OR ”=”. It allows anyone to login without a valid password.

SQL Injection protection

The best advice to avoid SQL injection vulnerability is “do not directly query the database”. You should be using the ORM which would protect you in these situations. Especially when grabbing data out of the EAV tables.

Besides, if you are running a native sql query with parameter input, you should bind the query parameters to the query with Zend_Db_Select’s bind rather than using a full SQL statement:

$query = $this->_connection->select()->from('eav_attribute')->where('attribute_id=?', $attributeId); $result = $this->_connection->fetchAll($query);

See also: How to Stop Brute Force Attack on Magento 2

Dom

A knowledge craver who always strive to be wiser everyday.