Ewan Gardner
21 min read

Subscribe to our Blog

Like any web application, attackers will always look to exploit vulnerabilities in the underlying code before researchers can identify them and developers can fix them, but even an up-to-date and fully patched system can be left vulnerable if it is not configured properly or merchants do not follow information security best practice.

In this article, we enter the mind-set of an attacker. We will explore some possible routes to compromise a Magento site using techniques which Foregenix forensic analysts have seen exploited in the wild. Firstly, we will consider how an attacker identifies a Magento site and its weaknesses before discussing exploitation and compromise methods.

Also, we document the “Froghopper” attack which exploits a now patched vulnerability in the Magento 1 CMS. This allows attackers with access to the Magento administrative area to upload malicious PHP code into the victim’s environment. The article focuses on Magento 1, that being the most prominent version of the software in use, although some of the methods discussed still apply to Magento 2.

Reconnaissance

The first stage in an attack is to identify a website running Magento. Whilst it's possible to manually identify Magento sites by navigating to them and examining the HTML code for Magento software identifiers, there are options to automate this process.

Such services, including Shodan, a “search engine for internet devices” allows users to search for internet devices which the service has previously scanned[5]. Users can identify services those devices are running by using a variety of filters including; port numbers, operating systems or countries (based on IP geo-location). Shodan will even allow searching for specific HTML within the web page.

As Magento installations typically contain specific tags within the HTML of the websites front page, Shodan can be used to search for these specific tags. In the example in Illustration 1 below, a filter has been applied for TCP port 80 (typically used for HTTP web servers) and string “Mage.Cookies.path” within the HTML. Over 1000 results are returned, suggesting Shodan has located over 1000 accessible websites running Magento[6]. The scan summaries for two such websites (with the identifying details obfuscated) are shown.

 

Attacking-a-Magento-Store-Picture1.png

Illustration 1: Screenshot of Shodan search results for Magento sites

The results from these searches can be “manually” browsed, so the attacker can visit these sites to conduct further reconnaissance.

BuiltWith is another web service which allows users to query which sites are running Magento, as well as other technologies[7]. This site uses automated web scanning to query web pages and looks for specific files or strings associated with various applications. However, such web scanning scripts are easy to develop and therefore attackers could use their own scripts to scan websites, customised for their own needs.

CHECK YOUR SITE SECURITY HERE

Identifying Vulnerabilities

Once a Magento site has been identified, an attacker will try to determine whether that site can be attacked. A common attack vector is to attempt to “brute force” exposed administration panels; this may be the first vulnerability that an attacker will look for. Whilst the default location of the main Magento administration panel can be changed to something less obvious from the default “admin” path, sometimes administrators overlook this and the exposed panel can be browsed to by entering the site URL and then the “admin” path, as shown in Illustration 2 below.

Attacking-a-Magento-Website-Picture2.png

Illustration 2: Screenshot of an exposed Magento administration login panel

Similarly, the Magento RSS service provides endpoints which can allow access to login panels located at “/rss/order/new”, “rss/catalog/notifystock” and “rss/catalog/review”. Depending on the configuration, these RSS endpoints may be accessible even if the service is not being used (shown in Illustration 3).

Attacking-a-magento-website-picture3.pngIllustration 3: Screenshot of an exposed Magento RSS login panel

 

The last access panel commonly accessible is the “Downloader” service which allows administrators to install programs via the Magento Connect Manager. By default, this service is active and accessible at http://sitename/downloader. A screenshot of the login panel on for the Magento Connect Manager is shown in Illustration 4 below.

Attacking-a-magento-website-picture4.png

Illustration 4: Screenshot of an exposed Magento RSS Downloader login panel 

Attackers will also look to exploit known software vulnerabilities affecting older versions of Magento that may not have been patched. Rather than blindly trying these vulnerabilities it is useful to identify the specific version of Magento running, but from simply browsing a site and looking at the code within it would be difficult to identify specific vulnerable versions. However, there are some ways to find out the version number remotely.

