Magento SQL Injection: How to Secure your Magento Store Against SQL Injection Attack

Avatar photo
Author
Updated: July 16th, 2024
12 mins read

Magento is quite popular among the business community. This can be traced back to its open-source origins. Magento was aimed towards easing the process of managing and creating a store. Being open-source, it uses MySql or MariaDB for data storage and management. Database plays a vital role in managing the Magento store. This also means targeting the Magento database with Magento SQL injection attacks is quite common. A Magento SQL injection is the result of unsanitized user input. It is a significant threat looming over the stores. One sloppy coding can expose the entire database.

Besides SQL injection attacks, Magento is also plaguing with Credit card theft scam, Cryptojacking, SEO spam, and other cyber threats. However, in this article, we will keep our focus on Magento SQL injection attacks and how you can prevent them from happening on your store.

Follow the below links if you are looking for

What can a Magento SQL Injection do?

The database is one of the most sensitive components of your store. First SQLi was reported way back in 1998. Yet, SQLi still makes it to the list of OWASP Top 10 vulnerabilities. So there is a good reason to beware of it. A Magento SQL injection can:

  • Read the contents of a database.
  • Manipulate the database. This can modify the contents of the store.
  • Delete the entire database.
  • Steal credit card details.
  • Expose admin credentials. This could lead way for further attacks.
  • Obtain a reverse shell in some cases. Also, it can then escalate the privileges

Advanced methods to exploit a Magento SQL injection are found every year. New tricks to bypass filters and Magento security audits are developed every month. So, the threat of Magento SQL injection attack is increasing day by day. A lot can still be done to prevent Magento SQL injection.

Magento hack removal

Your store shows signs of a Magento SQL injection attack? Drop us a message on the chat widget and we’d be happy to help you. Secure my Magento website now.

Causes of Magento SQL Injection

1) Client Side Implementation of Code

Often the developers pay no heed to secure coding practices. As a result, some code is run of the client-side. As it is run on the client’s machine, it can be altered by the client. This can result in bypassing input validation. In layman’s terms, the attacker can pass your security check just because you made him the in-charge. Ask your developer to run the sensitive functions on the server-side to prevent Magento SQL injection.

2) Unsanitized Input

Often the input received from the user is not sanitized properly. Every time a request is made to the server, a fresh query is generated using the given input. These are known as dynamic queries. Let’s see why these are dangerous. For instance look at the following query:

txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " ' + txtUserId ' ";

This piece of code requests for UserId and then submits it to the SQL query. Everything seems fine what can go wrong ?. Let’s see. An attacker can provide an input such as 105'; DROP TABLE Users. So now the attacker has very clearly stacked one statement over the other. Thus the second query will be executed after first. So the final query  that will be executed will be

SELECT * FROM Users WHERE UserId = 105; DROP TABLE Users;

This way the attacker can modify the contents of the database. Therefore it is best to avoid dynamic queries. Also, not to worry. There is an alternative to dynamic queries. Those are called prepared statements which help to prevent Magento SQL injection.

3) Tautologies

Firstly, this kind of attack uses statements that evaluate to true. Thus it then helps to bypass login restrictions. Poor coding practices can result in bypassing the restrictions. For example, look at the source code of a login page given below:

<?php

$_POST['username'] = '';

$_POST['password'] = '';

$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND
password='{$_POST['password']}'";

mysql_query($query);

echo$query;

?>

It merely takes inputs from user and password fields. Then evaluates them against SQL query. Now if the attacker was to provide an input as admin' or 1=1--. So the SQL statement executed will be

SELECT * FROM users WHERE user= 'admin' AND password='' OR 1=1--

Note the symbols -- ensure that all other statements after it are treated as comments. Therefore the attacker has bypassed the login page and is now the admin. Also, there are multiple variants of ' or 1=1-- . There is a comprehensive list of such parameters. Poor coding can make your login pages vulnerable to Magento SQL injection attack.

4) Error Messages

Error Messages can give away a lot about your system. Some of them can reveal the columns and the database version. For example look at this image given below.

Magento SQL injection error page

This message here reveals the database and columns. Thus, there are different messages for different databases. Magento runs on My SQL so it would look something like this. These messages can assist attackers to conduct a Magento SQL injection attack. Disabling errors can aid to prevent Magento SQL injection. Though if error messages are disabled, the possibility of blind SQLi still looms. However, it is best to switch off error messages for the users.

5) Database Privileges

Improper permissions can further fuel the Magento SQL injection attack. After the database is compromised, the attacker gains admin privileges. This happens because the instance of the database was running as admin. Therefore the attacker can manipulate the contents as per wish. Had there been lack of admin privileges the attacker could only read contents. Thus database privileges can stop SQL commands like Update, Insert etc. So, it is safe to set DBA to False.

6) Encryption

If the sensitive table values are not encrypted it adds fuel to the fire. Thus, storing passwords in plaintext is a big mistake!. Ensure that encryption is set to True for your database. So it can act as damage control in case of Magento SQL injection attack.

7) Variable Size Filtering

If there is no limit on the size of variables, the user can provide a long input. This is usually malicious input containing SQL statements. So, if there is a limit on variable size it can prevent a Magento SQL injection. Thus preventing Magento SQL injection attacks.

Need professional help in securing Magento Store? Drop us a message on the chat widget and we’d be happy to help you. Protect my Magento website now.

