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
- Magento Hack Removal
- Magento Security Guide (For Rock Solid Security Against XSS, SQLi, Credit Card Hack, Admin Hack)
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.
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.
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?
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.
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);
$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.
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!
Hello Astra, so we have been using Magento 2 based website for a quite long time now. Recently we heard that Magento websites are getting hacked very easily. Can you tell us how we can prevent it from happening?
Thanks for responding to our article. Magento 2, one of the largest open-source e-commerce platforms in the world, has often been an eye candy for people with malicious intent. No matter the amount of work gone into securing this platform, hackers tend to come up with new ways to circumvent security measures. As its reputation grows, so does the notoriety surrounding the diverse forms of malpractices possible with it. For more information visit here: https://www.getastra.com/blog/cms/magento-security/how-to-prevent-your-magento-2-store-from-being-hacked/
Great article, I do also own a magento based website. Can you tell me how I can protect it against attacks and how I can remove malware?
Thanks for responding to the article. There are many telltale signs that convey that your Magento store might be hacked. Looking for these with an open eye can save your business from a debacle. For more information visit here: https://www.getastra.com/blog/911/magento-hacked/
So once the magento audit is completed on the website, Can I request a re-scan to check if the vulnerability is patched or not?
Thanks for responding to our article. Definitely, once you’ve fixed the vulnerabilities you can request a scan simply by clicking a button on your dashboard. Following which, our engineers are notified and they plan a re-scan. If you are a business plan customer, you get a rescan every month. If you’ve opted for a security audit separately then one re-scan is available to you. For more information visit here: https://www.getastra.com/magento-vapt
Hi, I would like to know more information on Magento security audits like price and things you perform in the audit.
Thanks for responding to the article. Astra’s Vulnerability Management Platform uncovers loopholes in your Magento with the right mix of automated & manual security testing. Each audit is tailored to the technology stack of the application. Manage bugs, collaborate with the security team, verify fixes at your own pace under one unified platform. For prices and more information visit: https://www.getastra.com/magento-vapt
Is there any way I can protect from getting credit card details hacked? I run a magento store. I see a lot of them are happening and I am scared.
Thanks for responding to the article. Online shopping has become the most natural phenomena around. And CMS (Content Management System) like Magento, is one thriving software in this niche. However, it has resulted in it becoming the unfortunate target of cyber attacks. Well, credit card hacks in Magento is not something unheard-of. Adding to its previous list of attacks, a new case of Credit Card Hack in Magento has come to light. For more information on how to protect against, visit here: https://www.getastra.com/blog/911/fake-payment-method-added-in-magento/
What does cryptojacking mean? Is there any way I can protect from them? I own a magento store.
Thanks for responding to the article. CoinHive is an online service which provides cryptocurrency miners (crypto mining malware) that can be installed on websites using JavaScript. The JavaScript miner runs in the browser of the website visitors and mines coins on the Monero blockchain. It is promoted as an alternative to placing advertising on the website. And turns out, it is being used by hackers as malware to hijack end customers of a website by infecting the website in the first place.
Recently I have heard about a Korean spam. What is it exactly and how can I defend against them?
Thanks for responding to the article. Spam is a blanket term used for unsolicited emails, adverts, etc which have no relevance to the end user. Spam is used for a wide variety of internet crimes. Sometimes, it is deployed by hackers to trick innocent users into buying fake products or to click farming. Sometimes, spam is used to pollute the search results of competing sites. Spam usually targets users via lucrative offers like pyramid schemes, multi level marketing, cheap pharma products, etc. Recently, a large scale Korean SEO scam was uncovered. For more info, visit here: https://www.getastra.com/blog/911/korean-seo-spam-removal/
Hi, I have a magento store? What are the prices and plans that you offer? So, I can review them and purchase a plan that suits me the best.
Thanks for responding to our article and showing interest in Astra. You don’t have to worry about any malware, credit card hack, SQLi, XSS, SEO Spam, comments spam, brute force & 100+ types of threats. This means you can get rid of other security plugins & let Astra take care of it all.You can visit here for pricing info and details: https://www.getastra.com/magento-firewall
Hey, what do business logic errors mean? How can they affect a website? Can you tell me some info on this?
Thanks for responding to the article. Business logic or application login is the core logic of your website. Business logic defines how data can be created, stored and modified. It is the features that are specific to your business and usually developed for you. For example, e-commerce websites allow visitors to add products to a shopping cart, specify the quantity, delivery address, and payment information. For more information visit: https://www.getastra.com/blog/knowledge-base/business-logic-errors-need-know/
Hello I am developing a website based on magento. Can you share with me some important things that I have to keep in mind while developing?
Thanks for responding to the article. Sure, you can check our checklist for Magento here: https://webpro.getastra.com/checklist/magento