The quickest way is to browse to the login page for the Magento Connect Manager (if available) and look at the footer of the login panel where the version for the Magento Connect Manager is included; the version number (1.8.1.0 in the example illustrated above) will usually correlate with the version of Magento running.

A more convoluted method to determine version number is by conducting hash analysis on accessible files and comparing those with files from stock Magento installation files. For example, the MD5 hash value for the “sales.js” JavaScript file from the stock Magento 1.8.1.0 Community Edition installation is:

 

       5656a8c1c646afaaf260a130fe405691

 

This version of this file is unique to Magento 1.8.1.0 Community Edition. In this example. downloading and hashing the corresponding “sales.js” file confirms it has the same hash and therefore we can conclude this site is running the same version. However, if the merchant has altered these files in any way the resulting hash will be different and automated identification via this method would not work.

Knowing the specific Magento version is extremely important as it can suggest whether this installation may be vulnerable to specific exploits. For example, Magento Community version 1.8.1.0 was released in December 2013, before many critical Magento patches were released; including the SUPRE-5344 “Shoplift” patch released in February 2015.

This patch addressed a critical SQL injection vulnerability that allows remote unauthenticated attackers to add users (or any other data) to the administration database. Whilst the administrator of this site could have patched this vulnerability separately without upgrading Magento to a newer version, this information would still prompt an attack to focus on this older and therefore potentially unprotected Magento installation.

CHECK YOUR SITE SECURITY HERE

Exploitation

Once the attacker has identified potential attack vectors, they will try to gain access to the system. Assuming the attacker has not gained credentials from another source e.g. social engineering, they may try to “brute force” exposed administration panels. They try numerous combinations of usernames and passwords until the correct one is found. This task is easier said than done, although by making educated guesses as to likely credentials and using automated scripts to cycle through combinations, this is still a potentially effective tactic.

An attacker would likely use freely available password lists (huge lists of common passwords, usually sourced from previous unrelated website breaches) in addition to guessed usernames derived from staff member names listed on the victim website. Attackers may also consider trying user names derived from victim staff members or staff members from associated third parties e.g. web developers; details of staff could be found from company websites or from third-party sites such as LinkedIn.

An example of a Python script that could be used to test credentials against an exposed Magento endpoint is shown in Table 1 below. This script iterates through a list of usernames and passwords and makes an authentication request to an exposed Magento RSS endpoint at “rss/order/new”. The script determines the status code response from the target web server and alerts the user when the attempted credentials results successful authentication to the RSS area. This is not designed to be an “attack tool” but illustrates how small and simple such a tool actually is.

import requests,time

from requests.auth import HTTPBasicAuth

 

#Set variables

base_url = "http://www.magentosite.com/"

endpoint_path = "rss/order/new"

username_list = "usernames.txt"

password_list = "passwords.txt"

success = 0

counter = 0

counter_interval = 0

interval = 100

s = requests.Session()

 

#print header

print "\nMAGENTO BRUTE FORCE DEMONSTRATION\n----------------------------------------"

print "Starting attack on %s ...\n" % (base_url+endpoint_path)

 

#start timer

time_start=time.time()

time_interval = time_start

 

#start iteration

with open(username_list,'r') as list_username:

 

  for username in list_username:

 

    username = username.replace('\n','')

 

    with open(password_list,'r') as list_password:

 

      for password in list_password:

 

        password = password.replace('\n','')

 

        #launch request

        s = requests.get(base_url+endpoint_path, auth=HTTPBasicAuth(username,password))

 

        #detect status returned

        if s.status_code!=401:

 

          success = 1

 

          print "SUCCESS: Username: %s Password: %s" % (username,password)

 

          break

 

        counter+=1

        counter_interval+=1

 

        #update code

        if counter_interval==interval:

 

          print "Tried %s combinations, rate %s combinations/s" % (str(counter),str(round(interval/(time.time()-time_interval),1)))

 

          counter_interval=0

 

          time_interval=time.time()

 

    if success==1: break

 

