Magento Hacked: Complete Guide to Magento Malware Removal

Avatar photo
Author
Updated: May 2nd, 2022
15 mins read

Magento powers 1.2% of the internet and, 12% of all eCommerce sites. In pure numbers, 250,00 active sites use Magento.

Since the eCommerce site processes a huge amount of customer data that makes them the primary target of hackers.  So, we have put together stepwise Magento hack removal techniques to pull you out of this crisis. This guide further covers the symptoms, examples, possible causes and prevention tips for your Magento website.

Although there is no dearth of Magento hacking types, credit card skimming & identity theft make for the most common ones on Magento. Moreover, the CVE details of Magento reveal the attack vectors that threatens Magento the most –

Other than this, some severe vulnerabilities were reported in the software for which the company had to roll out a bundle of new updates titled SUPEE-10266. An attack by the name of ‘Magento Killer‘ targeted Magento wildly only a few months back. The official support for Magento 1 would end soon and therefore stores that didn’t mitigate would be inviting hackers. 

Magento Hacked: Possible Consequences or Symptoms

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. I have listed some of these symptoms here:

Symptoms

  • Customer complains about stolen credit card details
  • The checkout page has additional fake forms and you are losing money on sales
  • Search engines blacklist your Magento store
  • Host suspends your website
  • Malicious redirects appear on your website
  • Admin panel defaced or a blank screen after login
  • The Magento store gets slow & shows error messages
  • New, rogue admins appear in the login database
  • Google showing spam keywords (Japanese or Pharma) search results for your website
Magento hack removal

Consequences

  • A decline in user traffic and revenue from the Magento store.
  • Negative effect on the website’s SEO.
  • Users refrain from visiting your Magento store due to a lack of trust.
  • Site data may be sold on the onion sites to competitors.
  • Sensitive data theft from the store via phishing pages or javascript.

Magento Hacked: Examples

Often, multiple Magento users are targeted by attackers in one go. Not every site admin may be an expert at security. Therefore, the troubled user can be found resorting to community forums for help, and to fix the Magento hacked stores.

Magento hacked example (Source: Forum)

Cleaning A Magento (1x & 2x) Hacked Store

Control the damage

Begin with damage control. Take note that this won’t fix the hack. But, it sure will stop the rage. Here is what you must consider as damage control:

  1. Change the default & obvious credentials to something difficult, random and unique.
  2. Update the user passwords with a single SQL statement to lock out all the attackers. This can be done via the following SQL statement:

    update users set pass = concat(‘ZZZ’, sha(concat(pass, md5(rand()))));
  3. Deny access to sensitive folders. You can do this by creating a .htaccess file inside them. Within that file add the following code:
    Order Deny,AllowDeny from allAllow from xx.xx.xx.xx

Edit the xx.xx.xx.xx with your IP address. To add more IP addresses, repeat the line “Allow from…” with different IPs.These lines of code block unwanted access to those particular folders. 

Take a backup of your site

Before you start cleaning your Magento store, take a backup first. This backup should include both the core files and the database. If there are additional files that define the working and look of your store, include them in the backup as well. To clarify, take a backup of core, extensions & database.

Confirm the hack

By using a tool

After you have taken the backup, start with scanning your store. Now, there are scores of free tools available that check if your website has been infected or not. Virustotal is the most popular tool of all.

By checking Google search console

Other than a tool, security reports by search engines can help you too. Check the security report by logging into your webmaster’s too (Google search console, in case of Google). Follow these simple steps and know if your website is infected or not:

  1. Log into your Google search console (webmasters tool)
  2. Go to ‘Security tab’
  3. Check if there are any flaggings. Generally, a hacked website is flagged almost immediately by search engines. You will see a report detailing the type of infection and the exact files that have them.

Now that you know there is indeed an infection. It is time to search for the exact place it is. Remember in a Magento hack removal process, the bigger part goes into scanning. So, we will now hunt for the infection in the core files, extension files, module files, the database, etc.

