Trustwave and Cybereason Merge to Form Global MDR Powerhouse for Unparalleled Cybersecurity Value. Learn More

Trustwave and Cybereason Merge to Form Global MDR Powerhouse for Unparalleled Cybersecurity Value. Learn More

Services
Managed Detection & Response

Eliminate active threats with 24/7 threat detection, investigation, and response.

Co-Managed SOC (SIEM)

Maximize your SIEM investment, stop alert fatigue, and enhance your team with hybrid security operations support.

Advisory & Diagnostics

Advance your cybersecurity program and get expert guidance where you need it most.

Penetration Testing

Test your physical locations and IT infrastructure to shore up weaknesses before exploitation.

Database Security

Prevent unauthorized access and exceed compliance requirements.

Email Security

Stop email threats others miss and secure your organization against the #1 ransomware attack vector.

Digital Forensics & Incident Response

Prepare for the inevitable with 24/7 global breach response in-region and available on-site.

Firewall & Technology Management

Mitigate risk of a cyberattack with 24/7 incident and health monitoring and the latest threat intelligence.

Solutions
BY TOPIC
Microsoft Security
Unlock the full power of Microsoft Security
Offensive Security
Solutions to maximize your security ROI
Rapidly Secure New Environments
Security for rapid response situations
Securing the Cloud
Safely navigate and stay protected
Securing the IoT Landscape
Test, monitor and secure network objects
Why Trustwave
About Us
Awards and Accolades
Trustwave SpiderLabs Team
Trustwave Fusion Security Operations Platform
Trustwave Security Colony
Partners
Technology Alliance Partners
Key alliances who align and support our ecosystem of security offerings
Trustwave PartnerOne Program
Join forces with Trustwave to protect against the most advance cybersecurity threats

Magecart - An overview and defense mechanisms

Summary

This blog post offers insight into Magecart and offers advice on how to protect your systems from this threat using a number of methods including ModSecurity WAF rules.

TL;DR, if you are already quite familiar with this threat, go ahead and skip to the Prevention and Virtual Patching sections. You can also grab a rule to improve detection and block Magecart attacks.

ModSecurity Commercial Rules customers can take advantage of a set of additional rules provided by the SpiderLabs Research Team tailored to prevent Magecart threats.

Overview

Many Content Management Systems (CMS), are being hit by attackers even harder due to the growing trend of "online skimmers" being injected into these systems to scrape credit card data and personal information, both being valuable for miscreants. There have been reports that close to 50,000 online stores were already compromised by this threat so far.

These attacks are dubbed "Magecart" probably due to the group modus operandi usually involving exploiting either known vulnerabilities or 0-days in online stores that use Magento as its backend. There are reports of Magecart being operating since at least 2015, and since then, the group has stepped up their game by making their attacks cleverer with more efficient skimmers, more pervasive attacks and, unfortunately, a better job at covering their tracks.

Magecart-logo-1

Magecart logo. Source: Google Images

Online retailers should expect that dedicated attackers could try exploiting any kind of vulnerability that allows them to either gain full control or simply upload and/or replace data on the targeted website through an XSS, RCE or LFI/RFI for instance. Maybe an innocuous and overlooked file upload functionality accessible to attackers which is not resilient against arbitrary file upload flaws, for instance, could be at a greater risk.

That being said, so far attackers seem to be focusing on the "low hanging fruits" by taking advantage of unpatched Magento installations that are vulnerable to issues such as CVE-2016-4010 which in a number of unpatched Magento installations would allow remote attackers to conduct PHP object injection attacks and execute arbitrary PHP code via crafted serialized data being fed to vulnerable websites.

To make matters worse, fully patched Magento systems might still be vulnerable due to popular extensions that were developed without taking trendy security issues into account, such as unsafe deserialization.

One of the things that made Magecart a much more pervasive threat is the fact that bad guys managed to find their way into compromising servers that hosted JavaScript code that added a given functionality to their website and checkout page/extensions. This code that is supposed to be necessary to the website and harmless to end users ended up blindly trusted by numerous websites and browsers worldwide that would load the malicious script when a page was loaded.

This was one of the reasons why major corporations such as British Airways, TicketMaster and NewEgg, ended up falling prey from these attacks. To make matters worse, there has been reports showing that infected websites are ended up becoming reinfected after hours or days since being cleaned due to MageCart operators becoming more sophisticated in hiding their tracks and applying persistence techniques through backdoors, hidden admin accounts, database "triggers" and hidden scheduled tasks to reinfect a cleaned system.

Modus Operandi

Recently a number of popular Magento extensions were found to be vulnerable to a similar issue as the one described in CVE-2016-4010. In many cases the fix for the extension could be as simple as replacing an unsafe/unsanitized user input call to the PHP unserialize() function, with something more forgiving like json_decode(). This was the case for the Made_Cache extension as can be seen on this changeset. The recommendation from PHP manual is quite clear on the dangers of reckless usage of the unserialize() function:

Unserialize1

Usage of the unserialize() function in PHP. Source: PHP online manual

In a nutshell, Magecart deployment usually starts with compromising the targeted system/website through the aforementioned issues, and then they change the website content and scripts in a way that they can embed their own skimming scripts into it in order to scrape sensitive data such as credit card and other personal data from customers.

Unsurprisingly, one of the main targets of these scripts are specifically the checkout pages of online stores where users fill their credit card data. Below is an example of such malicious script:

Magecart-1-js

JavaScript Magecart Sample. Source: SpiderLabs Threat Intelligence / Malware teams

There are a few interesting things to note about this particular script. It's a one-liner, and that variable and function names are meaningless. Looking closely one can notice that all object names start with the "_0x" prefix attached to it which suggests that these identifiers are based on hexadecimal representations. It becomes somewhat obvious that this code is obfuscated.

This specific piece of code was probably obfuscated with a tool like javascript-obfuscator. There's a web version of this tool which makes pretty easy for anyone to use it. For instance, the result of obfuscating something as trivial as console.log ("Hello World!"); in JavaScript turns out like this:

Helloworld

"Hello world" program in PHP obfuscated

We could try to make this more readable by maybe starting with decoding those hexEncoded strings there like so:

➜ ~ python -c 'print "\x6c\x6f\x67"'
log

This would obviously take a long time to decode manually, so we could write some automation to go over this code and "beautify" it to something more meaningful. Luckily there's wide availability of JavaScript beautifiers out there such as js-beautify. Also, there's a web version that we can use at beautifier.io.

If we run that first sample of obfuscated JavaScript through the beautifier, we get something more readable:

Decoded-1

De-obfuscated JavaScript Magecart Sample. Source: SpiderLabs Threat Intelligence / Malware teams

Just by glancing at this piece of JavaScript we can identify interesting stuff such as the usage of the XMLHttpRequest() to send a POST request with a fixed set of parameters that appends data from variables defined previously. Also, a URL defined at the beginning of the script that is identified as a known IOC related with Magecart.

In the way that the script is laid out, the user input, being clicks, mouse (h)overs or form fields would be skimmed, appended to a variable and them sent to a server controlled by the attackers. In this case, the entity that wrote the script decided to have the receiving end with a misleading script name that mimics a common JavaScript "slider" script.

On our quick analysis, we can also tell that the script is checking if the data worth to be skimmed by means of an if block in the end of the script checking if JavaScript's window.location object (that is used to get the current URL in the browser) matches a RegExp() that contains pay (OR) checkout (OR) onestep. These are names of popular Magento extensions used in shopping carts for checking out as is the case of oneStep.

It's important to clarify that this only one of the several "strains" of Magecart that were already found in the wild. Our intelligence data have provided a number of other variations of Magecart that checks for other extensions that contains valuable data to skim or that uses different approaches or written in other popular web programming languages such as PHP.

Prevention

The most important step to be safer from Magecart is to apply a defense in depth approach. First, make sure that all your web-server infrastructure is fully patched to their latest versions, this includes everything from operating system level patches and software all the way to the extensions and third-party code that runs as part of your website. Sadly though we know that this single approach is not enough due to a number of factors including the fact some of the extensions were not even patched yet, as the example of mageGwishlist Magento module.

But not all is lost as by disabling the extensions that are not entirely mandatory for your website to run is always a good approach to lessen exposure. Also, it is highly recommended that the most critical sections of the website (such as the checkout page) would only run the absolute minimum and taking extra precaution measures.

For instance, whenever possible, having a local copy of a script that gets loaded on the client's browser when processing that page as opposed to loading from a remote and possibly compromised location could be an easy layer of protection to adopt.

Alternatively and in addition, site owners should make every effort to adopt Content Security Policy (CSP) throughout their sites or at very least the on the critical parts (i.e., cart/checkout). Its primary goal is mitigating XSS attacks. CSP allows site owners to specify which domains the browser should consider trusted sources of scripts. A compliant browser will therefore only execute scripts loaded in source files received from those whitelisted domains, ignoring all other scripts.

Owasp-secure-headers

CSP and other Secure Headers usage. Source: OWASP Secure Headers Project

Depending on how your website is laid out, you could opt for a more strict script-src 'self' approach including any required outside domains or specific scripts using CSP Nonces. A more comprehensive approach would be hashing out the script content and validating that it has not been tampered with by using the hash-source functionality of CSP or a combination of these approaches for different parts of your website.