time_end = time.time()

 

#print footer

print "FINISHED. Tried %s combinations" % (str(counter))

print "Duration: %s seconds" % (str(round(time_end-time_start,2)))

Table 1: Example of a Python script to "brute force" credentials against an exposed Magento RSS endpoint

Illustration 5 below shows the output of this script, having been run against a test Magento site, revealing the found administrative credentials.

 

Attacking-a-magento-website-picture5.png

 

 

 

Illustration 5: Screenshot of the output message from the example Magento "brute force" script

With the verified credentials, the attacker might now be able to access the administration area and start to compromise the site in several ways based on the administration rights of the account they've obtained. Depending on the motivations of the attacker, this could be anything from simply gathering details on users to more destructive actions such as defacing the site or removing content. However, the goal for many attackers will be to obtain payment card information.

Compromise

The Magento system is a Content Management System (CMS) and therefore allows administrators to change the content of the site, including adding new products but also changing the design of pages. The CMS also enables the administrator to directly edit the HTML code of the pages, which means our attacker can not only delete content but add content too; including malicious scripts. Illustrations 6 & 7 show an example of this type of attack where a JavaScript insert has been placed in the footer section, which is then loaded on every page. In this example, a JavaScript alert box is triggered, but a JavaScript could be inserted which scrapes form data, such as from a payment card details form, and forwards it to a third party.

 Attacking-a-magento-website-picture6.png

Illustration 6: Screenshot of Magento CMS showing Javascript modification to site footer

Attacking-a-magento-website-picture7.pngIllustration 7: Screenshot showing Magento site modified with a Javascript

In this scenario, the attacker is constrained by the functionality of the Magento CMS and therefore can only change what the CMS allows - only HTML pages can be created and the attacker has no access to the underlying server file system.  This is however a real world attack and one that is seen implemented across literally hundreds of merchant sites around the world.  Foregenix along with other forensic investigators have been seeing this style of attack for about two years now.

The “Froghopper” Attack

However, in some unpatched versions of Magento 1, several vulnerabilities can be combined to allow attackers to upload files and execute them on the server to gain full control of the file system. One common attack methodology described below was nicknamed “Froghopper” by Foregenix analysts because the attackers frequently used an image file featuring a cartoon frog named ‘Pepe’ to introduce malicious code to the system.

Firstly, the attacker can use the functionality of the Magento CMS to upload a file to the system. There are several functions in the administration area which will expose this feature but in several previous attacks Foregenix forensic analysts have seen attackers uploading files by attaching an image to a Magento product category. In a typical Magento configuration, the file is uploaded and stored in the web site file system, meaning the file is publicly accessible.

To prevent arbitrary upload of any file type, Magento does validate this action and only certain file types are permissible including JPG and PNG files. However, Magento does not detect and deny files containing malicious code inserted after the image content. Using this method, any uploaded files will be placed in the “media/catalog/category” directory of the site.

In many attacks Foregenix analysts have noted this behaviour and have recovered uploaded JPG image files with malicious PHP code appended at the end. From analysis conducted on recovered uploaded malicious files, the malicious scripts will typically create a new file termed a “web shell” which is an application to enable remote administration of the machine, and therefore this initial file is commonly known as a “dropper” (as its function is to “drop” the web shell on the server). Depending on the specific functionality, a web shell may allow the user to browse and modify files on the server file system, access any accompanying databases and even allow for remote backdoor connections to be made to the compromised system.

However, the attacker does need to launch the “dropper” file, which presents a challenge. The web server interprets files by their file extension, so a file with a “PHP' extension will be passed to the PHP interpreter to run the code. But, the malicious uploaded file has a “JPG” (or PNG) extension, which was necessary to allow the upload, and therefore when the file is accessed the web server will display the initial image and ignore the PHP code at the end.