Magento Security Audit Post SQL Injection

1)  Detection of SQL Injection Vulnerability

The best way to start looking for a Magento SQL injection is to dig logs. Look at the image given below and does your log show something like this?

Magento sql injection log

If yes that means an automated SQLi tool has been used. The server logs display the various SQL statements used. Check database logs immediately to determine the changes that have taken place. Also look if any new users have popped up.

Temporarily disable the affected pages till the code is sorted out. Also, make sure the instance of the database is not running as Admin on the server. This would limit the ability of an attacker to read-only. From here on proceed for Magento security audit.

Magento Security Audit & Pentesting

2) Checking Users

A heuristic idea can be taken using the command show tables ;. If there exist tables like Sqlmap then most likely an automated tool has been run against the website. The next step shall be to look for new users. Use the following command:

Select * from users  as u
AND u.created > UNIX_TIMESTAMP(STR_TO_DATE('Oct 15 2018', '%M %d %Y '));

This SQL statement displays users created after 15 October. The date string can be manipulated to check back in time. Rogue databases can be dropped using the following SQL statement:

drop database database-name.dbo;

3) Blocking Users

Post detection of rogue users its time to block them out. So the following SQL statement does the trick:

update users set pass = concat('ZZZ', sha(concat(pass, md5(rand()))));

The following statement updates the table users and sets a new password. Moreover, the password is set in an encrypted format. Thus the attacker would have to brute force and use other known techniques to get plain text.

4) Restoring Database

At times the attacker may have deleted the database. In that scenario, it can be restored from the backup. Just run the My SQL command-line client. Log in using the following command.mysql -u root -p 'your password' After that run the following SQL statements:

create database new_db;
use new_db;
\. backupfile.sql

This shall restore the database. Thus controlling the damage caused by Magento SQL injection hack. However, the store still needs a comprehensive Magento security audit. For extra protection, you can use air gap backup solutions. These solutions keep your backups offline and safe from attacks. Adding this layer of security helps protect your Magento store from SQL injection and other threats.

Example of SQL Injection Attack in Magento 

example.com/?___from_store=en' union select 0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526,0x5e2526 -```

The _ _store and _ _from_store URL parameters are used in Magento Multistore installations to switch between versions of the store and languages. Hackers commonly attack this parameter with SQL Injection queries.

This is typical behavior from automated security tools such as Sqlmap and Acunetix. If the tool suspects that “union injection” is possible, it will first try to determine the number of fields it needs in the union query, and also see which fields end up reflected in the output. Having a unique query like this helps to test both, and also bypasses some security systems where you can’t refer to field indexes in the query.

How to Prevent Magento SQL Injection Attack

1) Protection Parameters

Each database comes with specific protection parameters. These help in avoiding Magento SQL injection attacks. For example look at this code:

txtUser = getRequestString("User"); txtPass = getRequestString("Password"); txtOTP = getRequestString("OTP"); txtSQL = "INSERT INTO Login (User,Password,OTP Values(@0,@1,@2)"; db.Execute(txtSQL,txtUser,txtPass,txtOTP);
The input parameters are represented by thus @ marker. Therefore, the SQL engine checks each parameter. Moreover, it makes sure that they are treated literally. This avoids them being a part of the SQL statement. Therefore whatever input the user gives will not be a part of the SQL statement. So you have successfully prevented a Magento SQL injection. However, if you wish to execute is PHP, here is the code:
$stmt = $dbh->prepare("INSERT INTO Login (User,Password,OTP)  VALUES (:usr, :pass, :otp)"); $stmt->bindParam(':usr', $txtUser); $stmt->bindParam(':pass', $txtPass); $stmt->bindParam(':otp', $txtOtp); $stmt->execute();

Consult Astra security experts now to find and fix a Magento SQL injection. Our powerful Firewall safeguards your website from SQL Injection, XSS, LFI, RFI, Bad bots, Automated Vulnerability Scanners, and 80+ security threats. Secure my website now.

2) Use Prepared Statements

The alternate option to dynamic queries is the prepared statements. These are the statements which are prepared and parsed later on. So, the database stores the statement without executing it. It first checks the parameters. Later it ensures that a string input is a string only and so on. This ensures that the input is not mischievous. Once all the parameters are checked, it executes the statements. Thus ensuring that no Magento SQL injection attack occurs. Given below is a prepared statement implementation in My SQL and PHP.

Magento SQL INJECTION prepared statement

As we can see here there are ‘?‘ in place of some values. So, it says that the specific data type will substitute the value here. It can be an integer, string, blob etc. Magento uses the Zend framework. So, in that case, the components of the Zend framework can be used. Bind the query parameters to the query with Zend_Db_Select’s bind rather than using a full SQL statement. Like this:

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

3) Limit Privileges

Ensure that the sensitive columns are encrypted. Thus even if the database is compromised the attacker needs to brute force the password. Also, ensure the passwords used are strong. Moreover, limit the role of the database. Disallow statements like Update, Drop etc.

4) Use A Web Application Firewall

Manual inspection of code to determine a Magento SQL injection attack is tedious. So hire the experts for it. Also, use a firewall so that no such commands can pass by its filters. Astra has a great firewall and security solution designed to keep out Magento SQL injection attack. Magento security audit can save precious resources and time in the future!