Scan core files

Hackers can compromise your Magento website by injecting code into your database & core files. Thus, you need to check for the recent unfamiliar changes in these files. To do this, you can either run a command or use a difference checker tool. I, however, will list both these methods here for your convenience:

By running an SSH command line:

For the command lines to work, you would first need to download the clean and authentic version of your Magento store. You can easily download it from Magento’s official site or Github. The following commands will check these two copies for any anomalies.

$ mkdir magento-2.2.5

$ cd magento-2.2.5

$ wget https://github.com/magento/magento2/archive/2.2.5.tar.gz

$ tar -zxvf 2.2.5.tar.gz

$ diff -r 2.2.5 ./public_html

Note: Here the Magento 2.2.5. is being used as the clean file and your current installation is indicated with the public_html folder.

By running a diff command line:

Recently modified files should be suspected always in case of a hack. The diff command reveals all these changes in a file for a set time period. For instance, in this case, we have set the time period to 10 days (see mtime -15).
Here is how you can run the command:

  1. Log into your Magento web server.
  2. When accessing with SSH, run the following command. This will list all the changes in the last 10 days.
    $ find ./ -type f -mtime -10
  3. When accessing with SFTP, review the last modified date column of all files on the server.

With this, you will get the list of all the modifications done in the past 10 days. Hereafter, you can manually go through the changes.

Review user logs

Next up is checking the users on your website. Sometimes, hackers get unauthorized access to your website. And, they add themselves as a user. This is why it is necessary to audit your user accounts. Find and remove rogue users in the admin table. Removing these accounts will help to check the damage on your website.

To audit the user logs, follow these steps:

  1. Log into your admin panel
  2. Navigate to System>Permissions>All users
  3. Review this list attentively

Hunt for Malware

In the case of SQL injections, attackers often obfuscate the code to a format unreadable to humans. And, Base64 format comes in handy for the attackers. To search for any base64 code within your files, execute the command:

find . -name "*.php" -exec grep "base64"'{}'; -print &> hiddencode.txt

This command would scan for base64 eth encoded lines of code. And store it inside hiddencode.txt. You can decode this using online tools for further analysis.

However, in the case of spam attacks, tools like phpMyAdmin can come handy. Magento spam attacks include gibberish injected to every Magento hacked page. Not to say, this is pretty difficult to search for and get rid of. Hence, we recommend using phpMyAdmin to search for malicious code within multiple pages in one go.

Search for malicious code using phpMyAdmin within pages.

Magento Security: Restoring Files

After, the malicious code is revealed, remove it from the Magento hacked pages. If you are unsure about any code, comment it out and contact the experts. Restore the pages from a backup. If the backup is unavailable then use a fresh copy.

Possible Causes of Magento Hack

Magento Hacked: Magento SQL Injection

An SQL injection is fairly common on web apps. It targets the database of a Magento store. The database is often called the brain of a website. It holds all the sensitive data like order history, transactions, etc. in a Magento store. This makes it a charming target.

Effects

No doubt an SQLi can do severe damage to your website. I have listed what all could go wrong here.

  • The attacker could read the contents of a database.
  • He can change the contents of the database. This, in turn, modifies the contents of the store.
  • Obviously, he can delete the entire database.
  • He can steal credit card details.
  • An attacker can also steal & expose admin credentials. This could lead the way for further attacks.
  • They can obtain a reverse shell in some cases. It could help in privilege escalation.

Examples

I have cited one example to clarify how a SQL injection attack takes place. This is an actual case that happened on Magento shoplift attack in 2015.

In this attack, the target URL to which malicious requests were made was something like this:

http://www.example.com/index.php/admin/Cms_Wysiwyg/directive/index/

This happened because of a parsing error. All values entered in the filter key i.e. (“filter”:malicious_value) were wrongly parsed. Further, the attackers used base64 encoding to evade detection. Attackers, basically, inserted SQL statements as a value to the filter key and it was parsed.