From the restricted Magento CMS environment the attacker cannot change the file extension, so must find a way to force Magento to interpret the file as raw data as opposed to just an image file. The answer lies within the Magento Newsletter functionality, which allows the creation of customer newsletters from templates, and the way in which Magento interprets the template files.

The first step in this process is to activate a Magento developer function “Allow Symlinks” for Magento Newsletter templates (found within System > Configuration > Developer). This functionality simply allows an administrator to access newsletter templates outside of the newsletter document root. As shown in Illustration 8 below, Magento does provide a warning that this setting “represents a potential security risk”, but this is a warning that an attacker is likely to ignore!

 

Attacking-a-magento-website-picture8.png

 

 

 

Illustration 8: Screenshot of the Magento "Template Settings" box from Magento 1.9.3.2

Now the attacker proceeds to the Magento “Newsletter Templates” section and creates a new newsletter template. The Magento system allows the administrator to include blocks of template code into their newsletters so, for example, they can add the “newsletter signup” module into the newsletter by including the following code snippet:

code-snippet-01.png

The file “subscribe.phtml” would be found in the “app/design/frontend/base/default/frontend/base/default/template/newsletter” path so the newsletter will default to the “app/design/frontend/base/default/frontend/base/default/template” path. However, by modifying this template path, the attacker can point to their previously uploaded file in the “media/catalog/category” directory. In the example below, the uploaded file was named “h1.jpg” so the appropriate reference would be:

code-snippet-02.png

Under normal circumstances Magento would reject this path, but because the attacker has previously enabled the “Allow Symlinks” option, it is accepted.  Now, all the attacker needs to do is view the newsletter by clicking on the “Preview Template” option. This will load the template and include any template blocks in the preview page including the malicious file. Because this template file is being interpreted by the PHP interpreter and not as an image, the raw code is activated and (in this instance) a new file is created on the web server – the web shell. The result of the newsletter template preview is shown in Illustration 9 below.

 

Attacking-a-magento-website-picture9.png

Illustration 9: Screenshot of malicious PHP script output after template preview

Most of the content is the ASCII representation of the image data but at the end is the output of the PHP script “shell ok”, a status message the attacker put into the PHP code to confirm the script has functioned correctly and the web shell has been created.

The Magento PHP code which controls this functionality is contained within “app/code/core/Mage/Core/Block/Template.php” and the function “fetchView”. The specific section of code responsible for including the specified template file is shown in Table 2 below.

try {

    $includeFilePath = realpath($this->_viewDir . DS . $fileName);

    if (strpos($includeFilePath, realpath($this->_viewDir)) === 0 || $this->_getAllowSymlinks()) {

        include $includeFilePath;

    } else {

        Mage::log('Not valid template file:'.$fileName, Zend_Log::CRIT, null, null, true);

    }

}

catch (Exception $e) {

    ob_get_clean(); throw $e;

}

Table 2: Section of PHP code from the Magento "fetchView" function

The Magento function assumes the template file will be an HTML file and no validation is done on the file type before it is included in the template. Therefore, it will allow the malicious JPG file to be included even though it is not a valid template file.

The “Froghopper” vulnerability was reported to Magento by Foregenix following the principles of responsible disclosure. A patch was released in May 2017 as part of the SUPREE-9767[8] update to address this issue, and therefore Foregenix can now report it. It affects all versions of Magento Community Edition prior to version 1.9.3.3, and Magento Enterprise Edition prior to version 1.14.3.3 if they have not been patched with the SUPREE-9767 update. So we would strongly advise the patch is applied.

Post Exploitation

In our example, the site is now compromised as the web shell dropper has been activated and the web shell created in a location specified by the attacker in the “dropper” code. The attacker can simply access this web shell and use its functionality to make any changes to the site, including modifying Magento files or uploading further malware. An example of a web shell is shown in Illustration 10 below where the user is browsing the root directory of the server.