Another layer of defense for site owners wanting to defend from Magecart is also adopting Subresource Integrity (SRI) to make sure that the files your web application loads externally (e.g., a CDN) have not been replaced or tampered by a third-party. This requires applying a de-facto cryptographic hash algorithm (i.e., SHA-384) to calculate the hashes of all the scripts that are loaded from a third-party and then enforcing it in portions of the website, or site-wide.

With both CSP and SRI deployed, if the contents of that file ever change it will be blocked by the browser being an effective measure against attacks that involve modifying web scripts to skim data such as Magecart.

Our friend Ryan Barnett from Akamai has recently posted an in deep view of CSP and SRI, including examples on how the usage of these modern web browser security features could be effective on defending from threats like Magecart. We recommend checking it out.

Virtual Patching and more layers of defense

Deploying a WAF such as ModSecurity with a comprehensive ruleset as another layer of defense is also a good approach. Researchers at SpiderLabs have developed a set of rules in that works on different fronts to prevent exploitation to take place and also to prevent that servers already infected continue to skim more data back to the malicious actors. These are:

  1. Rules for detecting and blocking attacks on known vulnerabilities being exploited by Magecart (e.g., CVE-2016-4010);
  2. Rules that blacklists and blocks requests/responses using known malicious domains / IOCs used by Magecart;
  3. Rules that users ModSecurity’s powerful chained transformations functionality that matches for pieces of data present in the malicious codes in requests/responses;
  4. Rules based on numerous samples of Magecart scripts that use ssdeep to find CTPH hashes.

For item 1, Commercial Rules customers should only need to make sure that their SecDefaultAction is defined accordingly to either log or deny requests that trigger these rules as all rules are defined with the block action.

For items 2, 3 and 4, users should that wish to inspect requests and responses body should make sure that both SecRequestBodyAccess and SecResponseBodyAccess directives are enabled. In addition, for full inspection of responses the SecResponseBodyMimeType option needs to be configured accordingly. We recommend having the configuration set with text/plain text/html text/xml application/javascript application/octet-stream

Before wrapping up this blog post, let's talk a bit about a lesser known but very powerful feature of ModSecurity: fuzzyHash inspection (item 4).

CTPH stands for context triggered piecewise hashes. In the case of ModSecurity, this is accomplished using the ssdeep program. Also called fuzzy hashes, CTPH can match inputs that have homologies. Such inputs have sequences of identical bytes in the same order, although bytes in between these sequences may be different in both content and length.

The best example of practical fuzzy hashing usage is during forensic investigations when malware analysts want to compare unknown files with known malware families. Even if the files are different, fuzzy hashing can let you know what malware groups it is similar too and to what degree (%).

In the example below, we can see ModSecurity matching a Magecart script with the use of ssdeep:

Modsec-audit-1

Sample audit log output of one ModSecurity rules for Magecart

Behind the scenes we examine the debug_logs to see how the data is processed by the engine:

Modsec-debug-2

Sample debug log output of ModSecurity rules with the FuzzyHash operator

Those more familiar with ModSecurity would notice that the response body data is transformed a number of times and with each transformation/decode step the data is again matched with the fuzzy hash to reduce the chances of false negatives due to simple obfuscation techniques.

We are open-sourcing this experimental rule to allow that all ModSecurity users benefit from this approach to help stopping Magecart attacks:

#
# (2200005) ModSecurity Rules from Trustwave SpiderLabs: Magecart Related Code Detected in Response Body
#
SecRule REQUEST_FILENAME "@rx \.(?:js|mjs|phtml|php)$" "chain,id:2200005,\
phase:4,\
block,\
rev:'11072018',\
t:none,\
t:urlDecodeUni,\
t:lowercase,\
severity:'2',\
msg:'SLR: Magecart Related Code Detected in Response Body',\
tag:'application-magento',\
tag:'language-php',\
tag:'platform-multi',\
tag:'attack-lfi'"
SecRule RESPONSE_BODY "@fuzzyHash magecart-ssdeep-1.txt 80" "t:none,t:jsDecode,t:escapeSeqDecode,t:urlDecodeUni,multiMatch"

A sample of some of the fuzzyHashes for Magecart is available here: https://www.modsecurity.org/magecart-ssdeep-1.txt

It's important that ModSecurity users that wishes to take full advantage of this defense approach, make sure that they have a version of ModSecurity with SSDEEP support enabled. To read more about how fuzzyHash works with ModSecurity and how to enable it and create more fuzzyHashes, check out this blog post.

ABOUT TRUSTWAVE

Trustwave is a globally recognized cybersecurity leader that reduces cyber risk and fortifies organizations against disruptive and damaging cyber threats. Our comprehensive offensive and defensive cybersecurity portfolio detects what others cannot, responds with greater speed and effectiveness, optimizes client investment, and improves security resilience. Learn more about us.

Latest Intelligence

Discover how our specialists can tailor a security program to fit the needs of
your organization.

Request a Demo