Final encoded payload in Magento SQLi attack

On decoding the above request, the outcome looked something like this:

popularity[from]=0&popularity[to]=3&popularity[field_expr]=0);

SET @SALT = 'rp';

SET @PASS = CONCAT(MD5(CONCAT( @SALT , 'asdf') ), CONCAT(':', @SALT ));

SELECT @EXTRA := MAX(extra) FROM admin_user WHERE extra IS NOT NULL;

INSERT INTO `admin_user` (`firstname`,`lastname`,`email`,`username`,`password`,`created`,`lognum`,`reload_acl_flag`,`is_active`,`extra`,`rp_token`,`rp_token_created_at`) VALUES ('Firstname','Lastname','[email protected]','sadmin',@PASS,NOW(),0,0,1,@EXTRA,NULL, NOW());

INSERT INTO `admin_role` (parent_id,tree_level,sort_order,role_type,user_id,role_name) VALUES (1,2,0,'U',(SELECT user_id FROM admin_user WHERE username = 'sadmin'),'Firstname');

Here, the first few SQL statements are basically setting a new password using an attacker chosen salt. Thereafter, the next group of SQL statements is inserting a new admin_user to the database. And the final few SQL statements are leveraging the role to admin. Therefore, the attackers have created a new user admin with username=”ypwq“, password=”123“. The full exploit is publicly available on GitHub.

Prevention

Protect your website from SQL injections as follows:

  1. Limit Privileges to client-side
  2. Use Prepared statements
  3. Protection Parameters
  4. A firewall

For more detailed prevention tips, refer to this article.

Via XSS Attack

In a Magento XSS attack, attackers inject malicious JavaScript codes into various web pages for the Magento store. It arises from weak or non-existent Sanitization & Validation rules. This attack mainly targets the stored cookies and session details of users. Usually, the motive behind this attack is to steal session details of either users or admin. As the session details also contain login credentials for that user, it can be used to log into your store unauthentically.

Effects

  • Theft of Cookie/session details
  • Unauthenticated access to the hacker
  • Hackers can read important data like CSRF tokens
  • Make requests as an imposter of the user

Example

An XSS vulnerability was discovered in Magento version 1.9.0.1. The files containing the vulnerable element were:

http://[magento_url]/skin/adminhtml/default/default/media/editor.swf
http://[magento_url]/skin/adminhtml/default/default/media/uploader.swf
http://[magento_url]/skin/adminhtml/default/default/media/uploaderSingle.swf

The cause for XSS was that the FlashVar parameter “bridgeName” was being passed to the ExternalInterface.call method without proper sanitation. As a result, it was possible to pass a malicious JavaScript code through the bridgeName parameter. Therefore, this malicious JS code runs whenever the page loads. The complete payload looked like:

http://example.com/skin/adminhtml/default/default/media/editor.swf?bridgeName=1%22]%29%29;alert%281%29}catch%28e%29{alert%281%29}//

Prevention

You can keep your website XSS free by following these measures:

  1. Set proper sanitization & validation rules
  2. Limit Privilege

Magento Hacked: Magento Cross-Site Request Forgery

A Magento CSRF attack is basically executing forged requests on behalf of an end-user, without the knowledge of the user. Generally, a CSRF attack is accompanied by social engineering. So, a hacker might send malicious links to the targeted user (usually admin) via mail. The motive behind these links is to execute functions on behalf of the user.

Effects

  • The attacker may delete your account.
  • He may use your credit card
  • Making use of the bank account details, an attacker may transfer funds from the victim’s bank account to his own
  • He may order illegally from your Magento store without paying or by manipulating prices