Attacking-a-magento-website-picture10.png

Illustration 10: Screenshot showing a PHP Webshell

Common activity Foregenix analysts have seen in previous attacks include the modification of Magento checkout pages. They use form-scraping JavaScript malware or modification of server-side Magento PHP files to intercept posted payment card data. With this level of access to the compromised server, virtually anything is possible.

Defence

There is no way to hide your website from attackers (unless you want to hide it from customers as well!) but by following some simple steps, you can reduce the risk of them getting past the “front door”.

Firstly, software should be kept up to date and patches installed promptly. Attackers will quickly try to exploit vulnerabilities as soon as they are announced. They realise they have a diminishing window of opportunity, so it's important to act quickly.

Foregenix recommend website owners check the Magento security blog at https://magento.com/security regularly and sign up for Magento security alerts by email to receive notifications of patches. It is also important to have procedures in place to manage the patching process and test those patches to ensure they have been installed correctly.

Magento settings should be regularly reviewed to make sure that the configuration is appropriate for your environment. Any default settings, such as the default administration panel location, should be changed. Any unrequired services such as the Magento Connect Manager (“downloader”) or the RSS feeds should be deactivated – they can always be reactivated for short periods as required. Access to administration areas can be restricted to certain users within Magneto or restricted to specific IP addresses by manipulating web server settings.

Passwords for user accounts should be complex (at least 12 alphanumeric characters with symbols) and Two Factor authentication (which is available with some free and paid-for third-party Magento extensions) should be considered. Usernames should also be made more complex – they don't need to be email addresses or names of employees. User accounts should never be shared between employees or organisations.

If attackers do manage to breach your Magento site, effective monitoring is the key to being able to detect malicious activity and react quickly. Magento Enterprise edition has a feature to track and logs administrative actions as standard. Although the Magento Community Edition does not provide this feature, free and paid-for modules are available from the Magento store to add this functionality.

Foregenix's FGX-Web solution provides a variety of functionality including detection of malware, web shells and backdoors. It also provides alerts for website file changes. To assist merchants to maintain PCI compliance it also features automatic card scanning to alert to the presence of payment card details found on your website, which may be because of attackers “harvesting” payment card data before retrieving it later.

Conclusion

Magento enables thousands of websites, both large and small, to provide eCommerce services. The features provided have made the platform an extremely popular choice for merchants, but also for malicious attackers. The attack methodology described in this article is just one of many that Foregenix analysts have seen during their forensic investigations, but in nearly all cases, those attacks could have been prevented by merchants taking fairly basic precautions to secure their site.

Foregenix recognises that many merchants may not have the resources to effectively deal with all their information security challenges on their own, so we have a range of tools and services to help you improve your site's security. For more information visit us at https://www.foregenix.com and get in touch with our information security experts today.

 Check your site here

[1]     Estimate based on data obtained from BuiltWith (http://www.builtwith.com) on April 10th 2017.

[2]     http://gethuawei.com

[3]     https://shop.landrover.com

[4]     http://www.hellyhansen.com

[5]     https://www.shodan.io

[6]     Shodan search conducted April 4th 2017.

[7]     https://builtwith.com

[8] https://magento.com/security/patches/supee-9767

Magento is the most popular eCommerce web application in the world for advanced/fast growing eCommerce businesses, with an estimated 200,000+ live websites using the Content Management System (CMS)[1]. Available in both paid-for “enterprise” versions and free “community” versions, it powers some of the world's most popular websites including Huawai[2], Land Rover[3] and Helly Hansen[4]. However, common eCommerce platforms make popular targets for hackers and thieves looking to steal payment card information.

Contact Us

Access cybersecurity advisory services

 

Ewan Gardner
Ewan Gardner

See All Articles
SUBSCRIBE

Subscribe to our blog

Security never stops. Get the most up-to-date information by subscribing to the Foregenix blog.