Examples

  1. A severe CSRF bug was found in Magento 1 which allowed remote attackers to inject script code to the application-side of the affected service module for execution. The component vulnerable to this was the ‘filename‘ parameter of the image upload module. The attackers used POST requests from the application-side to successfully conduct this attack. However, in order to exploit its, the attacker needed a low privileged web-application user account and low or medium user interaction. The code snippet of the vulnerable script is given below.

Vulnerable Script

Here, attackers manipulated the ‘to‘ and parent_message_id parameters due to lack of proper checks and balances. Using these the attacker could send a message to any other user without his/her consent. Moreover, it also gave an attacker other abilities to manipulate content on a Magento hacked store.

  • Magento Community and Enterprise editions before 2.0.10/2.1.2 also suffered from two CSRF bugs.
    APPSEC-1212: Magento failed to validate the anti-CSRF token while deleting items from the mini cart through a GET request. Therefore, the attacker could use this vulnerability to remove items from the cart through phishing and other tricks.
    APPSEC-1433: This was a more severe CSRF vulnerability. Exploiting this, the attacker could delete any address on the store because due to the lack of anti-CSRF token or Referer header validation.
  • Prevention

    • The best way to prevent CSRF attack is to use token-based prevention
    • Using same-origin policy also works in case of CSRF
    • Another way is to have Synchronizer Tokens
    • Using Captcha.

    Visit here for detailed information on CSRF.

    Magento Hacked: Magento Remote Code Execution

    A Magento code execution is a type of attack that allows an attacker to insert malicious code into your website. This attack can

    Effect

    • Attackers can compromise your website and the web server.
    • He can view, change & delete files and databases.

    Examples

    Magento CE and EE before 2.0.10/2.1.2 were vulnerable to Remote code execution. This was dubbed as APPSEC-1484 and had a severity rating of 9.8 (critical). The cause of the vulnerability was that some payment methods allowed users to execute malicious PHP code while checking out. The exploit, as well as the Metasploit module for this vulnerability, has already been released.

    Prevention

    • Set proper parsing methods.
    • Set stricter permissions for the users.

    Magento Hacked: Other Causes

    • Weak or hard-coded credentials.
    • LFI, RFI, OWASP top 10, etc.
    • Outdated versions.
    • Server misconfigurations like open ports etc.
    • Poor hosting without subnets.

    How To Prevent Magento Store From Hacker

    Update and Backup

    Migrate to Magento 2. The Magento team updates critical flaws with each new update. This can be verified using the changelog. Moreover, avoid using unreputed extensions as they are likely to contain buggy code. Make sure to create a copy of the site. This could come in handy to restore the site after an attack. Updates and backups are the cheapest and most effective methods of securing a Magento store.

    Complete Step by Step Guide to Magento Security (Videos, Extensions, Code & Infographics) (Reduce the risk of getting hacked by 90%)

    Security Audit

    A security audit can protect the Magento store from attacks. Every Magento user cannot be an expert in security. Therefore use online services like Astra. Apart from this, Astra security audit and pen-testing can uncover severe threats present on the store. These vulnerabilities can be patched before an attacker exploits them!

    Magento Security Audit & Pentesting

    Astra Security: Magento Malware Scanner and Magento Firewall Plugin

    New vulnerabilities are uncovered in the Magento e-commerce solution each month. Though you can still keep your store safe from fraud and malware at as low as $9 per month. Buy a feasible firewall for your store. Astra is an out of box solution deployed on the cloud. This means protecting your store without using any resource-hungry anti-virus solutions. Also, average users can comfortably use Astra through a simple dashboard. Installation of Magento Firewall plugins is pretty easy and if you are still unable to figure out, Astra’s engineers got you covered. Astra firewall is the right choice for you being highly robust and scalable.

    Cleaning and restoring a hacked Magento store is at times confusing and painstaking. The solution to all these problems is automatic tools like Astra Security. The Astra Security Magento malware scanner can detect and weed out multiple signatures of malware from hacked sites within minutes. Moreover, don’t worry about the files, Astra will patch them for you.